@yoch/minisearch 8.0.0-beta.2

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.
@@ -0,0 +1,2949 @@
1
+ /** @ignore */
2
+ const ENTRIES = 'ENTRIES';
3
+ /** @ignore */
4
+ const KEYS = 'KEYS';
5
+ /** @ignore */
6
+ const VALUES = 'VALUES';
7
+ /** @ignore */
8
+ const LEAF = '';
9
+ /**
10
+ * @private
11
+ */
12
+ class TreeIterator {
13
+ constructor(set, type) {
14
+ const node = set._tree;
15
+ const keys = Array.from(node.keys());
16
+ this.set = set;
17
+ this._type = type;
18
+ this._path = keys.length > 0 ? [{ node, keys }] : [];
19
+ }
20
+ next() {
21
+ const value = this.dive();
22
+ this.backtrack();
23
+ return value;
24
+ }
25
+ dive() {
26
+ if (this._path.length === 0) {
27
+ return { done: true, value: undefined };
28
+ }
29
+ const { node, keys } = last$1(this._path);
30
+ if (last$1(keys) === LEAF) {
31
+ return { done: false, value: this.result() };
32
+ }
33
+ const child = node.get(last$1(keys));
34
+ this._path.push({ node: child, keys: Array.from(child.keys()) });
35
+ return this.dive();
36
+ }
37
+ backtrack() {
38
+ if (this._path.length === 0) {
39
+ return;
40
+ }
41
+ const keys = last$1(this._path).keys;
42
+ keys.pop();
43
+ if (keys.length > 0) {
44
+ return;
45
+ }
46
+ this._path.pop();
47
+ this.backtrack();
48
+ }
49
+ key() {
50
+ return this.set._prefix + this._path
51
+ .map(({ keys }) => last$1(keys))
52
+ .filter(key => key !== LEAF)
53
+ .join('');
54
+ }
55
+ value() {
56
+ return last$1(this._path).node.get(LEAF);
57
+ }
58
+ result() {
59
+ switch (this._type) {
60
+ case VALUES: return this.value();
61
+ case KEYS: return this.key();
62
+ default: return [this.key(), this.value()];
63
+ }
64
+ }
65
+ [Symbol.iterator]() {
66
+ return this;
67
+ }
68
+ }
69
+ const last$1 = (array) => {
70
+ return array[array.length - 1];
71
+ };
72
+
73
+ /* eslint-disable no-labels */
74
+ /**
75
+ * @ignore
76
+ */
77
+ const fuzzySearch = (node, query, maxDistance) => {
78
+ const results = new Map();
79
+ if (query === undefined)
80
+ return results;
81
+ // Number of columns in the Levenshtein matrix.
82
+ const n = query.length + 1;
83
+ // Matching terms can never be longer than N + maxDistance.
84
+ const m = n + maxDistance;
85
+ // Fill first matrix row and column with numbers: 0 1 2 3 ...
86
+ const matrix = new Uint8Array(m * n).fill(maxDistance + 1);
87
+ for (let j = 0; j < n; ++j)
88
+ matrix[j] = j;
89
+ for (let i = 1; i < m; ++i)
90
+ matrix[i * n] = i;
91
+ recurse(node, query, maxDistance, results, matrix, 1, n, '');
92
+ return results;
93
+ };
94
+ // Modified version of http://stevehanov.ca/blog/?id=114
95
+ // This builds a Levenshtein matrix for a given query and continuously updates
96
+ // it for nodes in the radix tree that fall within the given maximum edit
97
+ // distance. Keeping the same matrix around is beneficial especially for larger
98
+ // edit distances.
99
+ //
100
+ // k a t e <-- query
101
+ // 0 1 2 3 4
102
+ // c 1 1 2 3 4
103
+ // a 2 2 1 2 3
104
+ // t 3 3 2 1 [2] <-- edit distance
105
+ // ^
106
+ // ^ term in radix tree, rows are added and removed as needed
107
+ const recurse = (node, query, maxDistance, results, matrix, m, n, prefix) => {
108
+ const offset = m * n;
109
+ key: for (const key of node.keys()) {
110
+ if (key === LEAF) {
111
+ // We've reached a leaf node. Check if the edit distance acceptable and
112
+ // store the result if it is.
113
+ const distance = matrix[offset - 1];
114
+ if (distance <= maxDistance) {
115
+ results.set(prefix, [node.get(key), distance]);
116
+ }
117
+ }
118
+ else {
119
+ // Iterate over all characters in the key. Update the Levenshtein matrix
120
+ // and check if the minimum distance in the last row is still within the
121
+ // maximum edit distance. If it is, we can recurse over all child nodes.
122
+ let i = m;
123
+ for (let pos = 0; pos < key.length; ++pos, ++i) {
124
+ const char = key[pos];
125
+ const thisRowOffset = n * i;
126
+ const prevRowOffset = thisRowOffset - n;
127
+ // Set the first column based on the previous row, and initialize the
128
+ // minimum distance in the current row.
129
+ let minDistance = matrix[thisRowOffset];
130
+ const jmin = Math.max(0, i - maxDistance - 1);
131
+ const jmax = Math.min(n - 1, i + maxDistance);
132
+ // Iterate over remaining columns (characters in the query).
133
+ for (let j = jmin; j < jmax; ++j) {
134
+ const different = char !== query[j];
135
+ // It might make sense to only read the matrix positions used for
136
+ // deletion/insertion if the characters are different. But we want to
137
+ // avoid conditional reads for performance reasons.
138
+ const rpl = matrix[prevRowOffset + j] + +different;
139
+ const del = matrix[prevRowOffset + j + 1] + 1;
140
+ const ins = matrix[thisRowOffset + j] + 1;
141
+ const dist = matrix[thisRowOffset + j + 1] = Math.min(rpl, del, ins);
142
+ if (dist < minDistance)
143
+ minDistance = dist;
144
+ }
145
+ // Because distance will never decrease, we can stop. There will be no
146
+ // matching child nodes.
147
+ if (minDistance > maxDistance) {
148
+ continue key;
149
+ }
150
+ }
151
+ recurse(node.get(key), query, maxDistance, results, matrix, i, n, prefix + key);
152
+ }
153
+ }
154
+ };
155
+
156
+ /* eslint-disable no-labels */
157
+ /**
158
+ * A class implementing the same interface as a standard JavaScript
159
+ * [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
160
+ * with string keys, but adding support for efficiently searching entries with
161
+ * prefix or fuzzy search. This class is used internally by {@link MiniSearch}
162
+ * as the inverted index data structure. The implementation is a radix tree
163
+ * (compressed prefix tree).
164
+ *
165
+ * Since this class can be of general utility beyond _MiniSearch_, it is
166
+ * internal to `@yoch/minisearch` (not a separate public entry point).
167
+ *
168
+ * @typeParam T The type of the values stored in the map.
169
+ */
170
+ class SearchableMap {
171
+ /**
172
+ * The constructor is normally called without arguments, creating an empty
173
+ * map. In order to create a {@link SearchableMap} from an iterable or from an
174
+ * object, check {@link SearchableMap.from} and {@link
175
+ * SearchableMap.fromObject}.
176
+ *
177
+ * The constructor arguments are for internal use, when creating derived
178
+ * mutable views of a map at a prefix.
179
+ */
180
+ constructor(tree = new Map(), prefix = '') {
181
+ this._size = undefined;
182
+ this._tree = tree;
183
+ this._prefix = prefix;
184
+ }
185
+ /**
186
+ * Root radix tree backing this map. Used when cloning or serializing the full
187
+ * index so {@link Map} key insertion order (prefix / fuzzy / autoSuggest) is preserved.
188
+ */
189
+ get radixTree() {
190
+ return this._tree;
191
+ }
192
+ /**
193
+ * Creates and returns a mutable view of this {@link SearchableMap},
194
+ * containing only entries that share the given prefix.
195
+ *
196
+ * ### Usage:
197
+ *
198
+ * ```javascript
199
+ * let map = new SearchableMap()
200
+ * map.set("unicorn", 1)
201
+ * map.set("universe", 2)
202
+ * map.set("university", 3)
203
+ * map.set("unique", 4)
204
+ * map.set("hello", 5)
205
+ *
206
+ * let uni = map.atPrefix("uni")
207
+ * uni.get("unique") // => 4
208
+ * uni.get("unicorn") // => 1
209
+ * uni.get("hello") // => undefined
210
+ *
211
+ * let univer = map.atPrefix("univer")
212
+ * univer.get("unique") // => undefined
213
+ * univer.get("universe") // => 2
214
+ * univer.get("university") // => 3
215
+ * ```
216
+ *
217
+ * @param prefix The prefix
218
+ * @return A {@link SearchableMap} representing a mutable view of the original
219
+ * Map at the given prefix
220
+ */
221
+ atPrefix(prefix) {
222
+ if (!prefix.startsWith(this._prefix)) {
223
+ throw new Error('Mismatched prefix');
224
+ }
225
+ const [node, path] = trackDown(this._tree, prefix.slice(this._prefix.length));
226
+ if (node === undefined) {
227
+ const [parentNode, key] = last(path);
228
+ for (const k of parentNode.keys()) {
229
+ if (k !== LEAF && k.startsWith(key)) {
230
+ const node = new Map();
231
+ node.set(k.slice(key.length), parentNode.get(k));
232
+ return new SearchableMap(node, prefix);
233
+ }
234
+ }
235
+ }
236
+ return new SearchableMap(node, prefix);
237
+ }
238
+ /**
239
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/clear
240
+ */
241
+ clear() {
242
+ this._size = undefined;
243
+ this._tree.clear();
244
+ }
245
+ /**
246
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/delete
247
+ * @param key Key to delete
248
+ */
249
+ delete(key) {
250
+ this._size = undefined;
251
+ return remove(this._tree, key);
252
+ }
253
+ /**
254
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries
255
+ * @return An iterator iterating through `[key, value]` entries.
256
+ */
257
+ entries() {
258
+ return new TreeIterator(this, ENTRIES);
259
+ }
260
+ /**
261
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach
262
+ * @param fn Iteration function
263
+ */
264
+ forEach(fn) {
265
+ for (const [key, value] of this) {
266
+ fn(key, value, this);
267
+ }
268
+ }
269
+ /**
270
+ * Returns a Map of all the entries that have a key within the given edit
271
+ * distance from the search key. The keys of the returned Map are the matching
272
+ * keys, while the values are two-element arrays where the first element is
273
+ * the value associated to the key, and the second is the edit distance of the
274
+ * key to the search key.
275
+ *
276
+ * ### Usage:
277
+ *
278
+ * ```javascript
279
+ * let map = new SearchableMap()
280
+ * map.set('hello', 'world')
281
+ * map.set('hell', 'yeah')
282
+ * map.set('ciao', 'mondo')
283
+ *
284
+ * // Get all entries that match the key 'hallo' with a maximum edit distance of 2
285
+ * map.fuzzyGet('hallo', 2)
286
+ * // => Map(2) { 'hello' => ['world', 1], 'hell' => ['yeah', 2] }
287
+ *
288
+ * // In the example, the "hello" key has value "world" and edit distance of 1
289
+ * // (change "e" to "a"), the key "hell" has value "yeah" and edit distance of 2
290
+ * // (change "e" to "a", delete "o")
291
+ * ```
292
+ *
293
+ * @param key The search key
294
+ * @param maxEditDistance The maximum edit distance (Levenshtein)
295
+ * @return A Map of the matching keys to their value and edit distance
296
+ */
297
+ fuzzyGet(key, maxEditDistance) {
298
+ return fuzzySearch(this._tree, key, maxEditDistance);
299
+ }
300
+ /**
301
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get
302
+ * @param key Key to get
303
+ * @return Value associated to the key, or `undefined` if the key is not
304
+ * found.
305
+ */
306
+ get(key) {
307
+ const node = lookup(this._tree, key);
308
+ return node !== undefined ? node.get(LEAF) : undefined;
309
+ }
310
+ /**
311
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has
312
+ * @param key Key
313
+ * @return True if the key is in the map, false otherwise
314
+ */
315
+ has(key) {
316
+ const node = lookup(this._tree, key);
317
+ return node !== undefined && node.has(LEAF);
318
+ }
319
+ /**
320
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys
321
+ * @return An `Iterable` iterating through keys
322
+ */
323
+ keys() {
324
+ return new TreeIterator(this, KEYS);
325
+ }
326
+ /**
327
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/set
328
+ * @param key Key to set
329
+ * @param value Value to associate to the key
330
+ * @return The {@link SearchableMap} itself, to allow chaining
331
+ */
332
+ set(key, value) {
333
+ if (typeof key !== 'string') {
334
+ throw new Error('key must be a string');
335
+ }
336
+ this._size = undefined;
337
+ const node = createPath(this._tree, key);
338
+ node.set(LEAF, value);
339
+ return this;
340
+ }
341
+ /**
342
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/size
343
+ */
344
+ get size() {
345
+ if (this._size) {
346
+ return this._size;
347
+ }
348
+ /** @ignore */
349
+ this._size = 0;
350
+ const iter = this.entries();
351
+ while (!iter.next().done)
352
+ this._size += 1;
353
+ return this._size;
354
+ }
355
+ /**
356
+ * Updates the value at the given key using the provided function. The function
357
+ * is called with the current value at the key, and its return value is used as
358
+ * the new value to be set.
359
+ *
360
+ * ### Example:
361
+ *
362
+ * ```javascript
363
+ * // Increment the current value by one
364
+ * searchableMap.update('somekey', (currentValue) => currentValue == null ? 0 : currentValue + 1)
365
+ * ```
366
+ *
367
+ * If the value at the given key is or will be an object, it might not require
368
+ * re-assignment. In that case it is better to use `fetch()`, because it is
369
+ * faster.
370
+ *
371
+ * @param key The key to update
372
+ * @param fn The function used to compute the new value from the current one
373
+ * @return The {@link SearchableMap} itself, to allow chaining
374
+ */
375
+ update(key, fn) {
376
+ if (typeof key !== 'string') {
377
+ throw new Error('key must be a string');
378
+ }
379
+ this._size = undefined;
380
+ const node = createPath(this._tree, key);
381
+ node.set(LEAF, fn(node.get(LEAF)));
382
+ return this;
383
+ }
384
+ /**
385
+ * Fetches the value of the given key. If the value does not exist, calls the
386
+ * given function to create a new value, which is inserted at the given key
387
+ * and subsequently returned.
388
+ *
389
+ * ### Example:
390
+ *
391
+ * ```javascript
392
+ * const map = searchableMap.fetch('somekey', () => new Map())
393
+ * map.set('foo', 'bar')
394
+ * ```
395
+ *
396
+ * @param key The key to update
397
+ * @param initial A function that creates a new value if the key does not exist
398
+ * @return The existing or new value at the given key
399
+ */
400
+ fetch(key, initial) {
401
+ if (typeof key !== 'string') {
402
+ throw new Error('key must be a string');
403
+ }
404
+ this._size = undefined;
405
+ const node = createPath(this._tree, key);
406
+ let value = node.get(LEAF);
407
+ if (value === undefined) {
408
+ node.set(LEAF, value = initial());
409
+ }
410
+ return value;
411
+ }
412
+ /**
413
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/values
414
+ * @return An `Iterable` iterating through values.
415
+ */
416
+ values() {
417
+ return new TreeIterator(this, VALUES);
418
+ }
419
+ /**
420
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator
421
+ */
422
+ [Symbol.iterator]() {
423
+ return this.entries();
424
+ }
425
+ /**
426
+ * Creates a {@link SearchableMap} from an `Iterable` of entries
427
+ *
428
+ * @param entries Entries to be inserted in the {@link SearchableMap}
429
+ * @return A new {@link SearchableMap} with the given entries
430
+ */
431
+ static from(entries) {
432
+ const tree = new SearchableMap();
433
+ for (const [key, value] of entries) {
434
+ tree.set(key, value);
435
+ }
436
+ return tree;
437
+ }
438
+ /**
439
+ * Creates a {@link SearchableMap} from the iterable properties of a JavaScript object
440
+ *
441
+ * @param object Object of entries for the {@link SearchableMap}
442
+ * @return A new {@link SearchableMap} with the given entries
443
+ */
444
+ static fromObject(object) {
445
+ return SearchableMap.from(Object.entries(object));
446
+ }
447
+ }
448
+ const trackDown = (tree, key, path = []) => {
449
+ if (key.length === 0 || tree == null) {
450
+ return [tree, path];
451
+ }
452
+ for (const k of tree.keys()) {
453
+ if (k !== LEAF && key.startsWith(k)) {
454
+ path.push([tree, k]); // performance: update in place
455
+ return trackDown(tree.get(k), key.slice(k.length), path);
456
+ }
457
+ }
458
+ path.push([tree, key]); // performance: update in place
459
+ return trackDown(undefined, '', path);
460
+ };
461
+ const lookup = (tree, key) => {
462
+ if (key.length === 0 || tree == null) {
463
+ return tree;
464
+ }
465
+ for (const k of tree.keys()) {
466
+ if (k !== LEAF && key.startsWith(k)) {
467
+ return lookup(tree.get(k), key.slice(k.length));
468
+ }
469
+ }
470
+ };
471
+ // Create a path in the radix tree for the given key, and returns the deepest
472
+ // node. This function is in the hot path for indexing. It avoids unnecessary
473
+ // string operations and recursion for performance.
474
+ const createPath = (node, key) => {
475
+ const keyLength = key.length;
476
+ outer: for (let pos = 0; node && pos < keyLength;) {
477
+ for (const k of node.keys()) {
478
+ // Check whether this key is a candidate: the first characters must match.
479
+ if (k !== LEAF && key[pos] === k[0]) {
480
+ const len = Math.min(keyLength - pos, k.length);
481
+ // Advance offset to the point where key and k no longer match.
482
+ let offset = 1;
483
+ while (offset < len && key[pos + offset] === k[offset])
484
+ ++offset;
485
+ const child = node.get(k);
486
+ if (offset === k.length) {
487
+ // The existing key is shorter than the key we need to create.
488
+ node = child;
489
+ }
490
+ else {
491
+ // Partial match: we need to insert an intermediate node to contain
492
+ // both the existing subtree and the new node.
493
+ const intermediate = new Map();
494
+ intermediate.set(k.slice(offset), child);
495
+ node.set(key.slice(pos, pos + offset), intermediate);
496
+ node.delete(k);
497
+ node = intermediate;
498
+ }
499
+ pos += offset;
500
+ continue outer;
501
+ }
502
+ }
503
+ // Create a final child node to contain the final suffix of the key.
504
+ const child = new Map();
505
+ node.set(key.slice(pos), child);
506
+ return child;
507
+ }
508
+ return node;
509
+ };
510
+ const remove = (tree, key) => {
511
+ const [node, path] = trackDown(tree, key);
512
+ if (node === undefined) {
513
+ return;
514
+ }
515
+ node.delete(LEAF);
516
+ if (node.size === 0) {
517
+ cleanup(path);
518
+ }
519
+ else if (node.size === 1) {
520
+ const [key, value] = node.entries().next().value;
521
+ merge(path, key, value);
522
+ }
523
+ };
524
+ const cleanup = (path) => {
525
+ if (path.length === 0) {
526
+ return;
527
+ }
528
+ const [node, key] = last(path);
529
+ node.delete(key);
530
+ if (node.size === 0) {
531
+ cleanup(path.slice(0, -1));
532
+ }
533
+ else if (node.size === 1) {
534
+ const [key, value] = node.entries().next().value;
535
+ if (key !== LEAF) {
536
+ merge(path.slice(0, -1), key, value);
537
+ }
538
+ }
539
+ };
540
+ const merge = (path, key, value) => {
541
+ if (path.length === 0) {
542
+ return;
543
+ }
544
+ const [node, nodeKey] = last(path);
545
+ node.set(nodeKey + key, value);
546
+ node.delete(nodeKey);
547
+ };
548
+ const last = (array) => {
549
+ return array[array.length - 1];
550
+ };
551
+
552
+ const OR = 'or';
553
+ const AND = 'and';
554
+ const AND_NOT = 'and_not';
555
+ const defaultBM25params = { k: 1.2, b: 0.7, d: 0.5 };
556
+ const calcBM25Score = (termFreq, matchingCount, totalCount, fieldLength, avgFieldLength, bm25params) => {
557
+ const { k, b, d } = bm25params;
558
+ const invDocFreq = Math.log(1 + (totalCount - matchingCount + 0.5) / (matchingCount + 0.5));
559
+ return invDocFreq * (d + termFreq * (k + 1) / (termFreq + k * (1 - b + b * fieldLength / avgFieldLength)));
560
+ };
561
+ const getOwnProperty = (object, property) => Object.prototype.hasOwnProperty.call(object, property) ? object[property] : undefined;
562
+ const assignUniqueTerm = (target, term) => {
563
+ if (!target.includes(term))
564
+ target.push(term);
565
+ };
566
+ const assignUniqueTerms = (target, source) => {
567
+ for (const term of source) {
568
+ if (!target.includes(term))
569
+ target.push(term);
570
+ }
571
+ };
572
+ const byScore = ({ score: a }, { score: b }) => b - a;
573
+ /** Wrap Map<shortId, freq> as PostingListLike */
574
+ function mapPostingList(freqs) {
575
+ return {
576
+ get size() { return freqs.size; },
577
+ forEachDoc(callback) {
578
+ for (const [docId, termFreq] of freqs) {
579
+ callback(docId, termFreq);
580
+ }
581
+ }
582
+ };
583
+ }
584
+ /** Wrap Map<fieldId, Map<shortId, freq>> as FieldTermDataLike */
585
+ function mapFieldTermData(data) {
586
+ return {
587
+ get(fieldId) {
588
+ const freqs = data.get(fieldId);
589
+ return freqs == null ? undefined : mapPostingList(freqs);
590
+ }
591
+ };
592
+ }
593
+ function aggregateTerm(sourceTerm, derivedTerm, termWeight, termBoost, fieldTermData, fieldBoosts, context, boostDocumentFn, bm25params, results = new Map()) {
594
+ if (fieldTermData == null)
595
+ return results;
596
+ for (const field of Object.keys(fieldBoosts)) {
597
+ const fieldBoost = fieldBoosts[field];
598
+ const fieldId = context.fieldIds[field];
599
+ const postingList = fieldTermData.get(fieldId);
600
+ if (postingList == null)
601
+ continue;
602
+ let matchingFields = postingList.size;
603
+ const avgFieldLength = context.avgFieldLength[fieldId];
604
+ postingList.forEachDoc((docId, termFreq) => {
605
+ var _a;
606
+ if (context.isDocActive != null && !context.isDocActive(docId)) {
607
+ (_a = context.onInactiveDoc) === null || _a === void 0 ? void 0 : _a.call(context, docId, fieldId, derivedTerm);
608
+ matchingFields -= 1;
609
+ return;
610
+ }
611
+ const docBoost = boostDocumentFn
612
+ ? boostDocumentFn(context.getExternalId(docId), derivedTerm, context.getStoredFields(docId))
613
+ : 1;
614
+ if (!docBoost)
615
+ return;
616
+ const fieldLength = context.getFieldLength(docId, fieldId);
617
+ const rawScore = calcBM25Score(termFreq, matchingFields, context.documentCount, fieldLength, avgFieldLength, bm25params);
618
+ const weightedScore = termWeight * termBoost * fieldBoost * docBoost * rawScore;
619
+ const result = results.get(docId);
620
+ if (result) {
621
+ result.score += weightedScore;
622
+ assignUniqueTerm(result.terms, sourceTerm);
623
+ const match = getOwnProperty(result.match, derivedTerm);
624
+ if (match) {
625
+ match.push(field);
626
+ }
627
+ else {
628
+ result.match[derivedTerm] = [field];
629
+ }
630
+ }
631
+ else {
632
+ results.set(docId, {
633
+ score: weightedScore,
634
+ terms: [sourceTerm],
635
+ match: { [derivedTerm]: [field] }
636
+ });
637
+ }
638
+ });
639
+ }
640
+ return results;
641
+ }
642
+ const combinators = {
643
+ [OR]: (a, b) => {
644
+ for (const docId of b.keys()) {
645
+ const existing = a.get(docId);
646
+ if (existing == null) {
647
+ a.set(docId, b.get(docId));
648
+ }
649
+ else {
650
+ const { score, terms, match } = b.get(docId);
651
+ existing.score = existing.score + score;
652
+ existing.match = Object.assign(existing.match, match);
653
+ assignUniqueTerms(existing.terms, terms);
654
+ }
655
+ }
656
+ return a;
657
+ },
658
+ [AND]: (a, b) => {
659
+ const combined = new Map();
660
+ for (const docId of b.keys()) {
661
+ const existing = a.get(docId);
662
+ if (existing == null)
663
+ continue;
664
+ const { score, terms, match } = b.get(docId);
665
+ assignUniqueTerms(existing.terms, terms);
666
+ combined.set(docId, {
667
+ score: existing.score + score,
668
+ terms: existing.terms,
669
+ match: Object.assign(existing.match, match)
670
+ });
671
+ }
672
+ return combined;
673
+ },
674
+ [AND_NOT]: (a, b) => {
675
+ for (const docId of b.keys())
676
+ a.delete(docId);
677
+ return a;
678
+ }
679
+ };
680
+ function combineResults(results, combineWith = OR) {
681
+ if (results.length === 0)
682
+ return new Map();
683
+ const operator = combineWith.toLowerCase();
684
+ const combinator = combinators[operator];
685
+ if (!combinator) {
686
+ throw new Error(`Invalid combination operator: ${combineWith}`);
687
+ }
688
+ return results.reduce(combinator) || new Map();
689
+ }
690
+ function finalizeSearchResults(params) {
691
+ const { rawResults, getExternalId, getStoredFields, filter, skipSort } = params;
692
+ const results = [];
693
+ for (const [docId, { score, terms, match }] of rawResults) {
694
+ const quality = terms.length || 1;
695
+ const result = {
696
+ id: getExternalId(docId),
697
+ score: score * quality,
698
+ terms: Object.keys(match),
699
+ queryTerms: terms,
700
+ match
701
+ };
702
+ Object.assign(result, getStoredFields(docId));
703
+ if (filter == null || filter(result)) {
704
+ results.push(result);
705
+ }
706
+ }
707
+ if (!skipSort) {
708
+ results.sort(byScore);
709
+ }
710
+ return results;
711
+ }
712
+ const termToQuerySpec = (options) => (term, i, terms) => {
713
+ const fuzzy = (typeof options.fuzzy === 'function')
714
+ ? options.fuzzy(term, i, terms)
715
+ : (options.fuzzy || false);
716
+ const prefix = (typeof options.prefix === 'function')
717
+ ? options.prefix(term, i, terms)
718
+ : (options.prefix === true);
719
+ const termBoost = (typeof options.boostTerm === 'function')
720
+ ? options.boostTerm(term, i, terms)
721
+ : 1;
722
+ return { term, fuzzy, prefix, termBoost };
723
+ };
724
+
725
+ const MAX_FREQ_UINT8 = 255;
726
+ /** View into global flat posting buffers (no per-list allocation). */
727
+ class SegmentPostingList {
728
+ constructor(docIds, freqs, offset, length) {
729
+ this._docIds = docIds;
730
+ this._freqs = freqs;
731
+ this._offset = offset;
732
+ this._length = length;
733
+ }
734
+ get size() {
735
+ return this._length;
736
+ }
737
+ forEachDoc(callback) {
738
+ const { _docIds, _freqs, _offset, _length } = this;
739
+ for (let i = 0; i < _length; i++) {
740
+ callback(_docIds[_offset + i], _freqs[_offset + i]);
741
+ }
742
+ }
743
+ }
744
+ /**
745
+ * Clamp term frequency to Uint8 for flat storage.
746
+ * This intentionally caps tf at 255 in frozen indexes; see benchmark scenario
747
+ * \"overflow frequencies\" to quantify the score drift for very large tf values.
748
+ */
749
+ function clampFreq(freq) {
750
+ return freq > MAX_FREQ_UINT8 ? MAX_FREQ_UINT8 : freq;
751
+ }
752
+ function flatFieldTermData(termIndex, fieldCount, postingsOffsets, postingsLengths, allDocIds, allFreqs) {
753
+ const base = termIndex * fieldCount;
754
+ return {
755
+ get(fieldId) {
756
+ const len = postingsLengths[base + fieldId];
757
+ if (len === 0)
758
+ return undefined;
759
+ const off = postingsOffsets[base + fieldId];
760
+ return new SegmentPostingList(allDocIds, allFreqs, off, len);
761
+ }
762
+ };
763
+ }
764
+
765
+ /** Unicode space, newline, or punctuation — used by the default tokenizer */
766
+ const SPACE_OR_PUNCTUATION = /[\n\r\p{Z}\p{P}]+/u;
767
+ const defaultSearchOptions = {
768
+ combineWith: OR,
769
+ prefix: false,
770
+ fuzzy: false,
771
+ maxFuzzy: 6,
772
+ boost: {},
773
+ weights: { fuzzy: 0.45, prefix: 0.375 },
774
+ bm25: defaultBM25params
775
+ };
776
+ const defaultAutoSuggestOptions = {
777
+ combineWith: AND,
778
+ prefix: (term, i, terms) => i === terms.length - 1
779
+ };
780
+ /** Option defaults applied by {@link FrozenMiniSearch.loadBinary} before caller overrides */
781
+ const defaultFrozenLoadOptions = {
782
+ idField: 'id',
783
+ extractField: (document, fieldName) => document[fieldName],
784
+ stringifyField: (fieldValue) => fieldValue.toString(),
785
+ tokenize: (text) => text.split(SPACE_OR_PUNCTUATION),
786
+ processTerm: (term) => term.toLowerCase(),
787
+ storeFields: [],
788
+ logger: () => { },
789
+ autoVacuum: false
790
+ };
791
+
792
+ const BINARY_MAGIC_V1 = 'MSv1';
793
+ const BINARY_VERSION_V1 = 1;
794
+ const BINARY_MAGIC_V2 = 'MSv2';
795
+ const BINARY_VERSION_V2 = 2;
796
+ const HEADER_SIZE_V2 = 48;
797
+ const FREQ_UINT8 = 0;
798
+ const FREQ_UINT16 = 1;
799
+ function copyView(view) {
800
+ return Buffer.from(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));
801
+ }
802
+ function alignedSlice(buf, offset, length, alignment) {
803
+ if (length === 0)
804
+ return Buffer.alloc(0);
805
+ if (offset % alignment === 0) {
806
+ return buf.subarray(offset, offset + length);
807
+ }
808
+ return buf.subarray(offset, offset + length);
809
+ }
810
+ function readUint32Array(buf, offset, byteLength) {
811
+ if (byteLength === 0)
812
+ return new Uint32Array(0);
813
+ const slice = alignedSlice(buf, offset, byteLength, 4);
814
+ if (slice.byteOffset % 4 === 0 && slice.length === byteLength) {
815
+ return new Uint32Array(slice.buffer, slice.byteOffset, byteLength / 4);
816
+ }
817
+ const out = new Uint32Array(byteLength / 4);
818
+ for (let i = 0; i < out.length; i++)
819
+ out[i] = buf.readUInt32LE(offset + i * 4);
820
+ return out;
821
+ }
822
+ function readUint8Array(buf, offset, byteLength) {
823
+ if (byteLength === 0)
824
+ return new Uint8Array(0);
825
+ const slice = alignedSlice(buf, offset, byteLength, 1);
826
+ return new Uint8Array(slice.buffer, slice.byteOffset, byteLength);
827
+ }
828
+ function readFloat32Array(buf, offset, byteLength) {
829
+ if (byteLength === 0)
830
+ return new Float32Array(0);
831
+ const slice = alignedSlice(buf, offset, byteLength, 4);
832
+ if (slice.byteOffset % 4 === 0 && slice.length === byteLength) {
833
+ return new Float32Array(slice.buffer, slice.byteOffset, byteLength / 4);
834
+ }
835
+ const out = new Float32Array(byteLength / 4);
836
+ for (let i = 0; i < out.length; i++)
837
+ out[i] = buf.readFloatLE(offset + i * 4);
838
+ return out;
839
+ }
840
+ function encodeFrozenSnapshot(snap) {
841
+ const metaJson = Buffer.from(JSON.stringify({
842
+ documentCount: snap.documentCount,
843
+ nextId: snap.nextId,
844
+ fieldCount: snap.fieldCount,
845
+ fieldIds: snap.fieldIds,
846
+ externalIds: snap.externalIds,
847
+ storedFields: snap.storedFields,
848
+ treeShape: snap.treeShape
849
+ }), 'utf8');
850
+ const avgBuf = copyView(snap.avgFieldLength);
851
+ const flBuf = copyView(snap.fieldLengthMatrix);
852
+ const termBufs = snap.terms.map((term) => Buffer.from(term, 'utf8'));
853
+ const dictHeader = Buffer.alloc(4 + snap.terms.length * 4);
854
+ dictHeader.writeUInt32LE(snap.terms.length, 0);
855
+ for (let i = 0; i < termBufs.length; i++) {
856
+ dictHeader.writeUInt32LE(termBufs[i].length, 4 + i * 4);
857
+ }
858
+ const dict = Buffer.concat([dictHeader, ...termBufs]);
859
+ const offBuf = copyView(snap.postingsOffsets);
860
+ const lenBuf = copyView(snap.postingsLengths);
861
+ const docBuf = copyView(snap.allDocIds);
862
+ const freqBuf = copyView(snap.allFreqs);
863
+ const sections = [metaJson, avgBuf, flBuf, dict, offBuf, lenBuf, docBuf, freqBuf];
864
+ const header = Buffer.alloc(HEADER_SIZE_V2);
865
+ header.write(BINARY_MAGIC_V2, 0, 4, 'ascii');
866
+ header.writeUInt16LE(BINARY_VERSION_V2, 4);
867
+ header.writeUInt16LE(0, 6);
868
+ let off = HEADER_SIZE_V2;
869
+ for (let i = 0; i < sections.length; i++) {
870
+ header.writeUInt32LE(off, 8 + i * 4);
871
+ off += sections[i].length;
872
+ }
873
+ header.writeUInt32LE(off, 8 + sections.length * 4);
874
+ return Buffer.concat([header, ...sections]);
875
+ }
876
+ function decodeMSv2(buf) {
877
+ const metaOff = buf.readUInt32LE(8);
878
+ const avgOff = buf.readUInt32LE(12);
879
+ const flOff = buf.readUInt32LE(16);
880
+ const dictOff = buf.readUInt32LE(20);
881
+ const postOffOff = buf.readUInt32LE(24);
882
+ const postLenOff = buf.readUInt32LE(28);
883
+ const docIdsOff = buf.readUInt32LE(32);
884
+ const freqsOff = buf.readUInt32LE(36);
885
+ const endOff = buf.readUInt32LE(40);
886
+ const meta = JSON.parse(buf.toString('utf8', metaOff, avgOff));
887
+ const avgFieldLength = readFloat32Array(buf, avgOff, flOff - avgOff);
888
+ const fieldLengthMatrix = readUint32Array(buf, flOff, dictOff - flOff);
889
+ const termCount = buf.readUInt32LE(dictOff);
890
+ const terms = [];
891
+ let o = dictOff + 4 + termCount * 4;
892
+ for (let i = 0; i < termCount; i++) {
893
+ const len = buf.readUInt32LE(dictOff + 4 + i * 4);
894
+ terms.push(buf.toString('utf8', o, o + len));
895
+ o += len;
896
+ }
897
+ const slotCount = termCount * meta.fieldCount;
898
+ const postingsOffsets = readUint32Array(buf, postOffOff, slotCount * 4);
899
+ const postingsLengths = readUint32Array(buf, postLenOff, slotCount * 4);
900
+ const allDocIds = readUint32Array(buf, docIdsOff, freqsOff - docIdsOff);
901
+ const allFreqs = readUint8Array(buf, freqsOff, endOff - freqsOff);
902
+ return {
903
+ documentCount: meta.documentCount,
904
+ nextId: meta.nextId,
905
+ fieldIds: meta.fieldIds,
906
+ fieldCount: meta.fieldCount,
907
+ avgFieldLength,
908
+ externalIds: meta.externalIds,
909
+ storedFields: meta.storedFields,
910
+ fieldLengthMatrix,
911
+ terms,
912
+ treeShape: meta.treeShape,
913
+ postingsOffsets,
914
+ postingsLengths,
915
+ allDocIds,
916
+ allFreqs
917
+ };
918
+ }
919
+ function decodeMSv1(buf) {
920
+ const metaOff = buf.readUInt32LE(8);
921
+ const avgOff = buf.readUInt32LE(12);
922
+ const flOff = buf.readUInt32LE(16);
923
+ const dictOff = buf.readUInt32LE(20);
924
+ const postOff = buf.readUInt32LE(24);
925
+ const meta = JSON.parse(buf.toString('utf8', metaOff, avgOff));
926
+ const avgFieldLength = readFloat32Array(buf, avgOff, flOff - avgOff);
927
+ const fieldLengthMatrix = readUint32Array(buf, flOff, dictOff - flOff);
928
+ const termCount = buf.readUInt32LE(dictOff);
929
+ const terms = [];
930
+ let o = dictOff + 4 + termCount * 4;
931
+ for (let i = 0; i < termCount; i++) {
932
+ const len = buf.readUInt32LE(dictOff + 4 + i * 4);
933
+ terms.push(buf.toString('utf8', o, o + len));
934
+ o += len;
935
+ }
936
+ const fieldCount = meta.fieldCount;
937
+ const slotCount = termCount * fieldCount;
938
+ const postingsOffsets = new Uint32Array(slotCount);
939
+ const postingsLengths = new Uint32Array(slotCount);
940
+ const docIdChunks = [];
941
+ const freqChunks = [];
942
+ o = postOff;
943
+ for (let ti = 0; ti < termCount; ti++) {
944
+ const fc = buf.readUInt16LE(o);
945
+ o += 2;
946
+ const base = ti * fieldCount;
947
+ for (let f = 0; f < fc; f++) {
948
+ buf.readUInt32LE(o);
949
+ o += 4; // matchCount — same as docLen
950
+ const docLen = buf.readUInt32LE(o);
951
+ o += 4;
952
+ postingsLengths[base + f] = docLen;
953
+ if (docLen === 0) {
954
+ postingsOffsets[base + f] = 0;
955
+ o += 1;
956
+ continue;
957
+ }
958
+ postingsOffsets[base + f] = docIdChunks.length;
959
+ const kind = buf.readUInt8(o);
960
+ o += 1;
961
+ for (let d = 0; d < docLen; d++) {
962
+ docIdChunks.push(buf.readUInt32LE(o + d * 4));
963
+ }
964
+ o += docLen * 4;
965
+ const freqElem = kind === FREQ_UINT8 ? 1 : kind === FREQ_UINT16 ? 2 : 4;
966
+ for (let d = 0; d < docLen; d++) {
967
+ let freq;
968
+ if (kind === FREQ_UINT8)
969
+ freq = buf.readUInt8(o + d);
970
+ else if (kind === FREQ_UINT16)
971
+ freq = buf.readUInt16LE(o + d * 2);
972
+ else
973
+ freq = buf.readUInt32LE(o + d * 4);
974
+ freqChunks.push(freq > 255 ? 255 : freq);
975
+ }
976
+ o += docLen * freqElem;
977
+ }
978
+ }
979
+ return {
980
+ documentCount: meta.documentCount,
981
+ nextId: meta.nextId,
982
+ fieldIds: meta.fieldIds,
983
+ fieldCount,
984
+ avgFieldLength,
985
+ externalIds: meta.externalIds,
986
+ storedFields: meta.storedFields,
987
+ fieldLengthMatrix,
988
+ terms,
989
+ treeShape: meta.treeShape,
990
+ postingsOffsets,
991
+ postingsLengths,
992
+ allDocIds: new Uint32Array(docIdChunks),
993
+ allFreqs: new Uint8Array(freqChunks)
994
+ };
995
+ }
996
+ function decodeFrozenSnapshot(buf) {
997
+ const magic = buf.toString('ascii', 0, 4);
998
+ const version = buf.readUInt16LE(4);
999
+ if (magic === BINARY_MAGIC_V2 && version === BINARY_VERSION_V2) {
1000
+ return decodeMSv2(buf);
1001
+ }
1002
+ if (magic === BINARY_MAGIC_V1 && version === BINARY_VERSION_V1) {
1003
+ return decodeMSv1(buf);
1004
+ }
1005
+ throw new Error(`Invalid frozen index: magic=${magic} version=${version}`);
1006
+ }
1007
+ function deserializeTermIndexTree(shape) {
1008
+ const tree = new Map();
1009
+ for (const [key, value] of shape) {
1010
+ if (key === LEAF) {
1011
+ tree.set(LEAF, value);
1012
+ }
1013
+ else {
1014
+ tree.set(key, deserializeTermIndexTree(value));
1015
+ }
1016
+ }
1017
+ return tree;
1018
+ }
1019
+ function serializeTermIndexTree(tree) {
1020
+ const shape = [];
1021
+ for (const [key, val] of tree) {
1022
+ if (key === LEAF) {
1023
+ shape.push([key, val]);
1024
+ }
1025
+ else {
1026
+ shape.push([key, serializeTermIndexTree(val)]);
1027
+ }
1028
+ }
1029
+ return shape;
1030
+ }
1031
+
1032
+ function resolveIndexingOptions(options) {
1033
+ if ((options === null || options === void 0 ? void 0 : options.fields) == null) {
1034
+ throw new Error('MiniSearch: option "fields" must be provided');
1035
+ }
1036
+ return {
1037
+ ...defaultFrozenLoadOptions,
1038
+ ...options,
1039
+ searchOptions: { ...defaultSearchOptions, ...(options.searchOptions || {}) },
1040
+ autoSuggestOptions: { ...defaultAutoSuggestOptions, ...(options.autoSuggestOptions || {}) }
1041
+ };
1042
+ }
1043
+ function buildFieldIds(fields) {
1044
+ const fieldIds = {};
1045
+ for (let i = 0; i < fields.length; i++) {
1046
+ fieldIds[fields[i]] = i;
1047
+ }
1048
+ return fieldIds;
1049
+ }
1050
+ /** Token frequencies for one document field (after processTerm). */
1051
+ function collectFieldTermFreqs(tokens, fieldName, processTerm) {
1052
+ const localFreqs = new Map();
1053
+ for (const term of tokens) {
1054
+ const processedTerm = processTerm(term, fieldName);
1055
+ if (Array.isArray(processedTerm)) {
1056
+ for (const t of processedTerm) {
1057
+ localFreqs.set(t, (localFreqs.get(t) || 0) + 1);
1058
+ }
1059
+ }
1060
+ else if (processedTerm) {
1061
+ localFreqs.set(processedTerm, (localFreqs.get(processedTerm) || 0) + 1);
1062
+ }
1063
+ }
1064
+ return localFreqs;
1065
+ }
1066
+ /** Same running average as {@link MiniSearch} private addFieldLength. */
1067
+ function updateAvgFieldLength(avgFieldLength, fieldId, count, length) {
1068
+ const averageFieldLength = avgFieldLength[fieldId] || 0;
1069
+ const totalFieldLength = (averageFieldLength * count) + length;
1070
+ avgFieldLength[fieldId] = totalFieldLength / (count + 1);
1071
+ }
1072
+ function saveStoredFieldsForDocument(storeFields, extractField, document) {
1073
+ if (storeFields.length === 0)
1074
+ return undefined;
1075
+ const documentFields = {};
1076
+ for (const fieldName of storeFields) {
1077
+ const fieldValue = extractField(document, fieldName);
1078
+ if (fieldValue !== undefined)
1079
+ documentFields[fieldName] = fieldValue;
1080
+ }
1081
+ return documentFields;
1082
+ }
1083
+
1084
+ function getOrCreateTermIndex(builder, term) {
1085
+ const existing = builder.index.get(term);
1086
+ if (existing != null)
1087
+ return existing;
1088
+ const ti = builder.terms.length;
1089
+ builder.terms.push(term);
1090
+ builder.index.set(term, ti);
1091
+ return ti;
1092
+ }
1093
+ function appendPosting(builder, termIndex, fieldId, docId, freq) {
1094
+ const slot = termIndex * builder.fieldCount + fieldId;
1095
+ let docIds = builder.postingsDocIds[slot];
1096
+ let freqs = builder.postingsFreqs[slot];
1097
+ if (docIds == null) {
1098
+ docIds = [];
1099
+ freqs = [];
1100
+ builder.postingsDocIds[slot] = docIds;
1101
+ builder.postingsFreqs[slot] = freqs;
1102
+ }
1103
+ docIds.push(docId);
1104
+ freqs.push(clampFreq(freq));
1105
+ }
1106
+ function finalizeFlatPostings(builder) {
1107
+ const termCount = builder.terms.length;
1108
+ const slotCount = termCount * builder.fieldCount;
1109
+ const postingsOffsets = new Uint32Array(slotCount);
1110
+ const postingsLengths = new Uint32Array(slotCount);
1111
+ const docScratch = [];
1112
+ const freqScratch = [];
1113
+ for (let ti = 0; ti < termCount; ti++) {
1114
+ const base = ti * builder.fieldCount;
1115
+ for (let f = 0; f < builder.fieldCount; f++) {
1116
+ const offset = docScratch.length;
1117
+ const docIds = builder.postingsDocIds[base + f];
1118
+ const freqs = builder.postingsFreqs[base + f];
1119
+ if (docIds == null || docIds.length === 0) {
1120
+ postingsOffsets[base + f] = offset;
1121
+ postingsLengths[base + f] = 0;
1122
+ continue;
1123
+ }
1124
+ for (let i = 0; i < docIds.length; i++) {
1125
+ docScratch.push(docIds[i]);
1126
+ freqScratch.push(freqs[i]);
1127
+ }
1128
+ postingsOffsets[base + f] = offset;
1129
+ postingsLengths[base + f] = docIds.length;
1130
+ }
1131
+ }
1132
+ return {
1133
+ postingsOffsets,
1134
+ postingsLengths,
1135
+ allDocIds: new Uint32Array(docScratch),
1136
+ allFreqs: new Uint8Array(freqScratch)
1137
+ };
1138
+ }
1139
+ function indexDocument(builder, document, shortId) {
1140
+ const { extractField, stringifyField, tokenize, processTerm, fields, idField, storeFields } = builder.options;
1141
+ const id = extractField(document, idField);
1142
+ if (id == null) {
1143
+ throw new Error(`MiniSearch: document does not have ID field "${idField}"`);
1144
+ }
1145
+ if (builder.idToShortId.has(id)) {
1146
+ throw new Error(`MiniSearch: duplicate ID ${id}`);
1147
+ }
1148
+ builder.idToShortId.set(id, shortId);
1149
+ builder.externalIds[shortId] = id;
1150
+ builder.storedFields[shortId] = saveStoredFieldsForDocument(storeFields, extractField, document);
1151
+ const documentCount = shortId + 1;
1152
+ for (const field of fields) {
1153
+ const fieldValue = extractField(document, field);
1154
+ if (fieldValue == null)
1155
+ continue;
1156
+ const tokens = tokenize(stringifyField(fieldValue, field), field);
1157
+ const fieldId = builder.fieldIds[field];
1158
+ const uniqueTerms = new Set(tokens).size;
1159
+ const localFreqs = collectFieldTermFreqs(tokens, field, processTerm);
1160
+ builder.fieldLengthMatrix[shortId * builder.fieldCount + fieldId] = uniqueTerms;
1161
+ updateAvgFieldLength(builder.avgFieldLength, fieldId, documentCount - 1, uniqueTerms);
1162
+ for (const [term, freq] of localFreqs) {
1163
+ const ti = getOrCreateTermIndex(builder, term);
1164
+ appendPosting(builder, ti, fieldId, shortId, freq);
1165
+ }
1166
+ }
1167
+ }
1168
+ function createBuilder(options, documentCount) {
1169
+ const fieldCount = options.fields.length;
1170
+ return {
1171
+ options,
1172
+ fieldIds: buildFieldIds(options.fields),
1173
+ fieldCount,
1174
+ documentCount,
1175
+ index: new SearchableMap(),
1176
+ terms: [],
1177
+ postingsDocIds: [],
1178
+ postingsFreqs: [],
1179
+ externalIds: new Array(documentCount),
1180
+ idToShortId: new Map(),
1181
+ storedFields: new Array(documentCount),
1182
+ fieldLengthMatrix: new Uint32Array(documentCount * fieldCount),
1183
+ avgFieldLength: []
1184
+ };
1185
+ }
1186
+ function buildFrozenParamsFromDocuments(documents, options) {
1187
+ var _a;
1188
+ const resolved = resolveIndexingOptions(options);
1189
+ const documentCount = documents.length;
1190
+ const builder = createBuilder(resolved, documentCount);
1191
+ for (let d = 0; d < documentCount; d++) {
1192
+ indexDocument(builder, documents[d], d);
1193
+ }
1194
+ const flat = finalizeFlatPostings(builder);
1195
+ const avgFieldLength = new Float32Array(builder.fieldCount);
1196
+ for (let f = 0; f < builder.fieldCount; f++) {
1197
+ avgFieldLength[f] = (_a = builder.avgFieldLength[f]) !== null && _a !== void 0 ? _a : 0;
1198
+ }
1199
+ return {
1200
+ options: resolved,
1201
+ documentCount,
1202
+ nextId: documentCount,
1203
+ fieldIds: builder.fieldIds,
1204
+ fieldCount: builder.fieldCount,
1205
+ externalIds: builder.externalIds,
1206
+ idToShortId: builder.idToShortId,
1207
+ storedFields: builder.storedFields,
1208
+ fieldLengthMatrix: builder.fieldLengthMatrix,
1209
+ avgFieldLength,
1210
+ index: builder.index,
1211
+ terms: builder.terms,
1212
+ postingsOffsets: flat.postingsOffsets,
1213
+ postingsLengths: flat.postingsLengths,
1214
+ allDocIds: flat.allDocIds,
1215
+ allFreqs: flat.allFreqs
1216
+ };
1217
+ }
1218
+
1219
+ /** Shared wildcard query symbol for MiniSearch and FrozenMiniSearch */
1220
+ const WILDCARD_QUERY = Symbol('*');
1221
+
1222
+ const READ_ONLY_MSG = 'FrozenMiniSearch is read-only. Rebuild from a mutable MiniSearch instance.';
1223
+ const MAP_NODE_ESTIMATE_BYTES = 120;
1224
+ function throwReadOnly() {
1225
+ throw new Error(READ_ONLY_MSG);
1226
+ }
1227
+ function cloneRadixTreeWithTermIndex(tree, termIndexByLeaf) {
1228
+ const out = new Map();
1229
+ for (const [key, val] of tree) {
1230
+ if (key === LEAF) {
1231
+ const idx = termIndexByLeaf.get(val);
1232
+ if (idx == null) {
1233
+ throw new Error('FrozenMiniSearch: missing term index while cloning tree');
1234
+ }
1235
+ out.set(LEAF, idx);
1236
+ }
1237
+ else {
1238
+ out.set(key, cloneRadixTreeWithTermIndex(val, termIndexByLeaf));
1239
+ }
1240
+ }
1241
+ return out;
1242
+ }
1243
+ function countRadixMapNodes(tree) {
1244
+ let n = 1;
1245
+ for (const [key, val] of tree) {
1246
+ if (key !== LEAF)
1247
+ n += countRadixMapNodes(val);
1248
+ }
1249
+ return n;
1250
+ }
1251
+ function frozenMemoryBreakdown(frozen) {
1252
+ return frozen.memoryBreakdown();
1253
+ }
1254
+ /** Instantiate {@link FrozenMiniSearch} from pre-built flat index parts. */
1255
+ function assembleFrozen(params) {
1256
+ return new FrozenMiniSearch(params);
1257
+ }
1258
+ function buildFlatPostingsFromSource(source, fieldCount, shortIdRemap) {
1259
+ const terms = [];
1260
+ const leafToIndex = new WeakMap();
1261
+ for (const [term, fieldIndex] of source._index) {
1262
+ const ti = terms.length;
1263
+ terms.push(term);
1264
+ leafToIndex.set(fieldIndex, ti);
1265
+ }
1266
+ const termCount = terms.length;
1267
+ const slotCount = termCount * fieldCount;
1268
+ const postingsOffsets = new Uint32Array(slotCount);
1269
+ const postingsLengths = new Uint32Array(slotCount);
1270
+ const docScratch = [];
1271
+ const freqScratch = [];
1272
+ for (const [, fieldIndex] of source._index) {
1273
+ const ti = leafToIndex.get(fieldIndex);
1274
+ const base = ti * fieldCount;
1275
+ for (let f = 0; f < fieldCount; f++) {
1276
+ const offset = docScratch.length;
1277
+ const freqs = fieldIndex.get(f);
1278
+ if (freqs == null || freqs.size === 0) {
1279
+ postingsOffsets[base + f] = offset;
1280
+ postingsLengths[base + f] = 0;
1281
+ continue;
1282
+ }
1283
+ let count = 0;
1284
+ for (const [shortId, freq] of freqs) {
1285
+ const docId = shortIdRemap != null ? shortIdRemap[shortId] : shortId;
1286
+ // Skip discarded docs when dense remapping is enabled. This prevents
1287
+ // invalid docIds (no externalId) from leaking into frozen search results.
1288
+ if (docId === 0xffffffff)
1289
+ continue;
1290
+ docScratch.push(docId);
1291
+ freqScratch.push(clampFreq(freq));
1292
+ count++;
1293
+ }
1294
+ postingsOffsets[base + f] = offset;
1295
+ postingsLengths[base + f] = count;
1296
+ }
1297
+ }
1298
+ const allDocIds = new Uint32Array(docScratch);
1299
+ const allFreqs = new Uint8Array(freqScratch);
1300
+ const tree = cloneRadixTreeWithTermIndex(source._index.radixTree, leafToIndex);
1301
+ return { terms, tree, postingsOffsets, postingsLengths, allDocIds, allFreqs };
1302
+ }
1303
+ function freezeFromMiniSearch(source) {
1304
+ var _a;
1305
+ const fieldCount = source._options.fields.length;
1306
+ const { _documentCount, _nextId } = source;
1307
+ const useDense = _documentCount < _nextId;
1308
+ let shortIdRemap = null;
1309
+ const externalIds = new Array(useDense ? _documentCount : _nextId);
1310
+ const storedFields = new Array(externalIds.length);
1311
+ const idToShortId = new Map();
1312
+ if (useDense) {
1313
+ shortIdRemap = new Uint32Array(_nextId);
1314
+ shortIdRemap.fill(0xffffffff);
1315
+ let dense = 0;
1316
+ for (const [shortId, id] of source._documentIds) {
1317
+ shortIdRemap[shortId] = dense;
1318
+ externalIds[dense] = id;
1319
+ idToShortId.set(id, dense);
1320
+ storedFields[dense] = source._storedFields.get(shortId);
1321
+ dense++;
1322
+ }
1323
+ }
1324
+ else {
1325
+ for (const [shortId, id] of source._documentIds) {
1326
+ externalIds[shortId] = id;
1327
+ idToShortId.set(id, shortId);
1328
+ storedFields[shortId] = source._storedFields.get(shortId);
1329
+ }
1330
+ }
1331
+ const matrixRows = useDense ? _documentCount : _nextId;
1332
+ const fieldLengthMatrix = new Uint32Array(matrixRows * fieldCount);
1333
+ for (const [shortId, lengths] of source._fieldLength) {
1334
+ const row = shortIdRemap != null ? shortIdRemap[shortId] : shortId;
1335
+ if (row === 0xffffffff)
1336
+ continue;
1337
+ for (let f = 0; f < fieldCount; f++) {
1338
+ fieldLengthMatrix[row * fieldCount + f] = (_a = lengths[f]) !== null && _a !== void 0 ? _a : 0;
1339
+ }
1340
+ }
1341
+ const avgFieldLength = new Float32Array(source._avgFieldLength.length);
1342
+ for (let i = 0; i < source._avgFieldLength.length; i++) {
1343
+ avgFieldLength[i] = source._avgFieldLength[i];
1344
+ }
1345
+ const flat = buildFlatPostingsFromSource(source, fieldCount, shortIdRemap);
1346
+ const frozenIndex = new SearchableMap(flat.tree);
1347
+ return assembleFrozen({
1348
+ options: source._options,
1349
+ documentCount: _documentCount,
1350
+ nextId: useDense ? _documentCount : _nextId,
1351
+ fieldIds: source._fieldIds,
1352
+ fieldCount,
1353
+ externalIds,
1354
+ idToShortId,
1355
+ storedFields,
1356
+ fieldLengthMatrix,
1357
+ avgFieldLength,
1358
+ index: frozenIndex,
1359
+ terms: flat.terms,
1360
+ postingsOffsets: flat.postingsOffsets,
1361
+ postingsLengths: flat.postingsLengths,
1362
+ allDocIds: flat.allDocIds,
1363
+ allFreqs: flat.allFreqs
1364
+ });
1365
+ }
1366
+ function buildFrozenFromDocuments(documents, options) {
1367
+ return assembleFrozen(buildFrozenParamsFromDocuments(documents, options));
1368
+ }
1369
+ class FrozenMiniSearch {
1370
+ constructor(params) {
1371
+ this._options = params.options;
1372
+ this._documentCount = params.documentCount;
1373
+ this._nextId = params.nextId;
1374
+ this._externalIds = params.externalIds;
1375
+ this._idToShortId = params.idToShortId;
1376
+ this._fieldIds = params.fieldIds;
1377
+ this._fieldCount = params.fieldCount;
1378
+ this._fieldLengthMatrix = params.fieldLengthMatrix;
1379
+ this._avgFieldLength = params.avgFieldLength;
1380
+ this._storedFields = params.storedFields;
1381
+ this._index = params.index;
1382
+ this._terms = params.terms;
1383
+ this._postingsOffsets = params.postingsOffsets;
1384
+ this._postingsLengths = params.postingsLengths;
1385
+ this._allDocIds = params.allDocIds;
1386
+ this._allFreqs = params.allFreqs;
1387
+ }
1388
+ get documentCount() { return this._documentCount; }
1389
+ get termCount() { return this._index.size; }
1390
+ memoryBreakdown() {
1391
+ const termCount = this.termCount;
1392
+ const slotCount = termCount * this._fieldCount;
1393
+ const postingsTyped = this._allDocIds.byteLength + this._allFreqs.byteLength +
1394
+ this._postingsOffsets.byteLength + this._postingsLengths.byteLength;
1395
+ let storedJson = 0;
1396
+ for (const row of this._storedFields) {
1397
+ if (row != null)
1398
+ storedJson += JSON.stringify(row).length;
1399
+ }
1400
+ const mapNodeCount = countRadixMapNodes(this._index.radixTree);
1401
+ const radixEst = mapNodeCount * MAP_NODE_ESTIMATE_BYTES;
1402
+ const estimatedStructuredBytes = postingsTyped +
1403
+ this._fieldLengthMatrix.byteLength +
1404
+ this._avgFieldLength.byteLength +
1405
+ radixEst +
1406
+ storedJson +
1407
+ this._idToShortId.size * 32;
1408
+ return {
1409
+ termCount,
1410
+ documentCount: this._documentCount,
1411
+ nextId: this._nextId,
1412
+ postings: {
1413
+ slotCount,
1414
+ allDocIdsBytes: this._allDocIds.byteLength,
1415
+ allFreqsBytes: this._allFreqs.byteLength,
1416
+ offsetsBytes: this._postingsOffsets.byteLength,
1417
+ lengthsBytes: this._postingsLengths.byteLength,
1418
+ totalTypedBytes: postingsTyped
1419
+ },
1420
+ radixTree: {
1421
+ mapNodeCount,
1422
+ estimatedBytes: radixEst
1423
+ },
1424
+ documents: {
1425
+ externalIdsSlots: this._externalIds.length,
1426
+ storedFieldsSlots: this._storedFields.length,
1427
+ idToShortIdEntries: this._idToShortId.size,
1428
+ fieldLengthMatrixBytes: this._fieldLengthMatrix.byteLength,
1429
+ avgFieldLengthBytes: this._avgFieldLength.byteLength,
1430
+ storedFieldsJsonBytes: storedJson
1431
+ },
1432
+ estimatedStructuredBytes
1433
+ };
1434
+ }
1435
+ has(id) {
1436
+ return this._idToShortId.has(id);
1437
+ }
1438
+ getStoredFields(id) {
1439
+ const shortId = this._idToShortId.get(id);
1440
+ return shortId == null ? undefined : this._storedFields[shortId];
1441
+ }
1442
+ add() { throwReadOnly(); }
1443
+ addAll() { throwReadOnly(); }
1444
+ addAllAsync() { throwReadOnly(); }
1445
+ remove() { throwReadOnly(); }
1446
+ removeAll() { throwReadOnly(); }
1447
+ discard() { throwReadOnly(); }
1448
+ discardAll() { throwReadOnly(); }
1449
+ replace() { throwReadOnly(); }
1450
+ vacuum() { throwReadOnly(); }
1451
+ search(query, searchOptions = {}) {
1452
+ const { searchOptions: globalSearchOptions } = this._options;
1453
+ const searchOptionsWithDefaults = { ...globalSearchOptions, ...searchOptions };
1454
+ const rawResults = this.executeQuery(query, searchOptions);
1455
+ const skipSort = query === FrozenMiniSearch.wildcard && searchOptionsWithDefaults.boostDocument == null;
1456
+ return finalizeSearchResults({
1457
+ rawResults,
1458
+ getExternalId: (docId) => this._externalIds[docId],
1459
+ getStoredFields: (docId) => this._storedFields[docId],
1460
+ filter: searchOptionsWithDefaults.filter,
1461
+ skipSort
1462
+ });
1463
+ }
1464
+ autoSuggest(queryString, options = {}) {
1465
+ options = { ...this._options.autoSuggestOptions, ...options };
1466
+ const suggestions = new Map();
1467
+ for (const { score, terms } of this.search(queryString, options)) {
1468
+ const phrase = terms.join(' ');
1469
+ const suggestion = suggestions.get(phrase);
1470
+ if (suggestion != null) {
1471
+ suggestion.score += score;
1472
+ suggestion.count += 1;
1473
+ }
1474
+ else {
1475
+ suggestions.set(phrase, { score, terms, count: 1 });
1476
+ }
1477
+ }
1478
+ return [...suggestions.entries()]
1479
+ .map(([suggestion, { score, terms, count }]) => ({
1480
+ suggestion,
1481
+ terms,
1482
+ score: score / count
1483
+ }))
1484
+ .sort((a, b) => b.score - a.score);
1485
+ }
1486
+ saveBinary() {
1487
+ return encodeFrozenSnapshot({
1488
+ documentCount: this._documentCount,
1489
+ nextId: this._nextId,
1490
+ fieldIds: this._fieldIds,
1491
+ fieldCount: this._fieldCount,
1492
+ avgFieldLength: this._avgFieldLength,
1493
+ externalIds: this._externalIds,
1494
+ storedFields: this._storedFields,
1495
+ fieldLengthMatrix: this._fieldLengthMatrix,
1496
+ terms: this._terms,
1497
+ treeShape: serializeTermIndexTree(this._index.radixTree),
1498
+ postingsOffsets: this._postingsOffsets,
1499
+ postingsLengths: this._postingsLengths,
1500
+ allDocIds: this._allDocIds,
1501
+ allFreqs: this._allFreqs
1502
+ });
1503
+ }
1504
+ static loadBinary(buffer, options) {
1505
+ if ((options === null || options === void 0 ? void 0 : options.fields) == null) {
1506
+ throw new Error('FrozenMiniSearch: option "fields" must be provided');
1507
+ }
1508
+ const snap = decodeFrozenSnapshot(buffer);
1509
+ const fieldNames = options.fields;
1510
+ for (const name of fieldNames) {
1511
+ if (snap.fieldIds[name] === undefined) {
1512
+ throw new Error(`FrozenMiniSearch: field "${name}" not found in frozen index`);
1513
+ }
1514
+ }
1515
+ const opts = {
1516
+ ...defaultFrozenLoadOptions,
1517
+ ...options,
1518
+ searchOptions: {
1519
+ ...defaultSearchOptions,
1520
+ ...(options.searchOptions || {})
1521
+ },
1522
+ autoSuggestOptions: { ...defaultAutoSuggestOptions, ...(options.autoSuggestOptions || {}) }
1523
+ };
1524
+ const index = new SearchableMap(deserializeTermIndexTree(snap.treeShape));
1525
+ const idToShortId = new Map();
1526
+ for (let i = 0; i < snap.externalIds.length; i++) {
1527
+ if (snap.externalIds[i] !== undefined) {
1528
+ idToShortId.set(snap.externalIds[i], i);
1529
+ }
1530
+ }
1531
+ return assembleFrozen({
1532
+ options: opts,
1533
+ documentCount: snap.documentCount,
1534
+ nextId: snap.nextId,
1535
+ fieldIds: snap.fieldIds,
1536
+ fieldCount: snap.fieldCount,
1537
+ externalIds: snap.externalIds,
1538
+ idToShortId,
1539
+ storedFields: snap.storedFields,
1540
+ fieldLengthMatrix: snap.fieldLengthMatrix,
1541
+ avgFieldLength: snap.avgFieldLength,
1542
+ index,
1543
+ terms: snap.terms,
1544
+ postingsOffsets: snap.postingsOffsets,
1545
+ postingsLengths: snap.postingsLengths,
1546
+ allDocIds: snap.allDocIds,
1547
+ allFreqs: snap.allFreqs
1548
+ });
1549
+ }
1550
+ /**
1551
+ * Build a read-only index in one pass from documents (no mutable MiniSearch step).
1552
+ *
1553
+ * Use {@link MiniSearch} + {@link MiniSearch#freeze} when you need remove, discard, or
1554
+ * incremental updates before freezing.
1555
+ */
1556
+ static fromDocuments(documents, options) {
1557
+ return buildFrozenFromDocuments(documents, options);
1558
+ }
1559
+ getFieldLength(docId, fieldId) {
1560
+ var _a;
1561
+ return (_a = this._fieldLengthMatrix[docId * this._fieldCount + fieldId]) !== null && _a !== void 0 ? _a : 0;
1562
+ }
1563
+ fieldTermDataFor(termIndex) {
1564
+ return flatFieldTermData(termIndex, this._fieldCount, this._postingsOffsets, this._postingsLengths, this._allDocIds, this._allFreqs);
1565
+ }
1566
+ aggregateContext() {
1567
+ return {
1568
+ documentCount: this._documentCount,
1569
+ avgFieldLength: this._avgFieldLength,
1570
+ fieldIds: this._fieldIds,
1571
+ getFieldLength: (docId, fieldId) => this.getFieldLength(docId, fieldId),
1572
+ getExternalId: (docId) => this._externalIds[docId],
1573
+ getStoredFields: (docId) => this._storedFields[docId]
1574
+ };
1575
+ }
1576
+ termResults(sourceTerm, derivedTerm, termWeight, termBoost, termIndex, fieldBoosts, boostDocumentFn, bm25params, results = new Map()) {
1577
+ if (termIndex == null)
1578
+ return results;
1579
+ return aggregateTerm(sourceTerm, derivedTerm, termWeight, termBoost, this.fieldTermDataFor(termIndex), fieldBoosts, this.aggregateContext(), boostDocumentFn, bm25params, results);
1580
+ }
1581
+ executeQuery(query, searchOptions = {}) {
1582
+ if (query === FrozenMiniSearch.wildcard) {
1583
+ return this.executeWildcardQuery(searchOptions);
1584
+ }
1585
+ if (typeof query !== 'string') {
1586
+ const options = { ...searchOptions, ...query, queries: undefined };
1587
+ const results = query.queries.map((subquery) => this.executeQuery(subquery, options));
1588
+ return combineResults(results, options.combineWith);
1589
+ }
1590
+ const { tokenize, processTerm, searchOptions: globalSearchOptions } = this._options;
1591
+ const options = { tokenize, processTerm, ...globalSearchOptions, ...searchOptions };
1592
+ const { tokenize: searchTokenize, processTerm: searchProcessTerm } = options;
1593
+ const terms = searchTokenize(query)
1594
+ .flatMap((term) => searchProcessTerm(term))
1595
+ .filter((term) => !!term);
1596
+ const queries = terms.map(termToQuerySpec(options));
1597
+ const results = queries.map((q) => this.executeQuerySpec(q, options));
1598
+ return combineResults(results, options.combineWith);
1599
+ }
1600
+ executeQuerySpec(query, searchOptions) {
1601
+ var _a, _b;
1602
+ const options = { ...this._options.searchOptions, ...searchOptions };
1603
+ const boosts = (options.fields || this._options.fields).reduce((b, field) => ({ ...b, [field]: getOwnProperty(options.boost, field) || 1 }), {});
1604
+ const { boostDocument, weights, maxFuzzy, bm25: bm25params } = options;
1605
+ const fuzzyWeight = (_a = weights === null || weights === void 0 ? void 0 : weights.fuzzy) !== null && _a !== void 0 ? _a : 0.45;
1606
+ const prefixWeight = (_b = weights === null || weights === void 0 ? void 0 : weights.prefix) !== null && _b !== void 0 ? _b : 0.375;
1607
+ const termIndex = this._index.get(query.term);
1608
+ const results = this.termResults(query.term, query.term, 1, query.termBoost, termIndex, boosts, boostDocument, bm25params);
1609
+ let prefixMatches;
1610
+ let fuzzyMatches;
1611
+ if (query.prefix) {
1612
+ prefixMatches = this._index.atPrefix(query.term);
1613
+ }
1614
+ if (query.fuzzy) {
1615
+ const fuzzy = (query.fuzzy === true) ? 0.2 : query.fuzzy;
1616
+ const maxDistance = fuzzy < 1
1617
+ ? Math.min(maxFuzzy, Math.round(query.term.length * fuzzy))
1618
+ : fuzzy;
1619
+ if (maxDistance)
1620
+ fuzzyMatches = this._index.fuzzyGet(query.term, maxDistance);
1621
+ }
1622
+ if (prefixMatches) {
1623
+ for (const [term, ti] of prefixMatches) {
1624
+ const distance = term.length - query.term.length;
1625
+ if (!distance)
1626
+ continue;
1627
+ fuzzyMatches === null || fuzzyMatches === void 0 ? void 0 : fuzzyMatches.delete(term);
1628
+ const weight = prefixWeight * term.length / (term.length + 0.3 * distance);
1629
+ this.termResults(query.term, term, weight, query.termBoost, ti, boosts, boostDocument, bm25params, results);
1630
+ }
1631
+ }
1632
+ if (fuzzyMatches) {
1633
+ for (const term of fuzzyMatches.keys()) {
1634
+ const [ti, distance] = fuzzyMatches.get(term);
1635
+ if (!distance)
1636
+ continue;
1637
+ const weight = fuzzyWeight * term.length / (term.length + distance);
1638
+ this.termResults(query.term, term, weight, query.termBoost, ti, boosts, boostDocument, bm25params, results);
1639
+ }
1640
+ }
1641
+ return results;
1642
+ }
1643
+ executeWildcardQuery(searchOptions) {
1644
+ const results = new Map();
1645
+ const options = { ...this._options.searchOptions, ...searchOptions };
1646
+ for (let shortId = 0; shortId < this._nextId; shortId++) {
1647
+ const id = this._externalIds[shortId];
1648
+ if (id === undefined)
1649
+ continue;
1650
+ const score = options.boostDocument
1651
+ ? options.boostDocument(id, '', this._storedFields[shortId])
1652
+ : 1;
1653
+ results.set(shortId, { score, terms: [], match: {} });
1654
+ }
1655
+ return results;
1656
+ }
1657
+ }
1658
+ FrozenMiniSearch.wildcard = WILDCARD_QUERY;
1659
+
1660
+ /**
1661
+ * {@link MiniSearch} is the main entrypoint class, implementing a full-text
1662
+ * search engine in memory.
1663
+ *
1664
+ * @typeParam T The type of the documents being indexed.
1665
+ *
1666
+ * ### Basic example:
1667
+ *
1668
+ * ```javascript
1669
+ * const documents = [
1670
+ * {
1671
+ * id: 1,
1672
+ * title: 'Moby Dick',
1673
+ * text: 'Call me Ishmael. Some years ago...',
1674
+ * category: 'fiction'
1675
+ * },
1676
+ * {
1677
+ * id: 2,
1678
+ * title: 'Zen and the Art of Motorcycle Maintenance',
1679
+ * text: 'I can see by my watch...',
1680
+ * category: 'fiction'
1681
+ * },
1682
+ * {
1683
+ * id: 3,
1684
+ * title: 'Neuromancer',
1685
+ * text: 'The sky above the port was...',
1686
+ * category: 'fiction'
1687
+ * },
1688
+ * {
1689
+ * id: 4,
1690
+ * title: 'Zen and the Art of Archery',
1691
+ * text: 'At first sight it must seem...',
1692
+ * category: 'non-fiction'
1693
+ * },
1694
+ * // ...and more
1695
+ * ]
1696
+ *
1697
+ * // Create a search engine that indexes the 'title' and 'text' fields for
1698
+ * // full-text search. Search results will include 'title' and 'category' (plus the
1699
+ * // id field, that is always stored and returned)
1700
+ * const miniSearch = new MiniSearch({
1701
+ * fields: ['title', 'text'],
1702
+ * storeFields: ['title', 'category']
1703
+ * })
1704
+ *
1705
+ * // Add documents to the index
1706
+ * miniSearch.addAll(documents)
1707
+ *
1708
+ * // Search for documents:
1709
+ * let results = miniSearch.search('zen art motorcycle')
1710
+ * // => [
1711
+ * // { id: 2, title: 'Zen and the Art of Motorcycle Maintenance', category: 'fiction', score: 2.77258 },
1712
+ * // { id: 4, title: 'Zen and the Art of Archery', category: 'non-fiction', score: 1.38629 }
1713
+ * // ]
1714
+ * ```
1715
+ */
1716
+ class MiniSearch {
1717
+ /**
1718
+ * @param options Configuration options
1719
+ *
1720
+ * ### Examples:
1721
+ *
1722
+ * ```javascript
1723
+ * // Create a search engine that indexes the 'title' and 'text' fields of your
1724
+ * // documents:
1725
+ * const miniSearch = new MiniSearch({ fields: ['title', 'text'] })
1726
+ * ```
1727
+ *
1728
+ * ### ID Field:
1729
+ *
1730
+ * ```javascript
1731
+ * // Your documents are assumed to include a unique 'id' field, but if you want
1732
+ * // to use a different field for document identification, you can set the
1733
+ * // 'idField' option:
1734
+ * const miniSearch = new MiniSearch({ idField: 'key', fields: ['title', 'text'] })
1735
+ * ```
1736
+ *
1737
+ * ### Options and defaults:
1738
+ *
1739
+ * ```javascript
1740
+ * // The full set of options (here with their default value) is:
1741
+ * const miniSearch = new MiniSearch({
1742
+ * // idField: field that uniquely identifies a document
1743
+ * idField: 'id',
1744
+ *
1745
+ * // extractField: function used to get the value of a field in a document.
1746
+ * // By default, it assumes the document is a flat object with field names as
1747
+ * // property keys and field values as string property values, but custom logic
1748
+ * // can be implemented by setting this option to a custom extractor function.
1749
+ * extractField: (document, fieldName) => document[fieldName],
1750
+ *
1751
+ * // tokenize: function used to split fields into individual terms. By
1752
+ * // default, it is also used to tokenize search queries, unless a specific
1753
+ * // `tokenize` search option is supplied. When tokenizing an indexed field,
1754
+ * // the field name is passed as the second argument.
1755
+ * tokenize: (string, _fieldName) => string.split(SPACE_OR_PUNCTUATION),
1756
+ *
1757
+ * // processTerm: function used to process each tokenized term before
1758
+ * // indexing. It can be used for stemming and normalization. Return a falsy
1759
+ * // value in order to discard a term. By default, it is also used to process
1760
+ * // search queries, unless a specific `processTerm` option is supplied as a
1761
+ * // search option. When processing a term from a indexed field, the field
1762
+ * // name is passed as the second argument.
1763
+ * processTerm: (term, _fieldName) => term.toLowerCase(),
1764
+ *
1765
+ * // searchOptions: default search options, see the `search` method for
1766
+ * // details
1767
+ * searchOptions: undefined,
1768
+ *
1769
+ * // fields: document fields to be indexed. Mandatory, but not set by default
1770
+ * fields: undefined
1771
+ *
1772
+ * // storeFields: document fields to be stored and returned as part of the
1773
+ * // search results.
1774
+ * storeFields: []
1775
+ * })
1776
+ * ```
1777
+ */
1778
+ constructor(options) {
1779
+ if ((options === null || options === void 0 ? void 0 : options.fields) == null) {
1780
+ throw new Error('MiniSearch: option "fields" must be provided');
1781
+ }
1782
+ const autoVacuum = (options.autoVacuum == null || options.autoVacuum === true) ? defaultAutoVacuumOptions : options.autoVacuum;
1783
+ this._options = {
1784
+ ...defaultOptions,
1785
+ ...options,
1786
+ autoVacuum,
1787
+ searchOptions: { ...defaultSearchOptions, ...(options.searchOptions || {}) },
1788
+ autoSuggestOptions: { ...defaultAutoSuggestOptions, ...(options.autoSuggestOptions || {}) }
1789
+ };
1790
+ this._index = new SearchableMap();
1791
+ this._documentCount = 0;
1792
+ this._documentIds = new Map();
1793
+ this._idToShortId = new Map();
1794
+ // Fields are defined during initialization, don't change, are few in
1795
+ // number, rarely need iterating over, and have string keys. Therefore in
1796
+ // this case an object is a better candidate than a Map to store the mapping
1797
+ // from field key to ID.
1798
+ this._fieldIds = {};
1799
+ this._fieldLength = new Map();
1800
+ this._avgFieldLength = [];
1801
+ this._nextId = 0;
1802
+ this._storedFields = new Map();
1803
+ this._dirtCount = 0;
1804
+ this._currentVacuum = null;
1805
+ this._enqueuedVacuum = null;
1806
+ this._enqueuedVacuumConditions = defaultVacuumConditions;
1807
+ this.addFields(this._options.fields);
1808
+ }
1809
+ /**
1810
+ * Adds a document to the index
1811
+ *
1812
+ * @param document The document to be indexed
1813
+ */
1814
+ add(document) {
1815
+ const { extractField, stringifyField, tokenize, processTerm, fields, idField } = this._options;
1816
+ const id = extractField(document, idField);
1817
+ if (id == null) {
1818
+ throw new Error(`MiniSearch: document does not have ID field "${idField}"`);
1819
+ }
1820
+ if (this._idToShortId.has(id)) {
1821
+ throw new Error(`MiniSearch: duplicate ID ${id}`);
1822
+ }
1823
+ const shortDocumentId = this.addDocumentId(id);
1824
+ const stored = saveStoredFieldsForDocument(this._options.storeFields, extractField, document);
1825
+ if (stored != null)
1826
+ this._storedFields.set(shortDocumentId, stored);
1827
+ for (const field of fields) {
1828
+ const fieldValue = extractField(document, field);
1829
+ if (fieldValue == null)
1830
+ continue;
1831
+ const tokens = tokenize(stringifyField(fieldValue, field), field);
1832
+ const fieldId = this._fieldIds[field];
1833
+ const uniqueTerms = new Set(tokens).size;
1834
+ const localFreqs = collectFieldTermFreqs(tokens, field, processTerm);
1835
+ this.addFieldLength(shortDocumentId, fieldId, this._documentCount - 1, uniqueTerms);
1836
+ for (const [term] of localFreqs) {
1837
+ const freq = localFreqs.get(term);
1838
+ for (let i = 0; i < freq; i++) {
1839
+ this.addTerm(fieldId, shortDocumentId, term);
1840
+ }
1841
+ }
1842
+ }
1843
+ }
1844
+ /**
1845
+ * Adds all the given documents to the index
1846
+ *
1847
+ * @param documents An array of documents to be indexed
1848
+ */
1849
+ addAll(documents) {
1850
+ for (const document of documents)
1851
+ this.add(document);
1852
+ }
1853
+ /**
1854
+ * Adds all the given documents to the index asynchronously.
1855
+ *
1856
+ * Returns a promise that resolves (to `undefined`) when the indexing is done.
1857
+ * This method is useful when index many documents, to avoid blocking the main
1858
+ * thread. The indexing is performed asynchronously and in chunks.
1859
+ *
1860
+ * @param documents An array of documents to be indexed
1861
+ * @param options Configuration options
1862
+ * @return A promise resolving to `undefined` when the indexing is done
1863
+ */
1864
+ addAllAsync(documents, options = {}) {
1865
+ const { chunkSize = 10 } = options;
1866
+ const acc = { chunk: [], promise: Promise.resolve() };
1867
+ const { chunk, promise } = documents.reduce(({ chunk, promise }, document, i) => {
1868
+ chunk.push(document);
1869
+ if ((i + 1) % chunkSize === 0) {
1870
+ return {
1871
+ chunk: [],
1872
+ promise: promise
1873
+ .then(() => new Promise(resolve => setTimeout(resolve, 0)))
1874
+ .then(() => this.addAll(chunk))
1875
+ };
1876
+ }
1877
+ else {
1878
+ return { chunk, promise };
1879
+ }
1880
+ }, acc);
1881
+ return promise.then(() => this.addAll(chunk));
1882
+ }
1883
+ /**
1884
+ * Removes the given document from the index.
1885
+ *
1886
+ * The document to remove must NOT have changed between indexing and removal,
1887
+ * otherwise the index will be corrupted.
1888
+ *
1889
+ * This method requires passing the full document to be removed (not just the
1890
+ * ID), and immediately removes the document from the inverted index, allowing
1891
+ * memory to be released. A convenient alternative is {@link
1892
+ * MiniSearch#discard}, which needs only the document ID, and has the same
1893
+ * visible effect, but delays cleaning up the index until the next vacuuming.
1894
+ *
1895
+ * @param document The document to be removed
1896
+ */
1897
+ remove(document) {
1898
+ const { tokenize, processTerm, extractField, stringifyField, fields, idField } = this._options;
1899
+ const id = extractField(document, idField);
1900
+ if (id == null) {
1901
+ throw new Error(`MiniSearch: document does not have ID field "${idField}"`);
1902
+ }
1903
+ const shortId = this._idToShortId.get(id);
1904
+ if (shortId == null) {
1905
+ throw new Error(`MiniSearch: cannot remove document with ID ${id}: it is not in the index`);
1906
+ }
1907
+ for (const field of fields) {
1908
+ const fieldValue = extractField(document, field);
1909
+ if (fieldValue == null)
1910
+ continue;
1911
+ const tokens = tokenize(stringifyField(fieldValue, field), field);
1912
+ const fieldId = this._fieldIds[field];
1913
+ const uniqueTerms = new Set(tokens).size;
1914
+ this.removeFieldLength(shortId, fieldId, this._documentCount, uniqueTerms);
1915
+ for (const term of tokens) {
1916
+ const processedTerm = processTerm(term, field);
1917
+ if (Array.isArray(processedTerm)) {
1918
+ for (const t of processedTerm) {
1919
+ this.removeTerm(fieldId, shortId, t);
1920
+ }
1921
+ }
1922
+ else if (processedTerm) {
1923
+ this.removeTerm(fieldId, shortId, processedTerm);
1924
+ }
1925
+ }
1926
+ }
1927
+ this._storedFields.delete(shortId);
1928
+ this._documentIds.delete(shortId);
1929
+ this._idToShortId.delete(id);
1930
+ this._fieldLength.delete(shortId);
1931
+ this._documentCount -= 1;
1932
+ }
1933
+ /**
1934
+ * Removes all the given documents from the index. If called with no arguments,
1935
+ * it removes _all_ documents from the index.
1936
+ *
1937
+ * @param documents The documents to be removed. If this argument is omitted,
1938
+ * all documents are removed. Note that, for removing all documents, it is
1939
+ * more efficient to call this method with no arguments than to pass all
1940
+ * documents.
1941
+ */
1942
+ removeAll(documents) {
1943
+ if (documents) {
1944
+ for (const document of documents)
1945
+ this.remove(document);
1946
+ }
1947
+ else if (arguments.length > 0) {
1948
+ throw new Error('Expected documents to be present. Omit the argument to remove all documents.');
1949
+ }
1950
+ else {
1951
+ this._index = new SearchableMap();
1952
+ this._documentCount = 0;
1953
+ this._documentIds = new Map();
1954
+ this._idToShortId = new Map();
1955
+ this._fieldLength = new Map();
1956
+ this._avgFieldLength = [];
1957
+ this._storedFields = new Map();
1958
+ this._nextId = 0;
1959
+ }
1960
+ }
1961
+ /**
1962
+ * Discards the document with the given ID, so it won't appear in search results
1963
+ *
1964
+ * It has the same visible effect of {@link MiniSearch.remove} (both cause the
1965
+ * document to stop appearing in searches), but a different effect on the
1966
+ * internal data structures:
1967
+ *
1968
+ * - {@link MiniSearch#remove} requires passing the full document to be
1969
+ * removed as argument, and removes it from the inverted index immediately.
1970
+ *
1971
+ * - {@link MiniSearch#discard} instead only needs the document ID, and
1972
+ * works by marking the current version of the document as discarded, so it
1973
+ * is immediately ignored by searches. This is faster and more convenient
1974
+ * than {@link MiniSearch#remove}, but the index is not immediately
1975
+ * modified. To take care of that, vacuuming is performed after a certain
1976
+ * number of documents are discarded, cleaning up the index and allowing
1977
+ * memory to be released.
1978
+ *
1979
+ * After discarding a document, it is possible to re-add a new version, and
1980
+ * only the new version will appear in searches. In other words, discarding
1981
+ * and re-adding a document works exactly like removing and re-adding it. The
1982
+ * {@link MiniSearch.replace} method can also be used to replace a document
1983
+ * with a new version.
1984
+ *
1985
+ * #### Details about vacuuming
1986
+ *
1987
+ * Repetite calls to this method would leave obsolete document references in
1988
+ * the index, invisible to searches. Two mechanisms take care of cleaning up:
1989
+ * clean up during search, and vacuuming.
1990
+ *
1991
+ * - Upon search, whenever a discarded ID is found (and ignored for the
1992
+ * results), references to the discarded document are removed from the
1993
+ * inverted index entries for the search terms. This ensures that subsequent
1994
+ * searches for the same terms do not need to skip these obsolete references
1995
+ * again.
1996
+ *
1997
+ * - In addition, vacuuming is performed automatically by default (see the
1998
+ * `autoVacuum` field in {@link Options}) after a certain number of
1999
+ * documents are discarded. Vacuuming traverses all terms in the index,
2000
+ * cleaning up all references to discarded documents. Vacuuming can also be
2001
+ * triggered manually by calling {@link MiniSearch#vacuum}.
2002
+ *
2003
+ * @param id The ID of the document to be discarded
2004
+ */
2005
+ discard(id) {
2006
+ const shortId = this._idToShortId.get(id);
2007
+ if (shortId == null) {
2008
+ throw new Error(`MiniSearch: cannot discard document with ID ${id}: it is not in the index`);
2009
+ }
2010
+ this._idToShortId.delete(id);
2011
+ this._documentIds.delete(shortId);
2012
+ this._storedFields.delete(shortId);
2013
+ (this._fieldLength.get(shortId) || []).forEach((fieldLength, fieldId) => {
2014
+ this.removeFieldLength(shortId, fieldId, this._documentCount, fieldLength);
2015
+ });
2016
+ this._fieldLength.delete(shortId);
2017
+ this._documentCount -= 1;
2018
+ this._dirtCount += 1;
2019
+ this.maybeAutoVacuum();
2020
+ }
2021
+ maybeAutoVacuum() {
2022
+ if (this._options.autoVacuum === false) {
2023
+ return;
2024
+ }
2025
+ const { minDirtFactor, minDirtCount, batchSize, batchWait } = this._options.autoVacuum;
2026
+ this.conditionalVacuum({ batchSize, batchWait }, { minDirtCount, minDirtFactor });
2027
+ }
2028
+ /**
2029
+ * Discards the documents with the given IDs, so they won't appear in search
2030
+ * results
2031
+ *
2032
+ * It is equivalent to calling {@link MiniSearch#discard} for all the given
2033
+ * IDs, but with the optimization of triggering at most one automatic
2034
+ * vacuuming at the end.
2035
+ *
2036
+ * Note: to remove all documents from the index, it is faster and more
2037
+ * convenient to call {@link MiniSearch.removeAll} with no argument, instead
2038
+ * of passing all IDs to this method.
2039
+ */
2040
+ discardAll(ids) {
2041
+ const autoVacuum = this._options.autoVacuum;
2042
+ try {
2043
+ this._options.autoVacuum = false;
2044
+ for (const id of ids) {
2045
+ this.discard(id);
2046
+ }
2047
+ }
2048
+ finally {
2049
+ this._options.autoVacuum = autoVacuum;
2050
+ }
2051
+ this.maybeAutoVacuum();
2052
+ }
2053
+ /**
2054
+ * It replaces an existing document with the given updated version
2055
+ *
2056
+ * It works by discarding the current version and adding the updated one, so
2057
+ * it is functionally equivalent to calling {@link MiniSearch#discard}
2058
+ * followed by {@link MiniSearch#add}. The ID of the updated document should
2059
+ * be the same as the original one.
2060
+ *
2061
+ * Since it uses {@link MiniSearch#discard} internally, this method relies on
2062
+ * vacuuming to clean up obsolete document references from the index, allowing
2063
+ * memory to be released (see {@link MiniSearch#discard}).
2064
+ *
2065
+ * @param updatedDocument The updated document to replace the old version
2066
+ * with
2067
+ */
2068
+ replace(updatedDocument) {
2069
+ const { idField, extractField } = this._options;
2070
+ const id = extractField(updatedDocument, idField);
2071
+ this.discard(id);
2072
+ this.add(updatedDocument);
2073
+ }
2074
+ /**
2075
+ * Triggers a manual vacuuming, cleaning up references to discarded documents
2076
+ * from the inverted index
2077
+ *
2078
+ * Vacuuming is only useful for applications that use the {@link
2079
+ * MiniSearch#discard} or {@link MiniSearch#replace} methods.
2080
+ *
2081
+ * By default, vacuuming is performed automatically when needed (controlled by
2082
+ * the `autoVacuum` field in {@link Options}), so there is usually no need to
2083
+ * call this method, unless one wants to make sure to perform vacuuming at a
2084
+ * specific moment.
2085
+ *
2086
+ * Vacuuming traverses all terms in the inverted index in batches, and cleans
2087
+ * up references to discarded documents from the posting list, allowing memory
2088
+ * to be released.
2089
+ *
2090
+ * The method takes an optional object as argument with the following keys:
2091
+ *
2092
+ * - `batchSize`: the size of each batch (1000 by default)
2093
+ *
2094
+ * - `batchWait`: the number of milliseconds to wait between batches (10 by
2095
+ * default)
2096
+ *
2097
+ * On large indexes, vacuuming could have a non-negligible cost: batching
2098
+ * avoids blocking the thread for long, diluting this cost so that it is not
2099
+ * negatively affecting the application. Nonetheless, this method should only
2100
+ * be called when necessary, and relying on automatic vacuuming is usually
2101
+ * better.
2102
+ *
2103
+ * It returns a promise that resolves (to undefined) when the clean up is
2104
+ * completed. If vacuuming is already ongoing at the time this method is
2105
+ * called, a new one is enqueued immediately after the ongoing one, and a
2106
+ * corresponding promise is returned. However, no more than one vacuuming is
2107
+ * enqueued on top of the ongoing one, even if this method is called more
2108
+ * times (enqueuing multiple ones would be useless).
2109
+ *
2110
+ * @param options Configuration options for the batch size and delay. See
2111
+ * {@link VacuumOptions}.
2112
+ */
2113
+ vacuum(options = {}) {
2114
+ return this.conditionalVacuum(options);
2115
+ }
2116
+ conditionalVacuum(options, conditions) {
2117
+ // If a vacuum is already ongoing, schedule another as soon as it finishes,
2118
+ // unless there's already one enqueued. If one was already enqueued, do not
2119
+ // enqueue another on top, but make sure that the conditions are the
2120
+ // broadest.
2121
+ if (this._currentVacuum) {
2122
+ this._enqueuedVacuumConditions = this._enqueuedVacuumConditions && conditions;
2123
+ if (this._enqueuedVacuum != null) {
2124
+ return this._enqueuedVacuum;
2125
+ }
2126
+ this._enqueuedVacuum = this._currentVacuum.then(() => {
2127
+ const conditions = this._enqueuedVacuumConditions;
2128
+ this._enqueuedVacuumConditions = defaultVacuumConditions;
2129
+ return this.performVacuuming(options, conditions);
2130
+ });
2131
+ return this._enqueuedVacuum;
2132
+ }
2133
+ if (this.vacuumConditionsMet(conditions) === false) {
2134
+ return Promise.resolve();
2135
+ }
2136
+ this._currentVacuum = this.performVacuuming(options);
2137
+ return this._currentVacuum;
2138
+ }
2139
+ async performVacuuming(options, conditions) {
2140
+ const initialDirtCount = this._dirtCount;
2141
+ if (this.vacuumConditionsMet(conditions)) {
2142
+ const batchSize = options.batchSize || defaultVacuumOptions.batchSize;
2143
+ const batchWait = options.batchWait || defaultVacuumOptions.batchWait;
2144
+ let i = 1;
2145
+ for (const [term, fieldsData] of this._index) {
2146
+ for (const [fieldId, fieldIndex] of fieldsData) {
2147
+ for (const [shortId] of fieldIndex) {
2148
+ if (this._documentIds.has(shortId)) {
2149
+ continue;
2150
+ }
2151
+ if (fieldIndex.size <= 1) {
2152
+ fieldsData.delete(fieldId);
2153
+ }
2154
+ else {
2155
+ fieldIndex.delete(shortId);
2156
+ }
2157
+ }
2158
+ }
2159
+ if (this._index.get(term).size === 0) {
2160
+ this._index.delete(term);
2161
+ }
2162
+ if (i % batchSize === 0) {
2163
+ await new Promise((resolve) => setTimeout(resolve, batchWait));
2164
+ }
2165
+ i += 1;
2166
+ }
2167
+ this._dirtCount -= initialDirtCount;
2168
+ }
2169
+ // Make the next lines always async, so they execute after this function returns
2170
+ await null;
2171
+ this._currentVacuum = this._enqueuedVacuum;
2172
+ this._enqueuedVacuum = null;
2173
+ }
2174
+ vacuumConditionsMet(conditions) {
2175
+ if (conditions == null) {
2176
+ return true;
2177
+ }
2178
+ let { minDirtCount, minDirtFactor } = conditions;
2179
+ minDirtCount = minDirtCount || defaultAutoVacuumOptions.minDirtCount;
2180
+ minDirtFactor = minDirtFactor || defaultAutoVacuumOptions.minDirtFactor;
2181
+ return this.dirtCount >= minDirtCount && this.dirtFactor >= minDirtFactor;
2182
+ }
2183
+ /**
2184
+ * Is `true` if a vacuuming operation is ongoing, `false` otherwise
2185
+ */
2186
+ get isVacuuming() {
2187
+ return this._currentVacuum != null;
2188
+ }
2189
+ /**
2190
+ * The number of documents discarded since the most recent vacuuming
2191
+ */
2192
+ get dirtCount() {
2193
+ return this._dirtCount;
2194
+ }
2195
+ /**
2196
+ * A number between 0 and 1 giving an indication about the proportion of
2197
+ * documents that are discarded, and can therefore be cleaned up by vacuuming.
2198
+ * A value close to 0 means that the index is relatively clean, while a higher
2199
+ * value means that the index is relatively dirty, and vacuuming could release
2200
+ * memory.
2201
+ */
2202
+ get dirtFactor() {
2203
+ return this._dirtCount / (1 + this._documentCount + this._dirtCount);
2204
+ }
2205
+ /**
2206
+ * Returns `true` if a document with the given ID is present in the index and
2207
+ * available for search, `false` otherwise
2208
+ *
2209
+ * @param id The document ID
2210
+ */
2211
+ has(id) {
2212
+ return this._idToShortId.has(id);
2213
+ }
2214
+ /**
2215
+ * Returns the stored fields (as configured in the `storeFields` constructor
2216
+ * option) for the given document ID. Returns `undefined` if the document is
2217
+ * not present in the index.
2218
+ *
2219
+ * @param id The document ID
2220
+ */
2221
+ getStoredFields(id) {
2222
+ const shortId = this._idToShortId.get(id);
2223
+ if (shortId == null) {
2224
+ return undefined;
2225
+ }
2226
+ return this._storedFields.get(shortId);
2227
+ }
2228
+ /**
2229
+ * Search for documents matching the given search query.
2230
+ *
2231
+ * The result is a list of scored document IDs matching the query, sorted by
2232
+ * descending score, and each including data about which terms were matched and
2233
+ * in which fields.
2234
+ *
2235
+ * ### Basic usage:
2236
+ *
2237
+ * ```javascript
2238
+ * // Search for "zen art motorcycle" with default options: terms have to match
2239
+ * // exactly, and individual terms are joined with OR
2240
+ * miniSearch.search('zen art motorcycle')
2241
+ * // => [ { id: 2, score: 2.77258, match: { ... } }, { id: 4, score: 1.38629, match: { ... } } ]
2242
+ * ```
2243
+ *
2244
+ * ### Restrict search to specific fields:
2245
+ *
2246
+ * ```javascript
2247
+ * // Search only in the 'title' field
2248
+ * miniSearch.search('zen', { fields: ['title'] })
2249
+ * ```
2250
+ *
2251
+ * ### Field boosting:
2252
+ *
2253
+ * ```javascript
2254
+ * // Boost a field
2255
+ * miniSearch.search('zen', { boost: { title: 2 } })
2256
+ * ```
2257
+ *
2258
+ * ### Prefix search:
2259
+ *
2260
+ * ```javascript
2261
+ * // Search for "moto" with prefix search (it will match documents
2262
+ * // containing terms that start with "moto" or "neuro")
2263
+ * miniSearch.search('moto neuro', { prefix: true })
2264
+ * ```
2265
+ *
2266
+ * ### Fuzzy search:
2267
+ *
2268
+ * ```javascript
2269
+ * // Search for "ismael" with fuzzy search (it will match documents containing
2270
+ * // terms similar to "ismael", with a maximum edit distance of 0.2 term.length
2271
+ * // (rounded to nearest integer)
2272
+ * miniSearch.search('ismael', { fuzzy: 0.2 })
2273
+ * ```
2274
+ *
2275
+ * ### Combining strategies:
2276
+ *
2277
+ * ```javascript
2278
+ * // Mix of exact match, prefix search, and fuzzy search
2279
+ * miniSearch.search('ismael mob', {
2280
+ * prefix: true,
2281
+ * fuzzy: 0.2
2282
+ * })
2283
+ * ```
2284
+ *
2285
+ * ### Advanced prefix and fuzzy search:
2286
+ *
2287
+ * ```javascript
2288
+ * // Perform fuzzy and prefix search depending on the search term. Here
2289
+ * // performing prefix and fuzzy search only on terms longer than 3 characters
2290
+ * miniSearch.search('ismael mob', {
2291
+ * prefix: term => term.length > 3
2292
+ * fuzzy: term => term.length > 3 ? 0.2 : null
2293
+ * })
2294
+ * ```
2295
+ *
2296
+ * ### Combine with AND:
2297
+ *
2298
+ * ```javascript
2299
+ * // Combine search terms with AND (to match only documents that contain both
2300
+ * // "motorcycle" and "art")
2301
+ * miniSearch.search('motorcycle art', { combineWith: 'AND' })
2302
+ * ```
2303
+ *
2304
+ * ### Combine with AND_NOT:
2305
+ *
2306
+ * There is also an AND_NOT combinator, that finds documents that match the
2307
+ * first term, but do not match any of the other terms. This combinator is
2308
+ * rarely useful with simple queries, and is meant to be used with advanced
2309
+ * query combinations (see later for more details).
2310
+ *
2311
+ * ### Filtering results:
2312
+ *
2313
+ * ```javascript
2314
+ * // Filter only results in the 'fiction' category (assuming that 'category'
2315
+ * // is a stored field)
2316
+ * miniSearch.search('motorcycle art', {
2317
+ * filter: (result) => result.category === 'fiction'
2318
+ * })
2319
+ * ```
2320
+ *
2321
+ * ### Wildcard query
2322
+ *
2323
+ * Searching for an empty string (assuming the default tokenizer) returns no
2324
+ * results. Sometimes though, one needs to match all documents, like in a
2325
+ * "wildcard" search. This is possible by passing the special value
2326
+ * {@link MiniSearch.wildcard} as the query:
2327
+ *
2328
+ * ```javascript
2329
+ * // Return search results for all documents
2330
+ * miniSearch.search(MiniSearch.wildcard)
2331
+ * ```
2332
+ *
2333
+ * Note that search options such as `filter` and `boostDocument` are still
2334
+ * applied, influencing which results are returned, and their order:
2335
+ *
2336
+ * ```javascript
2337
+ * // Return search results for all documents in the 'fiction' category
2338
+ * miniSearch.search(MiniSearch.wildcard, {
2339
+ * filter: (result) => result.category === 'fiction'
2340
+ * })
2341
+ * ```
2342
+ *
2343
+ * ### Advanced combination of queries:
2344
+ *
2345
+ * It is possible to combine different subqueries with OR, AND, and AND_NOT,
2346
+ * and even with different search options, by passing a query expression
2347
+ * tree object as the first argument, instead of a string.
2348
+ *
2349
+ * ```javascript
2350
+ * // Search for documents that contain "zen" and ("motorcycle" or "archery")
2351
+ * miniSearch.search({
2352
+ * combineWith: 'AND',
2353
+ * queries: [
2354
+ * 'zen',
2355
+ * {
2356
+ * combineWith: 'OR',
2357
+ * queries: ['motorcycle', 'archery']
2358
+ * }
2359
+ * ]
2360
+ * })
2361
+ *
2362
+ * // Search for documents that contain ("apple" or "pear") but not "juice" and
2363
+ * // not "tree"
2364
+ * miniSearch.search({
2365
+ * combineWith: 'AND_NOT',
2366
+ * queries: [
2367
+ * {
2368
+ * combineWith: 'OR',
2369
+ * queries: ['apple', 'pear']
2370
+ * },
2371
+ * 'juice',
2372
+ * 'tree'
2373
+ * ]
2374
+ * })
2375
+ * ```
2376
+ *
2377
+ * Each node in the expression tree can be either a string, or an object that
2378
+ * supports all {@link SearchOptions} fields, plus a `queries` array field for
2379
+ * subqueries.
2380
+ *
2381
+ * Note that, while this can become complicated to do by hand for complex or
2382
+ * deeply nested queries, it provides a formalized expression tree API for
2383
+ * external libraries that implement a parser for custom query languages.
2384
+ *
2385
+ * @param query Search query
2386
+ * @param searchOptions Search options. Each option, if not given, defaults to the corresponding value of `searchOptions` given to the constructor, or to the library default.
2387
+ */
2388
+ search(query, searchOptions = {}) {
2389
+ const { searchOptions: globalSearchOptions } = this._options;
2390
+ const searchOptionsWithDefaults = { ...globalSearchOptions, ...searchOptions };
2391
+ const rawResults = this.executeQuery(query, searchOptions);
2392
+ const skipSort = query === MiniSearch.wildcard && searchOptionsWithDefaults.boostDocument == null;
2393
+ return finalizeSearchResults({
2394
+ rawResults,
2395
+ getExternalId: (docId) => this._documentIds.get(docId),
2396
+ getStoredFields: (docId) => this._storedFields.get(docId),
2397
+ filter: searchOptionsWithDefaults.filter,
2398
+ skipSort
2399
+ });
2400
+ }
2401
+ /**
2402
+ * Provide suggestions for the given search query
2403
+ *
2404
+ * The result is a list of suggested modified search queries, derived from the
2405
+ * given search query, each with a relevance score, sorted by descending score.
2406
+ *
2407
+ * By default, it uses the same options used for search, except that by
2408
+ * default it performs prefix search on the last term of the query, and
2409
+ * combine terms with `'AND'` (requiring all query terms to match). Custom
2410
+ * options can be passed as a second argument. Defaults can be changed upon
2411
+ * calling the {@link MiniSearch} constructor, by passing a
2412
+ * `autoSuggestOptions` option.
2413
+ *
2414
+ * ### Basic usage:
2415
+ *
2416
+ * ```javascript
2417
+ * // Get suggestions for 'neuro':
2418
+ * miniSearch.autoSuggest('neuro')
2419
+ * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 0.46240 } ]
2420
+ * ```
2421
+ *
2422
+ * ### Multiple words:
2423
+ *
2424
+ * ```javascript
2425
+ * // Get suggestions for 'zen ar':
2426
+ * miniSearch.autoSuggest('zen ar')
2427
+ * // => [
2428
+ * // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 },
2429
+ * // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 }
2430
+ * // ]
2431
+ * ```
2432
+ *
2433
+ * ### Fuzzy suggestions:
2434
+ *
2435
+ * ```javascript
2436
+ * // Correct spelling mistakes using fuzzy search:
2437
+ * miniSearch.autoSuggest('neromancer', { fuzzy: 0.2 })
2438
+ * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 1.03998 } ]
2439
+ * ```
2440
+ *
2441
+ * ### Filtering:
2442
+ *
2443
+ * ```javascript
2444
+ * // Get suggestions for 'zen ar', but only within the 'fiction' category
2445
+ * // (assuming that 'category' is a stored field):
2446
+ * miniSearch.autoSuggest('zen ar', {
2447
+ * filter: (result) => result.category === 'fiction'
2448
+ * })
2449
+ * // => [
2450
+ * // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 },
2451
+ * // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 }
2452
+ * // ]
2453
+ * ```
2454
+ *
2455
+ * @param queryString Query string to be expanded into suggestions
2456
+ * @param options Search options. The supported options and default values
2457
+ * are the same as for the {@link MiniSearch#search} method, except that by
2458
+ * default prefix search is performed on the last term in the query, and terms
2459
+ * are combined with `'AND'`.
2460
+ * @return A sorted array of suggestions sorted by relevance score.
2461
+ */
2462
+ autoSuggest(queryString, options = {}) {
2463
+ options = { ...this._options.autoSuggestOptions, ...options };
2464
+ const suggestions = new Map();
2465
+ for (const { score, terms } of this.search(queryString, options)) {
2466
+ const phrase = terms.join(' ');
2467
+ const suggestion = suggestions.get(phrase);
2468
+ if (suggestion != null) {
2469
+ suggestion.score += score;
2470
+ suggestion.count += 1;
2471
+ }
2472
+ else {
2473
+ suggestions.set(phrase, { score, terms, count: 1 });
2474
+ }
2475
+ }
2476
+ const results = [];
2477
+ for (const [suggestion, { score, terms, count }] of suggestions) {
2478
+ results.push({ suggestion, terms, score: score / count });
2479
+ }
2480
+ results.sort(byScore);
2481
+ return results;
2482
+ }
2483
+ /**
2484
+ * Total number of documents available to search
2485
+ */
2486
+ get documentCount() {
2487
+ return this._documentCount;
2488
+ }
2489
+ /**
2490
+ * Number of terms in the index
2491
+ */
2492
+ get termCount() {
2493
+ return this._index.size;
2494
+ }
2495
+ /**
2496
+ * Deserializes a JSON index (serialized with `JSON.stringify(miniSearch)`)
2497
+ * and instantiates a MiniSearch instance. It should be given the same options
2498
+ * originally used when serializing the index.
2499
+ *
2500
+ * ### Usage:
2501
+ *
2502
+ * ```javascript
2503
+ * // If the index was serialized with:
2504
+ * let miniSearch = new MiniSearch({ fields: ['title', 'text'] })
2505
+ * miniSearch.addAll(documents)
2506
+ *
2507
+ * const json = JSON.stringify(miniSearch)
2508
+ * // It can later be deserialized like this:
2509
+ * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] })
2510
+ * ```
2511
+ *
2512
+ * @param json JSON-serialized index
2513
+ * @param options configuration options, same as the constructor
2514
+ * @return An instance of MiniSearch deserialized from the given JSON.
2515
+ */
2516
+ static loadJSON(json, options) {
2517
+ if (options == null) {
2518
+ throw new Error('MiniSearch: loadJSON should be given the same options used when serializing the index');
2519
+ }
2520
+ return this.loadJS(JSON.parse(json), options);
2521
+ }
2522
+ /**
2523
+ * Async equivalent of {@link MiniSearch.loadJSON}
2524
+ *
2525
+ * This function is an alternative to {@link MiniSearch.loadJSON} that returns
2526
+ * a promise, and loads the index in batches, leaving pauses between them to avoid
2527
+ * blocking the main thread. It tends to be slower than the synchronous
2528
+ * version, but does not block the main thread, so it can be a better choice
2529
+ * when deserializing very large indexes.
2530
+ *
2531
+ * @param json JSON-serialized index
2532
+ * @param options configuration options, same as the constructor
2533
+ * @return A Promise that will resolve to an instance of MiniSearch deserialized from the given JSON.
2534
+ */
2535
+ static async loadJSONAsync(json, options) {
2536
+ if (options == null) {
2537
+ throw new Error('MiniSearch: loadJSON should be given the same options used when serializing the index');
2538
+ }
2539
+ return this.loadJSAsync(JSON.parse(json), options);
2540
+ }
2541
+ /**
2542
+ * Returns the default value of an option. It will throw an error if no option
2543
+ * with the given name exists.
2544
+ *
2545
+ * @param optionName Name of the option
2546
+ * @return The default value of the given option
2547
+ *
2548
+ * ### Usage:
2549
+ *
2550
+ * ```javascript
2551
+ * // Get default tokenizer
2552
+ * MiniSearch.getDefault('tokenize')
2553
+ *
2554
+ * // Get default term processor
2555
+ * MiniSearch.getDefault('processTerm')
2556
+ *
2557
+ * // Unknown options will throw an error
2558
+ * MiniSearch.getDefault('notExisting')
2559
+ * // => throws 'MiniSearch: unknown option "notExisting"'
2560
+ * ```
2561
+ */
2562
+ static getDefault(optionName) {
2563
+ if (defaultOptions.hasOwnProperty(optionName)) {
2564
+ return getOwnProperty(defaultOptions, optionName);
2565
+ }
2566
+ else {
2567
+ throw new Error(`MiniSearch: unknown option "${optionName}"`);
2568
+ }
2569
+ }
2570
+ /**
2571
+ * @ignore
2572
+ */
2573
+ static loadJS(js, options) {
2574
+ const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
2575
+ const miniSearch = this.instantiateMiniSearch(js, options);
2576
+ miniSearch._documentIds = objectToNumericMap(documentIds);
2577
+ miniSearch._fieldLength = objectToNumericMap(fieldLength);
2578
+ miniSearch._storedFields = objectToNumericMap(storedFields);
2579
+ for (const [shortId, id] of miniSearch._documentIds) {
2580
+ miniSearch._idToShortId.set(id, shortId);
2581
+ }
2582
+ for (const [term, data] of index) {
2583
+ const dataMap = new Map();
2584
+ for (const fieldId of Object.keys(data)) {
2585
+ let indexEntry = data[fieldId];
2586
+ // Version 1 used to nest the index entry inside a field called ds
2587
+ if (serializationVersion === 1) {
2588
+ indexEntry = indexEntry.ds;
2589
+ }
2590
+ dataMap.set(parseInt(fieldId, 10), objectToNumericMap(indexEntry));
2591
+ }
2592
+ miniSearch._index.set(term, dataMap);
2593
+ }
2594
+ return miniSearch;
2595
+ }
2596
+ /**
2597
+ * @ignore
2598
+ */
2599
+ static async loadJSAsync(js, options) {
2600
+ const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
2601
+ const miniSearch = this.instantiateMiniSearch(js, options);
2602
+ miniSearch._documentIds = await objectToNumericMapAsync(documentIds);
2603
+ miniSearch._fieldLength = await objectToNumericMapAsync(fieldLength);
2604
+ miniSearch._storedFields = await objectToNumericMapAsync(storedFields);
2605
+ for (const [shortId, id] of miniSearch._documentIds) {
2606
+ miniSearch._idToShortId.set(id, shortId);
2607
+ }
2608
+ let count = 0;
2609
+ for (const [term, data] of index) {
2610
+ const dataMap = new Map();
2611
+ for (const fieldId of Object.keys(data)) {
2612
+ let indexEntry = data[fieldId];
2613
+ // Version 1 used to nest the index entry inside a field called ds
2614
+ if (serializationVersion === 1) {
2615
+ indexEntry = indexEntry.ds;
2616
+ }
2617
+ dataMap.set(parseInt(fieldId, 10), await objectToNumericMapAsync(indexEntry));
2618
+ }
2619
+ if (++count % 1000 === 0)
2620
+ await wait(0);
2621
+ miniSearch._index.set(term, dataMap);
2622
+ }
2623
+ return miniSearch;
2624
+ }
2625
+ /**
2626
+ * @ignore
2627
+ */
2628
+ static instantiateMiniSearch(js, options) {
2629
+ const { documentCount, nextId, fieldIds, averageFieldLength, dirtCount, serializationVersion } = js;
2630
+ if (serializationVersion !== 1 && serializationVersion !== 2) {
2631
+ throw new Error('MiniSearch: cannot deserialize an index created with an incompatible version');
2632
+ }
2633
+ const miniSearch = new MiniSearch(options);
2634
+ miniSearch._documentCount = documentCount;
2635
+ miniSearch._nextId = nextId;
2636
+ miniSearch._idToShortId = new Map();
2637
+ miniSearch._fieldIds = fieldIds;
2638
+ miniSearch._avgFieldLength = averageFieldLength;
2639
+ miniSearch._dirtCount = dirtCount || 0;
2640
+ miniSearch._index = new SearchableMap();
2641
+ return miniSearch;
2642
+ }
2643
+ /**
2644
+ * @ignore
2645
+ */
2646
+ executeQuery(query, searchOptions = {}) {
2647
+ if (query === MiniSearch.wildcard) {
2648
+ return this.executeWildcardQuery(searchOptions);
2649
+ }
2650
+ if (typeof query !== 'string') {
2651
+ const options = { ...searchOptions, ...query, queries: undefined };
2652
+ const results = query.queries.map((subquery) => this.executeQuery(subquery, options));
2653
+ return this.combineResults(results, options.combineWith);
2654
+ }
2655
+ const { tokenize, processTerm, searchOptions: globalSearchOptions } = this._options;
2656
+ const options = { tokenize, processTerm, ...globalSearchOptions, ...searchOptions };
2657
+ const { tokenize: searchTokenize, processTerm: searchProcessTerm } = options;
2658
+ const terms = searchTokenize(query)
2659
+ .flatMap((term) => searchProcessTerm(term))
2660
+ .filter((term) => !!term);
2661
+ const queries = terms.map(termToQuerySpec(options));
2662
+ const results = queries.map(query => this.executeQuerySpec(query, options));
2663
+ return this.combineResults(results, options.combineWith);
2664
+ }
2665
+ /**
2666
+ * @ignore
2667
+ */
2668
+ executeQuerySpec(query, searchOptions) {
2669
+ const options = { ...this._options.searchOptions, ...searchOptions };
2670
+ const boosts = (options.fields || this._options.fields).reduce((boosts, field) => ({ ...boosts, [field]: getOwnProperty(options.boost, field) || 1 }), {});
2671
+ const { boostDocument, weights, maxFuzzy, bm25: bm25params } = options;
2672
+ const { fuzzy: fuzzyWeight, prefix: prefixWeight } = { ...defaultSearchOptions.weights, ...weights };
2673
+ const data = this._index.get(query.term);
2674
+ const results = this.termResults(query.term, query.term, 1, query.termBoost, data, boosts, boostDocument, bm25params);
2675
+ let prefixMatches;
2676
+ let fuzzyMatches;
2677
+ if (query.prefix) {
2678
+ prefixMatches = this._index.atPrefix(query.term);
2679
+ }
2680
+ if (query.fuzzy) {
2681
+ const fuzzy = (query.fuzzy === true) ? 0.2 : query.fuzzy;
2682
+ const maxDistance = fuzzy < 1 ? Math.min(maxFuzzy, Math.round(query.term.length * fuzzy)) : fuzzy;
2683
+ if (maxDistance)
2684
+ fuzzyMatches = this._index.fuzzyGet(query.term, maxDistance);
2685
+ }
2686
+ if (prefixMatches) {
2687
+ for (const [term, data] of prefixMatches) {
2688
+ const distance = term.length - query.term.length;
2689
+ if (!distance) {
2690
+ continue;
2691
+ } // Skip exact match.
2692
+ // Delete the term from fuzzy results (if present) if it is also a
2693
+ // prefix result. This entry will always be scored as a prefix result.
2694
+ fuzzyMatches === null || fuzzyMatches === void 0 ? void 0 : fuzzyMatches.delete(term);
2695
+ // Weight gradually approaches 0 as distance goes to infinity, with the
2696
+ // weight for the hypothetical distance 0 being equal to prefixWeight.
2697
+ // The rate of change is much lower than that of fuzzy matches to
2698
+ // account for the fact that prefix matches stay more relevant than
2699
+ // fuzzy matches for longer distances.
2700
+ const weight = prefixWeight * term.length / (term.length + 0.3 * distance);
2701
+ this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results);
2702
+ }
2703
+ }
2704
+ if (fuzzyMatches) {
2705
+ for (const term of fuzzyMatches.keys()) {
2706
+ const [data, distance] = fuzzyMatches.get(term);
2707
+ if (!distance) {
2708
+ continue;
2709
+ } // Skip exact match.
2710
+ // Weight gradually approaches 0 as distance goes to infinity, with the
2711
+ // weight for the hypothetical distance 0 being equal to fuzzyWeight.
2712
+ const weight = fuzzyWeight * term.length / (term.length + distance);
2713
+ this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results);
2714
+ }
2715
+ }
2716
+ return results;
2717
+ }
2718
+ /**
2719
+ * @ignore
2720
+ */
2721
+ executeWildcardQuery(searchOptions) {
2722
+ const results = new Map();
2723
+ const options = { ...this._options.searchOptions, ...searchOptions };
2724
+ for (const [shortId, id] of this._documentIds) {
2725
+ const score = options.boostDocument ? options.boostDocument(id, '', this._storedFields.get(shortId)) : 1;
2726
+ results.set(shortId, {
2727
+ score,
2728
+ terms: [],
2729
+ match: {}
2730
+ });
2731
+ }
2732
+ return results;
2733
+ }
2734
+ /**
2735
+ * @ignore
2736
+ */
2737
+ combineResults(results, combineWith = OR) {
2738
+ return combineResults(results, combineWith);
2739
+ }
2740
+ /**
2741
+ * Build a read-only {@link FrozenMiniSearch} snapshot optimized for RAM and search CPU.
2742
+ */
2743
+ freeze() {
2744
+ return freezeFromMiniSearch(this);
2745
+ }
2746
+ /**
2747
+ * Allows serialization of the index to JSON, to possibly store it and later
2748
+ * deserialize it with {@link MiniSearch.loadJSON}.
2749
+ *
2750
+ * Normally one does not directly call this method, but rather call the
2751
+ * standard JavaScript `JSON.stringify()` passing the {@link MiniSearch}
2752
+ * instance, and JavaScript will internally call this method. Upon
2753
+ * deserialization, one must pass to {@link MiniSearch.loadJSON} the same
2754
+ * options used to create the original instance that was serialized.
2755
+ *
2756
+ * ### Usage:
2757
+ *
2758
+ * ```javascript
2759
+ * // Serialize the index:
2760
+ * let miniSearch = new MiniSearch({ fields: ['title', 'text'] })
2761
+ * miniSearch.addAll(documents)
2762
+ * const json = JSON.stringify(miniSearch)
2763
+ *
2764
+ * // Later, to deserialize it:
2765
+ * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] })
2766
+ * ```
2767
+ *
2768
+ * @return A plain-object serializable representation of the search index.
2769
+ */
2770
+ toJSON() {
2771
+ const index = [];
2772
+ for (const [term, fieldIndex] of this._index) {
2773
+ const data = {};
2774
+ for (const [fieldId, freqs] of fieldIndex) {
2775
+ data[fieldId] = Object.fromEntries(freqs);
2776
+ }
2777
+ index.push([term, data]);
2778
+ }
2779
+ return {
2780
+ documentCount: this._documentCount,
2781
+ nextId: this._nextId,
2782
+ documentIds: Object.fromEntries(this._documentIds),
2783
+ fieldIds: this._fieldIds,
2784
+ fieldLength: Object.fromEntries(this._fieldLength),
2785
+ averageFieldLength: this._avgFieldLength,
2786
+ storedFields: Object.fromEntries(this._storedFields),
2787
+ dirtCount: this._dirtCount,
2788
+ index,
2789
+ serializationVersion: 2
2790
+ };
2791
+ }
2792
+ /**
2793
+ * @ignore
2794
+ */
2795
+ termResults(sourceTerm, derivedTerm, termWeight, termBoost, fieldTermData, fieldBoosts, boostDocumentFn, bm25params, results = new Map()) {
2796
+ return aggregateTerm(sourceTerm, derivedTerm, termWeight, termBoost, fieldTermData == null ? undefined : mapFieldTermData(fieldTermData), fieldBoosts, {
2797
+ documentCount: this._documentCount,
2798
+ avgFieldLength: this._avgFieldLength,
2799
+ fieldIds: this._fieldIds,
2800
+ getFieldLength: (docId, fieldId) => this._fieldLength.get(docId)[fieldId],
2801
+ getExternalId: (docId) => this._documentIds.get(docId),
2802
+ getStoredFields: (docId) => this._storedFields.get(docId),
2803
+ isDocActive: (docId) => this._documentIds.has(docId),
2804
+ onInactiveDoc: (docId, fieldId, term) => this.removeTerm(fieldId, docId, term)
2805
+ }, boostDocumentFn, bm25params, results);
2806
+ }
2807
+ /**
2808
+ * @ignore
2809
+ */
2810
+ addTerm(fieldId, documentId, term) {
2811
+ const indexData = this._index.fetch(term, createMap);
2812
+ let fieldIndex = indexData.get(fieldId);
2813
+ if (fieldIndex == null) {
2814
+ fieldIndex = new Map();
2815
+ fieldIndex.set(documentId, 1);
2816
+ indexData.set(fieldId, fieldIndex);
2817
+ }
2818
+ else {
2819
+ const docs = fieldIndex.get(documentId);
2820
+ fieldIndex.set(documentId, (docs || 0) + 1);
2821
+ }
2822
+ }
2823
+ /**
2824
+ * @ignore
2825
+ */
2826
+ removeTerm(fieldId, documentId, term) {
2827
+ if (!this._index.has(term)) {
2828
+ this.warnDocumentChanged(documentId, fieldId, term);
2829
+ return;
2830
+ }
2831
+ const indexData = this._index.fetch(term, createMap);
2832
+ const fieldIndex = indexData.get(fieldId);
2833
+ if (fieldIndex == null || fieldIndex.get(documentId) == null) {
2834
+ this.warnDocumentChanged(documentId, fieldId, term);
2835
+ }
2836
+ else if (fieldIndex.get(documentId) <= 1) {
2837
+ if (fieldIndex.size <= 1) {
2838
+ indexData.delete(fieldId);
2839
+ }
2840
+ else {
2841
+ fieldIndex.delete(documentId);
2842
+ }
2843
+ }
2844
+ else {
2845
+ fieldIndex.set(documentId, fieldIndex.get(documentId) - 1);
2846
+ }
2847
+ if (this._index.get(term).size === 0) {
2848
+ this._index.delete(term);
2849
+ }
2850
+ }
2851
+ /**
2852
+ * @ignore
2853
+ */
2854
+ warnDocumentChanged(shortDocumentId, fieldId, term) {
2855
+ for (const fieldName of Object.keys(this._fieldIds)) {
2856
+ if (this._fieldIds[fieldName] === fieldId) {
2857
+ this._options.logger('warn', `MiniSearch: document with ID ${this._documentIds.get(shortDocumentId)} has changed before removal: term "${term}" was not present in field "${fieldName}". Removing a document after it has changed can corrupt the index!`, 'version_conflict');
2858
+ return;
2859
+ }
2860
+ }
2861
+ }
2862
+ /**
2863
+ * @ignore
2864
+ */
2865
+ addDocumentId(documentId) {
2866
+ const shortDocumentId = this._nextId;
2867
+ this._idToShortId.set(documentId, shortDocumentId);
2868
+ this._documentIds.set(shortDocumentId, documentId);
2869
+ this._documentCount += 1;
2870
+ this._nextId += 1;
2871
+ return shortDocumentId;
2872
+ }
2873
+ /**
2874
+ * @ignore
2875
+ */
2876
+ addFields(fields) {
2877
+ for (let i = 0; i < fields.length; i++) {
2878
+ this._fieldIds[fields[i]] = i;
2879
+ }
2880
+ }
2881
+ /**
2882
+ * @ignore
2883
+ */
2884
+ addFieldLength(documentId, fieldId, count, length) {
2885
+ let fieldLengths = this._fieldLength.get(documentId);
2886
+ if (fieldLengths == null)
2887
+ this._fieldLength.set(documentId, fieldLengths = []);
2888
+ fieldLengths[fieldId] = length;
2889
+ const averageFieldLength = this._avgFieldLength[fieldId] || 0;
2890
+ const totalFieldLength = (averageFieldLength * count) + length;
2891
+ this._avgFieldLength[fieldId] = totalFieldLength / (count + 1);
2892
+ }
2893
+ /**
2894
+ * @ignore
2895
+ */
2896
+ removeFieldLength(documentId, fieldId, count, length) {
2897
+ if (count === 1) {
2898
+ this._avgFieldLength[fieldId] = 0;
2899
+ return;
2900
+ }
2901
+ const totalFieldLength = (this._avgFieldLength[fieldId] * count) - length;
2902
+ this._avgFieldLength[fieldId] = totalFieldLength / (count - 1);
2903
+ }
2904
+ }
2905
+ /**
2906
+ * The special wildcard symbol that can be passed to {@link MiniSearch#search}
2907
+ * to match all documents
2908
+ */
2909
+ MiniSearch.wildcard = WILDCARD_QUERY;
2910
+ const defaultOptions = {
2911
+ idField: 'id',
2912
+ extractField: (document, fieldName) => document[fieldName],
2913
+ stringifyField: (fieldValue, fieldName) => fieldValue.toString(),
2914
+ tokenize: (text) => text.split(SPACE_OR_PUNCTUATION),
2915
+ processTerm: (term) => term.toLowerCase(),
2916
+ fields: undefined,
2917
+ searchOptions: undefined,
2918
+ storeFields: [],
2919
+ logger: (level, message) => {
2920
+ if (typeof (console === null || console === void 0 ? void 0 : console[level]) === 'function')
2921
+ console[level](message);
2922
+ },
2923
+ autoVacuum: true
2924
+ };
2925
+ const defaultVacuumOptions = { batchSize: 1000, batchWait: 10 };
2926
+ const defaultVacuumConditions = { minDirtFactor: 0.1, minDirtCount: 20 };
2927
+ const defaultAutoVacuumOptions = { ...defaultVacuumOptions, ...defaultVacuumConditions };
2928
+ const createMap = () => new Map();
2929
+ const objectToNumericMap = (object) => {
2930
+ const map = new Map();
2931
+ for (const key of Object.keys(object)) {
2932
+ map.set(parseInt(key, 10), object[key]);
2933
+ }
2934
+ return map;
2935
+ };
2936
+ const objectToNumericMapAsync = async (object) => {
2937
+ const map = new Map();
2938
+ let count = 0;
2939
+ for (const key of Object.keys(object)) {
2940
+ map.set(parseInt(key, 10), object[key]);
2941
+ if (++count % 1000 === 0) {
2942
+ await wait(0);
2943
+ }
2944
+ }
2945
+ return map;
2946
+ };
2947
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2948
+
2949
+ export { AND, AND_NOT, FrozenMiniSearch, OR, assembleFrozen, buildFrozenFromDocuments, MiniSearch as default, freezeFromMiniSearch, frozenMemoryBreakdown };