@meddleware/dev 0.0.4 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. package/docs/.vitepress/cache/deps/@meddleware_ui.js +614 -0
  2. package/docs/.vitepress/cache/deps/@meddleware_ui.js.map +1 -0
  3. package/docs/.vitepress/cache/deps/_metadata.json +56 -0
  4. package/docs/.vitepress/cache/deps/package.json +3 -0
  5. package/docs/.vitepress/cache/deps/vitepress_n_@vue_devtools-api.js +3808 -0
  6. package/docs/.vitepress/cache/deps/vitepress_n_@vue_devtools-api.js.map +1 -0
  7. package/docs/.vitepress/cache/deps/vitepress_n_@vueuse_core.js +10171 -0
  8. package/docs/.vitepress/cache/deps/vitepress_n_@vueuse_core.js.map +1 -0
  9. package/docs/.vitepress/cache/deps/vitepress_n_@vueuse_integrations_useFocusTrap.js +1225 -0
  10. package/docs/.vitepress/cache/deps/vitepress_n_@vueuse_integrations_useFocusTrap.js.map +1 -0
  11. package/docs/.vitepress/cache/deps/vitepress_n_mark__js_src_vanilla__js.js +1492 -0
  12. package/docs/.vitepress/cache/deps/vitepress_n_mark__js_src_vanilla__js.js.map +1 -0
  13. package/docs/.vitepress/cache/deps/vitepress_n_minisearch.js +1773 -0
  14. package/docs/.vitepress/cache/deps/vitepress_n_minisearch.js.map +1 -0
  15. package/docs/.vitepress/cache/deps/vue.js +2 -0
  16. package/docs/.vitepress/cache/deps/vue.runtime.esm-bundler-Bo_ScjpA.js +8890 -0
  17. package/docs/.vitepress/cache/deps/vue.runtime.esm-bundler-Bo_ScjpA.js.map +1 -0
  18. package/docs/.vitepress/config.ts +1 -4
  19. package/docs/.vitepress/theme/Layout.vue +13 -0
  20. package/docs/.vitepress/theme/custom.css +6 -0
  21. package/docs/.vitepress/theme/index.ts +2 -0
  22. package/docs/index.md +0 -4
  23. package/package.json +2 -2
  24. package/tsconfig.json +1 -1
@@ -0,0 +1,1773 @@
1
+ //#region node_modules/minisearch/dist/es/index.js
2
+ /** @ignore */
3
+ var ENTRIES = "ENTRIES";
4
+ /** @ignore */
5
+ var KEYS = "KEYS";
6
+ /** @ignore */
7
+ var VALUES = "VALUES";
8
+ /** @ignore */
9
+ var LEAF = "";
10
+ /**
11
+ * @private
12
+ */
13
+ var TreeIterator = class {
14
+ constructor(set, type) {
15
+ const node = set._tree;
16
+ const keys = Array.from(node.keys());
17
+ this.set = set;
18
+ this._type = type;
19
+ this._path = keys.length > 0 ? [{
20
+ node,
21
+ keys
22
+ }] : [];
23
+ }
24
+ next() {
25
+ const value = this.dive();
26
+ this.backtrack();
27
+ return value;
28
+ }
29
+ dive() {
30
+ if (this._path.length === 0) return {
31
+ done: true,
32
+ value: void 0
33
+ };
34
+ const { node, keys } = last$1(this._path);
35
+ if (last$1(keys) === LEAF) return {
36
+ done: false,
37
+ value: this.result()
38
+ };
39
+ const child = node.get(last$1(keys));
40
+ this._path.push({
41
+ node: child,
42
+ keys: Array.from(child.keys())
43
+ });
44
+ return this.dive();
45
+ }
46
+ backtrack() {
47
+ if (this._path.length === 0) return;
48
+ const keys = last$1(this._path).keys;
49
+ keys.pop();
50
+ if (keys.length > 0) return;
51
+ this._path.pop();
52
+ this.backtrack();
53
+ }
54
+ key() {
55
+ return this.set._prefix + this._path.map(({ keys }) => last$1(keys)).filter((key) => key !== LEAF).join("");
56
+ }
57
+ value() {
58
+ return last$1(this._path).node.get(LEAF);
59
+ }
60
+ result() {
61
+ switch (this._type) {
62
+ case VALUES: return this.value();
63
+ case KEYS: return this.key();
64
+ default: return [this.key(), this.value()];
65
+ }
66
+ }
67
+ [Symbol.iterator]() {
68
+ return this;
69
+ }
70
+ };
71
+ var last$1 = (array) => {
72
+ return array[array.length - 1];
73
+ };
74
+ /**
75
+ * @ignore
76
+ */
77
+ var fuzzySearch = (node, query, maxDistance) => {
78
+ const results = /* @__PURE__ */ new Map();
79
+ if (query === void 0) return results;
80
+ const n = query.length + 1;
81
+ const m = n + maxDistance;
82
+ const matrix = new Uint8Array(m * n).fill(maxDistance + 1);
83
+ for (let j = 0; j < n; ++j) matrix[j] = j;
84
+ for (let i = 1; i < m; ++i) matrix[i * n] = i;
85
+ recurse(node, query, maxDistance, results, matrix, 1, n, "");
86
+ return results;
87
+ };
88
+ var recurse = (node, query, maxDistance, results, matrix, m, n, prefix) => {
89
+ const offset = m * n;
90
+ key: for (const key of node.keys()) if (key === LEAF) {
91
+ const distance = matrix[offset - 1];
92
+ if (distance <= maxDistance) results.set(prefix, [node.get(key), distance]);
93
+ } else {
94
+ let i = m;
95
+ for (let pos = 0; pos < key.length; ++pos, ++i) {
96
+ const char = key[pos];
97
+ const thisRowOffset = n * i;
98
+ const prevRowOffset = thisRowOffset - n;
99
+ let minDistance = matrix[thisRowOffset];
100
+ const jmin = Math.max(0, i - maxDistance - 1);
101
+ const jmax = Math.min(n - 1, i + maxDistance);
102
+ for (let j = jmin; j < jmax; ++j) {
103
+ const different = char !== query[j];
104
+ const rpl = matrix[prevRowOffset + j] + +different;
105
+ const del = matrix[prevRowOffset + j + 1] + 1;
106
+ const ins = matrix[thisRowOffset + j] + 1;
107
+ const dist = matrix[thisRowOffset + j + 1] = Math.min(rpl, del, ins);
108
+ if (dist < minDistance) minDistance = dist;
109
+ }
110
+ if (minDistance > maxDistance) continue key;
111
+ }
112
+ recurse(node.get(key), query, maxDistance, results, matrix, i, n, prefix + key);
113
+ }
114
+ };
115
+ /**
116
+ * A class implementing the same interface as a standard JavaScript
117
+ * [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
118
+ * with string keys, but adding support for efficiently searching entries with
119
+ * prefix or fuzzy search. This class is used internally by {@link MiniSearch}
120
+ * as the inverted index data structure. The implementation is a radix tree
121
+ * (compressed prefix tree).
122
+ *
123
+ * Since this class can be of general utility beyond _MiniSearch_, it is
124
+ * exported by the `minisearch` package and can be imported (or required) as
125
+ * `minisearch/SearchableMap`.
126
+ *
127
+ * @typeParam T The type of the values stored in the map.
128
+ */
129
+ var SearchableMap = class SearchableMap {
130
+ /**
131
+ * The constructor is normally called without arguments, creating an empty
132
+ * map. In order to create a {@link SearchableMap} from an iterable or from an
133
+ * object, check {@link SearchableMap.from} and {@link
134
+ * SearchableMap.fromObject}.
135
+ *
136
+ * The constructor arguments are for internal use, when creating derived
137
+ * mutable views of a map at a prefix.
138
+ */
139
+ constructor(tree = /* @__PURE__ */ new Map(), prefix = "") {
140
+ this._size = void 0;
141
+ this._tree = tree;
142
+ this._prefix = prefix;
143
+ }
144
+ /**
145
+ * Creates and returns a mutable view of this {@link SearchableMap},
146
+ * containing only entries that share the given prefix.
147
+ *
148
+ * ### Usage:
149
+ *
150
+ * ```javascript
151
+ * let map = new SearchableMap()
152
+ * map.set("unicorn", 1)
153
+ * map.set("universe", 2)
154
+ * map.set("university", 3)
155
+ * map.set("unique", 4)
156
+ * map.set("hello", 5)
157
+ *
158
+ * let uni = map.atPrefix("uni")
159
+ * uni.get("unique") // => 4
160
+ * uni.get("unicorn") // => 1
161
+ * uni.get("hello") // => undefined
162
+ *
163
+ * let univer = map.atPrefix("univer")
164
+ * univer.get("unique") // => undefined
165
+ * univer.get("universe") // => 2
166
+ * univer.get("university") // => 3
167
+ * ```
168
+ *
169
+ * @param prefix The prefix
170
+ * @return A {@link SearchableMap} representing a mutable view of the original
171
+ * Map at the given prefix
172
+ */
173
+ atPrefix(prefix) {
174
+ if (!prefix.startsWith(this._prefix)) throw new Error("Mismatched prefix");
175
+ const [node, path] = trackDown(this._tree, prefix.slice(this._prefix.length));
176
+ if (node === void 0) {
177
+ const [parentNode, key] = last(path);
178
+ for (const k of parentNode.keys()) if (k !== LEAF && k.startsWith(key)) {
179
+ const node = /* @__PURE__ */ new Map();
180
+ node.set(k.slice(key.length), parentNode.get(k));
181
+ return new SearchableMap(node, prefix);
182
+ }
183
+ }
184
+ return new SearchableMap(node, prefix);
185
+ }
186
+ /**
187
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/clear
188
+ */
189
+ clear() {
190
+ this._size = void 0;
191
+ this._tree.clear();
192
+ }
193
+ /**
194
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/delete
195
+ * @param key Key to delete
196
+ */
197
+ delete(key) {
198
+ this._size = void 0;
199
+ return remove(this._tree, key);
200
+ }
201
+ /**
202
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries
203
+ * @return An iterator iterating through `[key, value]` entries.
204
+ */
205
+ entries() {
206
+ return new TreeIterator(this, ENTRIES);
207
+ }
208
+ /**
209
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach
210
+ * @param fn Iteration function
211
+ */
212
+ forEach(fn) {
213
+ for (const [key, value] of this) fn(key, value, this);
214
+ }
215
+ /**
216
+ * Returns a Map of all the entries that have a key within the given edit
217
+ * distance from the search key. The keys of the returned Map are the matching
218
+ * keys, while the values are two-element arrays where the first element is
219
+ * the value associated to the key, and the second is the edit distance of the
220
+ * key to the search key.
221
+ *
222
+ * ### Usage:
223
+ *
224
+ * ```javascript
225
+ * let map = new SearchableMap()
226
+ * map.set('hello', 'world')
227
+ * map.set('hell', 'yeah')
228
+ * map.set('ciao', 'mondo')
229
+ *
230
+ * // Get all entries that match the key 'hallo' with a maximum edit distance of 2
231
+ * map.fuzzyGet('hallo', 2)
232
+ * // => Map(2) { 'hello' => ['world', 1], 'hell' => ['yeah', 2] }
233
+ *
234
+ * // In the example, the "hello" key has value "world" and edit distance of 1
235
+ * // (change "e" to "a"), the key "hell" has value "yeah" and edit distance of 2
236
+ * // (change "e" to "a", delete "o")
237
+ * ```
238
+ *
239
+ * @param key The search key
240
+ * @param maxEditDistance The maximum edit distance (Levenshtein)
241
+ * @return A Map of the matching keys to their value and edit distance
242
+ */
243
+ fuzzyGet(key, maxEditDistance) {
244
+ return fuzzySearch(this._tree, key, maxEditDistance);
245
+ }
246
+ /**
247
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get
248
+ * @param key Key to get
249
+ * @return Value associated to the key, or `undefined` if the key is not
250
+ * found.
251
+ */
252
+ get(key) {
253
+ const node = lookup(this._tree, key);
254
+ return node !== void 0 ? node.get(LEAF) : void 0;
255
+ }
256
+ /**
257
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has
258
+ * @param key Key
259
+ * @return True if the key is in the map, false otherwise
260
+ */
261
+ has(key) {
262
+ const node = lookup(this._tree, key);
263
+ return node !== void 0 && node.has(LEAF);
264
+ }
265
+ /**
266
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys
267
+ * @return An `Iterable` iterating through keys
268
+ */
269
+ keys() {
270
+ return new TreeIterator(this, KEYS);
271
+ }
272
+ /**
273
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/set
274
+ * @param key Key to set
275
+ * @param value Value to associate to the key
276
+ * @return The {@link SearchableMap} itself, to allow chaining
277
+ */
278
+ set(key, value) {
279
+ if (typeof key !== "string") throw new Error("key must be a string");
280
+ this._size = void 0;
281
+ createPath(this._tree, key).set(LEAF, value);
282
+ return this;
283
+ }
284
+ /**
285
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/size
286
+ */
287
+ get size() {
288
+ if (this._size) return this._size;
289
+ /** @ignore */
290
+ this._size = 0;
291
+ const iter = this.entries();
292
+ while (!iter.next().done) this._size += 1;
293
+ return this._size;
294
+ }
295
+ /**
296
+ * Updates the value at the given key using the provided function. The function
297
+ * is called with the current value at the key, and its return value is used as
298
+ * the new value to be set.
299
+ *
300
+ * ### Example:
301
+ *
302
+ * ```javascript
303
+ * // Increment the current value by one
304
+ * searchableMap.update('somekey', (currentValue) => currentValue == null ? 0 : currentValue + 1)
305
+ * ```
306
+ *
307
+ * If the value at the given key is or will be an object, it might not require
308
+ * re-assignment. In that case it is better to use `fetch()`, because it is
309
+ * faster.
310
+ *
311
+ * @param key The key to update
312
+ * @param fn The function used to compute the new value from the current one
313
+ * @return The {@link SearchableMap} itself, to allow chaining
314
+ */
315
+ update(key, fn) {
316
+ if (typeof key !== "string") throw new Error("key must be a string");
317
+ this._size = void 0;
318
+ const node = createPath(this._tree, key);
319
+ node.set(LEAF, fn(node.get(LEAF)));
320
+ return this;
321
+ }
322
+ /**
323
+ * Fetches the value of the given key. If the value does not exist, calls the
324
+ * given function to create a new value, which is inserted at the given key
325
+ * and subsequently returned.
326
+ *
327
+ * ### Example:
328
+ *
329
+ * ```javascript
330
+ * const map = searchableMap.fetch('somekey', () => new Map())
331
+ * map.set('foo', 'bar')
332
+ * ```
333
+ *
334
+ * @param key The key to update
335
+ * @param initial A function that creates a new value if the key does not exist
336
+ * @return The existing or new value at the given key
337
+ */
338
+ fetch(key, initial) {
339
+ if (typeof key !== "string") throw new Error("key must be a string");
340
+ this._size = void 0;
341
+ const node = createPath(this._tree, key);
342
+ let value = node.get(LEAF);
343
+ if (value === void 0) node.set(LEAF, value = initial());
344
+ return value;
345
+ }
346
+ /**
347
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/values
348
+ * @return An `Iterable` iterating through values.
349
+ */
350
+ values() {
351
+ return new TreeIterator(this, VALUES);
352
+ }
353
+ /**
354
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator
355
+ */
356
+ [Symbol.iterator]() {
357
+ return this.entries();
358
+ }
359
+ /**
360
+ * Creates a {@link SearchableMap} from an `Iterable` of entries
361
+ *
362
+ * @param entries Entries to be inserted in the {@link SearchableMap}
363
+ * @return A new {@link SearchableMap} with the given entries
364
+ */
365
+ static from(entries) {
366
+ const tree = new SearchableMap();
367
+ for (const [key, value] of entries) tree.set(key, value);
368
+ return tree;
369
+ }
370
+ /**
371
+ * Creates a {@link SearchableMap} from the iterable properties of a JavaScript object
372
+ *
373
+ * @param object Object of entries for the {@link SearchableMap}
374
+ * @return A new {@link SearchableMap} with the given entries
375
+ */
376
+ static fromObject(object) {
377
+ return SearchableMap.from(Object.entries(object));
378
+ }
379
+ };
380
+ var trackDown = (tree, key, path = []) => {
381
+ if (key.length === 0 || tree == null) return [tree, path];
382
+ for (const k of tree.keys()) if (k !== LEAF && key.startsWith(k)) {
383
+ path.push([tree, k]);
384
+ return trackDown(tree.get(k), key.slice(k.length), path);
385
+ }
386
+ path.push([tree, key]);
387
+ return trackDown(void 0, "", path);
388
+ };
389
+ var lookup = (tree, key) => {
390
+ if (key.length === 0 || tree == null) return tree;
391
+ for (const k of tree.keys()) if (k !== LEAF && key.startsWith(k)) return lookup(tree.get(k), key.slice(k.length));
392
+ };
393
+ var createPath = (node, key) => {
394
+ const keyLength = key.length;
395
+ outer: for (let pos = 0; node && pos < keyLength;) {
396
+ for (const k of node.keys()) if (k !== LEAF && key[pos] === k[0]) {
397
+ const len = Math.min(keyLength - pos, k.length);
398
+ let offset = 1;
399
+ while (offset < len && key[pos + offset] === k[offset]) ++offset;
400
+ const child = node.get(k);
401
+ if (offset === k.length) node = child;
402
+ else {
403
+ const intermediate = /* @__PURE__ */ new Map();
404
+ intermediate.set(k.slice(offset), child);
405
+ node.set(key.slice(pos, pos + offset), intermediate);
406
+ node.delete(k);
407
+ node = intermediate;
408
+ }
409
+ pos += offset;
410
+ continue outer;
411
+ }
412
+ const child = /* @__PURE__ */ new Map();
413
+ node.set(key.slice(pos), child);
414
+ return child;
415
+ }
416
+ return node;
417
+ };
418
+ var remove = (tree, key) => {
419
+ const [node, path] = trackDown(tree, key);
420
+ if (node === void 0) return;
421
+ node.delete(LEAF);
422
+ if (node.size === 0) cleanup(path);
423
+ else if (node.size === 1) {
424
+ const [key, value] = node.entries().next().value;
425
+ merge(path, key, value);
426
+ }
427
+ };
428
+ var cleanup = (path) => {
429
+ if (path.length === 0) return;
430
+ const [node, key] = last(path);
431
+ node.delete(key);
432
+ if (node.size === 0) cleanup(path.slice(0, -1));
433
+ else if (node.size === 1) {
434
+ const [key, value] = node.entries().next().value;
435
+ if (key !== LEAF) merge(path.slice(0, -1), key, value);
436
+ }
437
+ };
438
+ var merge = (path, key, value) => {
439
+ if (path.length === 0) return;
440
+ const [node, nodeKey] = last(path);
441
+ node.set(nodeKey + key, value);
442
+ node.delete(nodeKey);
443
+ };
444
+ var last = (array) => {
445
+ return array[array.length - 1];
446
+ };
447
+ var OR = "or";
448
+ var AND = "and";
449
+ var AND_NOT = "and_not";
450
+ /**
451
+ * {@link MiniSearch} is the main entrypoint class, implementing a full-text
452
+ * search engine in memory.
453
+ *
454
+ * @typeParam T The type of the documents being indexed.
455
+ *
456
+ * ### Basic example:
457
+ *
458
+ * ```javascript
459
+ * const documents = [
460
+ * {
461
+ * id: 1,
462
+ * title: 'Moby Dick',
463
+ * text: 'Call me Ishmael. Some years ago...',
464
+ * category: 'fiction'
465
+ * },
466
+ * {
467
+ * id: 2,
468
+ * title: 'Zen and the Art of Motorcycle Maintenance',
469
+ * text: 'I can see by my watch...',
470
+ * category: 'fiction'
471
+ * },
472
+ * {
473
+ * id: 3,
474
+ * title: 'Neuromancer',
475
+ * text: 'The sky above the port was...',
476
+ * category: 'fiction'
477
+ * },
478
+ * {
479
+ * id: 4,
480
+ * title: 'Zen and the Art of Archery',
481
+ * text: 'At first sight it must seem...',
482
+ * category: 'non-fiction'
483
+ * },
484
+ * // ...and more
485
+ * ]
486
+ *
487
+ * // Create a search engine that indexes the 'title' and 'text' fields for
488
+ * // full-text search. Search results will include 'title' and 'category' (plus the
489
+ * // id field, that is always stored and returned)
490
+ * const miniSearch = new MiniSearch({
491
+ * fields: ['title', 'text'],
492
+ * storeFields: ['title', 'category']
493
+ * })
494
+ *
495
+ * // Add documents to the index
496
+ * miniSearch.addAll(documents)
497
+ *
498
+ * // Search for documents:
499
+ * let results = miniSearch.search('zen art motorcycle')
500
+ * // => [
501
+ * // { id: 2, title: 'Zen and the Art of Motorcycle Maintenance', category: 'fiction', score: 2.77258 },
502
+ * // { id: 4, title: 'Zen and the Art of Archery', category: 'non-fiction', score: 1.38629 }
503
+ * // ]
504
+ * ```
505
+ */
506
+ var MiniSearch = class MiniSearch {
507
+ /**
508
+ * @param options Configuration options
509
+ *
510
+ * ### Examples:
511
+ *
512
+ * ```javascript
513
+ * // Create a search engine that indexes the 'title' and 'text' fields of your
514
+ * // documents:
515
+ * const miniSearch = new MiniSearch({ fields: ['title', 'text'] })
516
+ * ```
517
+ *
518
+ * ### ID Field:
519
+ *
520
+ * ```javascript
521
+ * // Your documents are assumed to include a unique 'id' field, but if you want
522
+ * // to use a different field for document identification, you can set the
523
+ * // 'idField' option:
524
+ * const miniSearch = new MiniSearch({ idField: 'key', fields: ['title', 'text'] })
525
+ * ```
526
+ *
527
+ * ### Options and defaults:
528
+ *
529
+ * ```javascript
530
+ * // The full set of options (here with their default value) is:
531
+ * const miniSearch = new MiniSearch({
532
+ * // idField: field that uniquely identifies a document
533
+ * idField: 'id',
534
+ *
535
+ * // extractField: function used to get the value of a field in a document.
536
+ * // By default, it assumes the document is a flat object with field names as
537
+ * // property keys and field values as string property values, but custom logic
538
+ * // can be implemented by setting this option to a custom extractor function.
539
+ * extractField: (document, fieldName) => document[fieldName],
540
+ *
541
+ * // tokenize: function used to split fields into individual terms. By
542
+ * // default, it is also used to tokenize search queries, unless a specific
543
+ * // `tokenize` search option is supplied. When tokenizing an indexed field,
544
+ * // the field name is passed as the second argument.
545
+ * tokenize: (string, _fieldName) => string.split(SPACE_OR_PUNCTUATION),
546
+ *
547
+ * // processTerm: function used to process each tokenized term before
548
+ * // indexing. It can be used for stemming and normalization. Return a falsy
549
+ * // value in order to discard a term. By default, it is also used to process
550
+ * // search queries, unless a specific `processTerm` option is supplied as a
551
+ * // search option. When processing a term from a indexed field, the field
552
+ * // name is passed as the second argument.
553
+ * processTerm: (term, _fieldName) => term.toLowerCase(),
554
+ *
555
+ * // searchOptions: default search options, see the `search` method for
556
+ * // details
557
+ * searchOptions: undefined,
558
+ *
559
+ * // fields: document fields to be indexed. Mandatory, but not set by default
560
+ * fields: undefined
561
+ *
562
+ * // storeFields: document fields to be stored and returned as part of the
563
+ * // search results.
564
+ * storeFields: []
565
+ * })
566
+ * ```
567
+ */
568
+ constructor(options) {
569
+ if ((options === null || options === void 0 ? void 0 : options.fields) == null) throw new Error("MiniSearch: option \"fields\" must be provided");
570
+ const autoVacuum = options.autoVacuum == null || options.autoVacuum === true ? defaultAutoVacuumOptions : options.autoVacuum;
571
+ this._options = {
572
+ ...defaultOptions,
573
+ ...options,
574
+ autoVacuum,
575
+ searchOptions: {
576
+ ...defaultSearchOptions,
577
+ ...options.searchOptions || {}
578
+ },
579
+ autoSuggestOptions: {
580
+ ...defaultAutoSuggestOptions,
581
+ ...options.autoSuggestOptions || {}
582
+ }
583
+ };
584
+ this._index = new SearchableMap();
585
+ this._documentCount = 0;
586
+ this._documentIds = /* @__PURE__ */ new Map();
587
+ this._idToShortId = /* @__PURE__ */ new Map();
588
+ this._fieldIds = {};
589
+ this._fieldLength = /* @__PURE__ */ new Map();
590
+ this._avgFieldLength = [];
591
+ this._nextId = 0;
592
+ this._storedFields = /* @__PURE__ */ new Map();
593
+ this._dirtCount = 0;
594
+ this._currentVacuum = null;
595
+ this._enqueuedVacuum = null;
596
+ this._enqueuedVacuumConditions = defaultVacuumConditions;
597
+ this.addFields(this._options.fields);
598
+ }
599
+ /**
600
+ * Adds a document to the index
601
+ *
602
+ * @param document The document to be indexed
603
+ */
604
+ add(document) {
605
+ const { extractField, stringifyField, tokenize, processTerm, fields, idField } = this._options;
606
+ const id = extractField(document, idField);
607
+ if (id == null) throw new Error(`MiniSearch: document does not have ID field "${idField}"`);
608
+ if (this._idToShortId.has(id)) throw new Error(`MiniSearch: duplicate ID ${id}`);
609
+ const shortDocumentId = this.addDocumentId(id);
610
+ this.saveStoredFields(shortDocumentId, document);
611
+ for (const field of fields) {
612
+ const fieldValue = extractField(document, field);
613
+ if (fieldValue == null) continue;
614
+ const tokens = tokenize(stringifyField(fieldValue, field), field);
615
+ const fieldId = this._fieldIds[field];
616
+ const uniqueTerms = new Set(tokens).size;
617
+ this.addFieldLength(shortDocumentId, fieldId, this._documentCount - 1, uniqueTerms);
618
+ for (const term of tokens) {
619
+ const processedTerm = processTerm(term, field);
620
+ if (Array.isArray(processedTerm)) for (const t of processedTerm) this.addTerm(fieldId, shortDocumentId, t);
621
+ else if (processedTerm) this.addTerm(fieldId, shortDocumentId, processedTerm);
622
+ }
623
+ }
624
+ }
625
+ /**
626
+ * Adds all the given documents to the index
627
+ *
628
+ * @param documents An array of documents to be indexed
629
+ */
630
+ addAll(documents) {
631
+ for (const document of documents) this.add(document);
632
+ }
633
+ /**
634
+ * Adds all the given documents to the index asynchronously.
635
+ *
636
+ * Returns a promise that resolves (to `undefined`) when the indexing is done.
637
+ * This method is useful when index many documents, to avoid blocking the main
638
+ * thread. The indexing is performed asynchronously and in chunks.
639
+ *
640
+ * @param documents An array of documents to be indexed
641
+ * @param options Configuration options
642
+ * @return A promise resolving to `undefined` when the indexing is done
643
+ */
644
+ addAllAsync(documents, options = {}) {
645
+ const { chunkSize = 10 } = options;
646
+ const acc = {
647
+ chunk: [],
648
+ promise: Promise.resolve()
649
+ };
650
+ const { chunk, promise } = documents.reduce(({ chunk, promise }, document, i) => {
651
+ chunk.push(document);
652
+ if ((i + 1) % chunkSize === 0) return {
653
+ chunk: [],
654
+ promise: promise.then(() => new Promise((resolve) => setTimeout(resolve, 0))).then(() => this.addAll(chunk))
655
+ };
656
+ else return {
657
+ chunk,
658
+ promise
659
+ };
660
+ }, acc);
661
+ return promise.then(() => this.addAll(chunk));
662
+ }
663
+ /**
664
+ * Removes the given document from the index.
665
+ *
666
+ * The document to remove must NOT have changed between indexing and removal,
667
+ * otherwise the index will be corrupted.
668
+ *
669
+ * This method requires passing the full document to be removed (not just the
670
+ * ID), and immediately removes the document from the inverted index, allowing
671
+ * memory to be released. A convenient alternative is {@link
672
+ * MiniSearch#discard}, which needs only the document ID, and has the same
673
+ * visible effect, but delays cleaning up the index until the next vacuuming.
674
+ *
675
+ * @param document The document to be removed
676
+ */
677
+ remove(document) {
678
+ const { tokenize, processTerm, extractField, stringifyField, fields, idField } = this._options;
679
+ const id = extractField(document, idField);
680
+ if (id == null) throw new Error(`MiniSearch: document does not have ID field "${idField}"`);
681
+ const shortId = this._idToShortId.get(id);
682
+ if (shortId == null) throw new Error(`MiniSearch: cannot remove document with ID ${id}: it is not in the index`);
683
+ for (const field of fields) {
684
+ const fieldValue = extractField(document, field);
685
+ if (fieldValue == null) continue;
686
+ const tokens = tokenize(stringifyField(fieldValue, field), field);
687
+ const fieldId = this._fieldIds[field];
688
+ const uniqueTerms = new Set(tokens).size;
689
+ this.removeFieldLength(shortId, fieldId, this._documentCount, uniqueTerms);
690
+ for (const term of tokens) {
691
+ const processedTerm = processTerm(term, field);
692
+ if (Array.isArray(processedTerm)) for (const t of processedTerm) this.removeTerm(fieldId, shortId, t);
693
+ else if (processedTerm) this.removeTerm(fieldId, shortId, processedTerm);
694
+ }
695
+ }
696
+ this._storedFields.delete(shortId);
697
+ this._documentIds.delete(shortId);
698
+ this._idToShortId.delete(id);
699
+ this._fieldLength.delete(shortId);
700
+ this._documentCount -= 1;
701
+ }
702
+ /**
703
+ * Removes all the given documents from the index. If called with no arguments,
704
+ * it removes _all_ documents from the index.
705
+ *
706
+ * @param documents The documents to be removed. If this argument is omitted,
707
+ * all documents are removed. Note that, for removing all documents, it is
708
+ * more efficient to call this method with no arguments than to pass all
709
+ * documents.
710
+ */
711
+ removeAll(documents) {
712
+ if (documents) for (const document of documents) this.remove(document);
713
+ else if (arguments.length > 0) throw new Error("Expected documents to be present. Omit the argument to remove all documents.");
714
+ else {
715
+ this._index = new SearchableMap();
716
+ this._documentCount = 0;
717
+ this._documentIds = /* @__PURE__ */ new Map();
718
+ this._idToShortId = /* @__PURE__ */ new Map();
719
+ this._fieldLength = /* @__PURE__ */ new Map();
720
+ this._avgFieldLength = [];
721
+ this._storedFields = /* @__PURE__ */ new Map();
722
+ this._nextId = 0;
723
+ }
724
+ }
725
+ /**
726
+ * Discards the document with the given ID, so it won't appear in search results
727
+ *
728
+ * It has the same visible effect of {@link MiniSearch.remove} (both cause the
729
+ * document to stop appearing in searches), but a different effect on the
730
+ * internal data structures:
731
+ *
732
+ * - {@link MiniSearch#remove} requires passing the full document to be
733
+ * removed as argument, and removes it from the inverted index immediately.
734
+ *
735
+ * - {@link MiniSearch#discard} instead only needs the document ID, and
736
+ * works by marking the current version of the document as discarded, so it
737
+ * is immediately ignored by searches. This is faster and more convenient
738
+ * than {@link MiniSearch#remove}, but the index is not immediately
739
+ * modified. To take care of that, vacuuming is performed after a certain
740
+ * number of documents are discarded, cleaning up the index and allowing
741
+ * memory to be released.
742
+ *
743
+ * After discarding a document, it is possible to re-add a new version, and
744
+ * only the new version will appear in searches. In other words, discarding
745
+ * and re-adding a document works exactly like removing and re-adding it. The
746
+ * {@link MiniSearch.replace} method can also be used to replace a document
747
+ * with a new version.
748
+ *
749
+ * #### Details about vacuuming
750
+ *
751
+ * Repetite calls to this method would leave obsolete document references in
752
+ * the index, invisible to searches. Two mechanisms take care of cleaning up:
753
+ * clean up during search, and vacuuming.
754
+ *
755
+ * - Upon search, whenever a discarded ID is found (and ignored for the
756
+ * results), references to the discarded document are removed from the
757
+ * inverted index entries for the search terms. This ensures that subsequent
758
+ * searches for the same terms do not need to skip these obsolete references
759
+ * again.
760
+ *
761
+ * - In addition, vacuuming is performed automatically by default (see the
762
+ * `autoVacuum` field in {@link Options}) after a certain number of
763
+ * documents are discarded. Vacuuming traverses all terms in the index,
764
+ * cleaning up all references to discarded documents. Vacuuming can also be
765
+ * triggered manually by calling {@link MiniSearch#vacuum}.
766
+ *
767
+ * @param id The ID of the document to be discarded
768
+ */
769
+ discard(id) {
770
+ const shortId = this._idToShortId.get(id);
771
+ if (shortId == null) throw new Error(`MiniSearch: cannot discard document with ID ${id}: it is not in the index`);
772
+ this._idToShortId.delete(id);
773
+ this._documentIds.delete(shortId);
774
+ this._storedFields.delete(shortId);
775
+ (this._fieldLength.get(shortId) || []).forEach((fieldLength, fieldId) => {
776
+ this.removeFieldLength(shortId, fieldId, this._documentCount, fieldLength);
777
+ });
778
+ this._fieldLength.delete(shortId);
779
+ this._documentCount -= 1;
780
+ this._dirtCount += 1;
781
+ this.maybeAutoVacuum();
782
+ }
783
+ maybeAutoVacuum() {
784
+ if (this._options.autoVacuum === false) return;
785
+ const { minDirtFactor, minDirtCount, batchSize, batchWait } = this._options.autoVacuum;
786
+ this.conditionalVacuum({
787
+ batchSize,
788
+ batchWait
789
+ }, {
790
+ minDirtCount,
791
+ minDirtFactor
792
+ });
793
+ }
794
+ /**
795
+ * Discards the documents with the given IDs, so they won't appear in search
796
+ * results
797
+ *
798
+ * It is equivalent to calling {@link MiniSearch#discard} for all the given
799
+ * IDs, but with the optimization of triggering at most one automatic
800
+ * vacuuming at the end.
801
+ *
802
+ * Note: to remove all documents from the index, it is faster and more
803
+ * convenient to call {@link MiniSearch.removeAll} with no argument, instead
804
+ * of passing all IDs to this method.
805
+ */
806
+ discardAll(ids) {
807
+ const autoVacuum = this._options.autoVacuum;
808
+ try {
809
+ this._options.autoVacuum = false;
810
+ for (const id of ids) this.discard(id);
811
+ } finally {
812
+ this._options.autoVacuum = autoVacuum;
813
+ }
814
+ this.maybeAutoVacuum();
815
+ }
816
+ /**
817
+ * It replaces an existing document with the given updated version
818
+ *
819
+ * It works by discarding the current version and adding the updated one, so
820
+ * it is functionally equivalent to calling {@link MiniSearch#discard}
821
+ * followed by {@link MiniSearch#add}. The ID of the updated document should
822
+ * be the same as the original one.
823
+ *
824
+ * Since it uses {@link MiniSearch#discard} internally, this method relies on
825
+ * vacuuming to clean up obsolete document references from the index, allowing
826
+ * memory to be released (see {@link MiniSearch#discard}).
827
+ *
828
+ * @param updatedDocument The updated document to replace the old version
829
+ * with
830
+ */
831
+ replace(updatedDocument) {
832
+ const { idField, extractField } = this._options;
833
+ const id = extractField(updatedDocument, idField);
834
+ this.discard(id);
835
+ this.add(updatedDocument);
836
+ }
837
+ /**
838
+ * Triggers a manual vacuuming, cleaning up references to discarded documents
839
+ * from the inverted index
840
+ *
841
+ * Vacuuming is only useful for applications that use the {@link
842
+ * MiniSearch#discard} or {@link MiniSearch#replace} methods.
843
+ *
844
+ * By default, vacuuming is performed automatically when needed (controlled by
845
+ * the `autoVacuum` field in {@link Options}), so there is usually no need to
846
+ * call this method, unless one wants to make sure to perform vacuuming at a
847
+ * specific moment.
848
+ *
849
+ * Vacuuming traverses all terms in the inverted index in batches, and cleans
850
+ * up references to discarded documents from the posting list, allowing memory
851
+ * to be released.
852
+ *
853
+ * The method takes an optional object as argument with the following keys:
854
+ *
855
+ * - `batchSize`: the size of each batch (1000 by default)
856
+ *
857
+ * - `batchWait`: the number of milliseconds to wait between batches (10 by
858
+ * default)
859
+ *
860
+ * On large indexes, vacuuming could have a non-negligible cost: batching
861
+ * avoids blocking the thread for long, diluting this cost so that it is not
862
+ * negatively affecting the application. Nonetheless, this method should only
863
+ * be called when necessary, and relying on automatic vacuuming is usually
864
+ * better.
865
+ *
866
+ * It returns a promise that resolves (to undefined) when the clean up is
867
+ * completed. If vacuuming is already ongoing at the time this method is
868
+ * called, a new one is enqueued immediately after the ongoing one, and a
869
+ * corresponding promise is returned. However, no more than one vacuuming is
870
+ * enqueued on top of the ongoing one, even if this method is called more
871
+ * times (enqueuing multiple ones would be useless).
872
+ *
873
+ * @param options Configuration options for the batch size and delay. See
874
+ * {@link VacuumOptions}.
875
+ */
876
+ vacuum(options = {}) {
877
+ return this.conditionalVacuum(options);
878
+ }
879
+ conditionalVacuum(options, conditions) {
880
+ if (this._currentVacuum) {
881
+ this._enqueuedVacuumConditions = this._enqueuedVacuumConditions && conditions;
882
+ if (this._enqueuedVacuum != null) return this._enqueuedVacuum;
883
+ this._enqueuedVacuum = this._currentVacuum.then(() => {
884
+ const conditions = this._enqueuedVacuumConditions;
885
+ this._enqueuedVacuumConditions = defaultVacuumConditions;
886
+ return this.performVacuuming(options, conditions);
887
+ });
888
+ return this._enqueuedVacuum;
889
+ }
890
+ if (this.vacuumConditionsMet(conditions) === false) return Promise.resolve();
891
+ this._currentVacuum = this.performVacuuming(options);
892
+ return this._currentVacuum;
893
+ }
894
+ async performVacuuming(options, conditions) {
895
+ const initialDirtCount = this._dirtCount;
896
+ if (this.vacuumConditionsMet(conditions)) {
897
+ const batchSize = options.batchSize || defaultVacuumOptions.batchSize;
898
+ const batchWait = options.batchWait || defaultVacuumOptions.batchWait;
899
+ let i = 1;
900
+ for (const [term, fieldsData] of this._index) {
901
+ for (const [fieldId, fieldIndex] of fieldsData) for (const [shortId] of fieldIndex) {
902
+ if (this._documentIds.has(shortId)) continue;
903
+ if (fieldIndex.size <= 1) fieldsData.delete(fieldId);
904
+ else fieldIndex.delete(shortId);
905
+ }
906
+ if (this._index.get(term).size === 0) this._index.delete(term);
907
+ if (i % batchSize === 0) await new Promise((resolve) => setTimeout(resolve, batchWait));
908
+ i += 1;
909
+ }
910
+ this._dirtCount -= initialDirtCount;
911
+ }
912
+ await null;
913
+ this._currentVacuum = this._enqueuedVacuum;
914
+ this._enqueuedVacuum = null;
915
+ }
916
+ vacuumConditionsMet(conditions) {
917
+ if (conditions == null) return true;
918
+ let { minDirtCount, minDirtFactor } = conditions;
919
+ minDirtCount = minDirtCount || defaultAutoVacuumOptions.minDirtCount;
920
+ minDirtFactor = minDirtFactor || defaultAutoVacuumOptions.minDirtFactor;
921
+ return this.dirtCount >= minDirtCount && this.dirtFactor >= minDirtFactor;
922
+ }
923
+ /**
924
+ * Is `true` if a vacuuming operation is ongoing, `false` otherwise
925
+ */
926
+ get isVacuuming() {
927
+ return this._currentVacuum != null;
928
+ }
929
+ /**
930
+ * The number of documents discarded since the most recent vacuuming
931
+ */
932
+ get dirtCount() {
933
+ return this._dirtCount;
934
+ }
935
+ /**
936
+ * A number between 0 and 1 giving an indication about the proportion of
937
+ * documents that are discarded, and can therefore be cleaned up by vacuuming.
938
+ * A value close to 0 means that the index is relatively clean, while a higher
939
+ * value means that the index is relatively dirty, and vacuuming could release
940
+ * memory.
941
+ */
942
+ get dirtFactor() {
943
+ return this._dirtCount / (1 + this._documentCount + this._dirtCount);
944
+ }
945
+ /**
946
+ * Returns `true` if a document with the given ID is present in the index and
947
+ * available for search, `false` otherwise
948
+ *
949
+ * @param id The document ID
950
+ */
951
+ has(id) {
952
+ return this._idToShortId.has(id);
953
+ }
954
+ /**
955
+ * Returns the stored fields (as configured in the `storeFields` constructor
956
+ * option) for the given document ID. Returns `undefined` if the document is
957
+ * not present in the index.
958
+ *
959
+ * @param id The document ID
960
+ */
961
+ getStoredFields(id) {
962
+ const shortId = this._idToShortId.get(id);
963
+ if (shortId == null) return;
964
+ return this._storedFields.get(shortId);
965
+ }
966
+ /**
967
+ * Search for documents matching the given search query.
968
+ *
969
+ * The result is a list of scored document IDs matching the query, sorted by
970
+ * descending score, and each including data about which terms were matched and
971
+ * in which fields.
972
+ *
973
+ * ### Basic usage:
974
+ *
975
+ * ```javascript
976
+ * // Search for "zen art motorcycle" with default options: terms have to match
977
+ * // exactly, and individual terms are joined with OR
978
+ * miniSearch.search('zen art motorcycle')
979
+ * // => [ { id: 2, score: 2.77258, match: { ... } }, { id: 4, score: 1.38629, match: { ... } } ]
980
+ * ```
981
+ *
982
+ * ### Restrict search to specific fields:
983
+ *
984
+ * ```javascript
985
+ * // Search only in the 'title' field
986
+ * miniSearch.search('zen', { fields: ['title'] })
987
+ * ```
988
+ *
989
+ * ### Field boosting:
990
+ *
991
+ * ```javascript
992
+ * // Boost a field
993
+ * miniSearch.search('zen', { boost: { title: 2 } })
994
+ * ```
995
+ *
996
+ * ### Prefix search:
997
+ *
998
+ * ```javascript
999
+ * // Search for "moto" with prefix search (it will match documents
1000
+ * // containing terms that start with "moto" or "neuro")
1001
+ * miniSearch.search('moto neuro', { prefix: true })
1002
+ * ```
1003
+ *
1004
+ * ### Fuzzy search:
1005
+ *
1006
+ * ```javascript
1007
+ * // Search for "ismael" with fuzzy search (it will match documents containing
1008
+ * // terms similar to "ismael", with a maximum edit distance of 0.2 term.length
1009
+ * // (rounded to nearest integer)
1010
+ * miniSearch.search('ismael', { fuzzy: 0.2 })
1011
+ * ```
1012
+ *
1013
+ * ### Combining strategies:
1014
+ *
1015
+ * ```javascript
1016
+ * // Mix of exact match, prefix search, and fuzzy search
1017
+ * miniSearch.search('ismael mob', {
1018
+ * prefix: true,
1019
+ * fuzzy: 0.2
1020
+ * })
1021
+ * ```
1022
+ *
1023
+ * ### Advanced prefix and fuzzy search:
1024
+ *
1025
+ * ```javascript
1026
+ * // Perform fuzzy and prefix search depending on the search term. Here
1027
+ * // performing prefix and fuzzy search only on terms longer than 3 characters
1028
+ * miniSearch.search('ismael mob', {
1029
+ * prefix: term => term.length > 3
1030
+ * fuzzy: term => term.length > 3 ? 0.2 : null
1031
+ * })
1032
+ * ```
1033
+ *
1034
+ * ### Combine with AND:
1035
+ *
1036
+ * ```javascript
1037
+ * // Combine search terms with AND (to match only documents that contain both
1038
+ * // "motorcycle" and "art")
1039
+ * miniSearch.search('motorcycle art', { combineWith: 'AND' })
1040
+ * ```
1041
+ *
1042
+ * ### Combine with AND_NOT:
1043
+ *
1044
+ * There is also an AND_NOT combinator, that finds documents that match the
1045
+ * first term, but do not match any of the other terms. This combinator is
1046
+ * rarely useful with simple queries, and is meant to be used with advanced
1047
+ * query combinations (see later for more details).
1048
+ *
1049
+ * ### Filtering results:
1050
+ *
1051
+ * ```javascript
1052
+ * // Filter only results in the 'fiction' category (assuming that 'category'
1053
+ * // is a stored field)
1054
+ * miniSearch.search('motorcycle art', {
1055
+ * filter: (result) => result.category === 'fiction'
1056
+ * })
1057
+ * ```
1058
+ *
1059
+ * ### Wildcard query
1060
+ *
1061
+ * Searching for an empty string (assuming the default tokenizer) returns no
1062
+ * results. Sometimes though, one needs to match all documents, like in a
1063
+ * "wildcard" search. This is possible by passing the special value
1064
+ * {@link MiniSearch.wildcard} as the query:
1065
+ *
1066
+ * ```javascript
1067
+ * // Return search results for all documents
1068
+ * miniSearch.search(MiniSearch.wildcard)
1069
+ * ```
1070
+ *
1071
+ * Note that search options such as `filter` and `boostDocument` are still
1072
+ * applied, influencing which results are returned, and their order:
1073
+ *
1074
+ * ```javascript
1075
+ * // Return search results for all documents in the 'fiction' category
1076
+ * miniSearch.search(MiniSearch.wildcard, {
1077
+ * filter: (result) => result.category === 'fiction'
1078
+ * })
1079
+ * ```
1080
+ *
1081
+ * ### Advanced combination of queries:
1082
+ *
1083
+ * It is possible to combine different subqueries with OR, AND, and AND_NOT,
1084
+ * and even with different search options, by passing a query expression
1085
+ * tree object as the first argument, instead of a string.
1086
+ *
1087
+ * ```javascript
1088
+ * // Search for documents that contain "zen" and ("motorcycle" or "archery")
1089
+ * miniSearch.search({
1090
+ * combineWith: 'AND',
1091
+ * queries: [
1092
+ * 'zen',
1093
+ * {
1094
+ * combineWith: 'OR',
1095
+ * queries: ['motorcycle', 'archery']
1096
+ * }
1097
+ * ]
1098
+ * })
1099
+ *
1100
+ * // Search for documents that contain ("apple" or "pear") but not "juice" and
1101
+ * // not "tree"
1102
+ * miniSearch.search({
1103
+ * combineWith: 'AND_NOT',
1104
+ * queries: [
1105
+ * {
1106
+ * combineWith: 'OR',
1107
+ * queries: ['apple', 'pear']
1108
+ * },
1109
+ * 'juice',
1110
+ * 'tree'
1111
+ * ]
1112
+ * })
1113
+ * ```
1114
+ *
1115
+ * Each node in the expression tree can be either a string, or an object that
1116
+ * supports all {@link SearchOptions} fields, plus a `queries` array field for
1117
+ * subqueries.
1118
+ *
1119
+ * Note that, while this can become complicated to do by hand for complex or
1120
+ * deeply nested queries, it provides a formalized expression tree API for
1121
+ * external libraries that implement a parser for custom query languages.
1122
+ *
1123
+ * @param query Search query
1124
+ * @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.
1125
+ */
1126
+ search(query, searchOptions = {}) {
1127
+ const { searchOptions: globalSearchOptions } = this._options;
1128
+ const searchOptionsWithDefaults = {
1129
+ ...globalSearchOptions,
1130
+ ...searchOptions
1131
+ };
1132
+ const rawResults = this.executeQuery(query, searchOptions);
1133
+ const results = [];
1134
+ for (const [docId, { score, terms, match }] of rawResults) {
1135
+ const quality = terms.length || 1;
1136
+ const result = {
1137
+ id: this._documentIds.get(docId),
1138
+ score: score * quality,
1139
+ terms: Object.keys(match),
1140
+ queryTerms: terms,
1141
+ match
1142
+ };
1143
+ Object.assign(result, this._storedFields.get(docId));
1144
+ if (searchOptionsWithDefaults.filter == null || searchOptionsWithDefaults.filter(result)) results.push(result);
1145
+ }
1146
+ if (query === MiniSearch.wildcard && searchOptionsWithDefaults.boostDocument == null) return results;
1147
+ results.sort(byScore);
1148
+ return results;
1149
+ }
1150
+ /**
1151
+ * Provide suggestions for the given search query
1152
+ *
1153
+ * The result is a list of suggested modified search queries, derived from the
1154
+ * given search query, each with a relevance score, sorted by descending score.
1155
+ *
1156
+ * By default, it uses the same options used for search, except that by
1157
+ * default it performs prefix search on the last term of the query, and
1158
+ * combine terms with `'AND'` (requiring all query terms to match). Custom
1159
+ * options can be passed as a second argument. Defaults can be changed upon
1160
+ * calling the {@link MiniSearch} constructor, by passing a
1161
+ * `autoSuggestOptions` option.
1162
+ *
1163
+ * ### Basic usage:
1164
+ *
1165
+ * ```javascript
1166
+ * // Get suggestions for 'neuro':
1167
+ * miniSearch.autoSuggest('neuro')
1168
+ * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 0.46240 } ]
1169
+ * ```
1170
+ *
1171
+ * ### Multiple words:
1172
+ *
1173
+ * ```javascript
1174
+ * // Get suggestions for 'zen ar':
1175
+ * miniSearch.autoSuggest('zen ar')
1176
+ * // => [
1177
+ * // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 },
1178
+ * // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 }
1179
+ * // ]
1180
+ * ```
1181
+ *
1182
+ * ### Fuzzy suggestions:
1183
+ *
1184
+ * ```javascript
1185
+ * // Correct spelling mistakes using fuzzy search:
1186
+ * miniSearch.autoSuggest('neromancer', { fuzzy: 0.2 })
1187
+ * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 1.03998 } ]
1188
+ * ```
1189
+ *
1190
+ * ### Filtering:
1191
+ *
1192
+ * ```javascript
1193
+ * // Get suggestions for 'zen ar', but only within the 'fiction' category
1194
+ * // (assuming that 'category' is a stored field):
1195
+ * miniSearch.autoSuggest('zen ar', {
1196
+ * filter: (result) => result.category === 'fiction'
1197
+ * })
1198
+ * // => [
1199
+ * // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 },
1200
+ * // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 }
1201
+ * // ]
1202
+ * ```
1203
+ *
1204
+ * @param queryString Query string to be expanded into suggestions
1205
+ * @param options Search options. The supported options and default values
1206
+ * are the same as for the {@link MiniSearch#search} method, except that by
1207
+ * default prefix search is performed on the last term in the query, and terms
1208
+ * are combined with `'AND'`.
1209
+ * @return A sorted array of suggestions sorted by relevance score.
1210
+ */
1211
+ autoSuggest(queryString, options = {}) {
1212
+ options = {
1213
+ ...this._options.autoSuggestOptions,
1214
+ ...options
1215
+ };
1216
+ const suggestions = /* @__PURE__ */ new Map();
1217
+ for (const { score, terms } of this.search(queryString, options)) {
1218
+ const phrase = terms.join(" ");
1219
+ const suggestion = suggestions.get(phrase);
1220
+ if (suggestion != null) {
1221
+ suggestion.score += score;
1222
+ suggestion.count += 1;
1223
+ } else suggestions.set(phrase, {
1224
+ score,
1225
+ terms,
1226
+ count: 1
1227
+ });
1228
+ }
1229
+ const results = [];
1230
+ for (const [suggestion, { score, terms, count }] of suggestions) results.push({
1231
+ suggestion,
1232
+ terms,
1233
+ score: score / count
1234
+ });
1235
+ results.sort(byScore);
1236
+ return results;
1237
+ }
1238
+ /**
1239
+ * Total number of documents available to search
1240
+ */
1241
+ get documentCount() {
1242
+ return this._documentCount;
1243
+ }
1244
+ /**
1245
+ * Number of terms in the index
1246
+ */
1247
+ get termCount() {
1248
+ return this._index.size;
1249
+ }
1250
+ /**
1251
+ * Deserializes a JSON index (serialized with `JSON.stringify(miniSearch)`)
1252
+ * and instantiates a MiniSearch instance. It should be given the same options
1253
+ * originally used when serializing the index.
1254
+ *
1255
+ * ### Usage:
1256
+ *
1257
+ * ```javascript
1258
+ * // If the index was serialized with:
1259
+ * let miniSearch = new MiniSearch({ fields: ['title', 'text'] })
1260
+ * miniSearch.addAll(documents)
1261
+ *
1262
+ * const json = JSON.stringify(miniSearch)
1263
+ * // It can later be deserialized like this:
1264
+ * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] })
1265
+ * ```
1266
+ *
1267
+ * @param json JSON-serialized index
1268
+ * @param options configuration options, same as the constructor
1269
+ * @return An instance of MiniSearch deserialized from the given JSON.
1270
+ */
1271
+ static loadJSON(json, options) {
1272
+ if (options == null) throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");
1273
+ return this.loadJS(JSON.parse(json), options);
1274
+ }
1275
+ /**
1276
+ * Async equivalent of {@link MiniSearch.loadJSON}
1277
+ *
1278
+ * This function is an alternative to {@link MiniSearch.loadJSON} that returns
1279
+ * a promise, and loads the index in batches, leaving pauses between them to avoid
1280
+ * blocking the main thread. It tends to be slower than the synchronous
1281
+ * version, but does not block the main thread, so it can be a better choice
1282
+ * when deserializing very large indexes.
1283
+ *
1284
+ * @param json JSON-serialized index
1285
+ * @param options configuration options, same as the constructor
1286
+ * @return A Promise that will resolve to an instance of MiniSearch deserialized from the given JSON.
1287
+ */
1288
+ static async loadJSONAsync(json, options) {
1289
+ if (options == null) throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");
1290
+ return this.loadJSAsync(JSON.parse(json), options);
1291
+ }
1292
+ /**
1293
+ * Returns the default value of an option. It will throw an error if no option
1294
+ * with the given name exists.
1295
+ *
1296
+ * @param optionName Name of the option
1297
+ * @return The default value of the given option
1298
+ *
1299
+ * ### Usage:
1300
+ *
1301
+ * ```javascript
1302
+ * // Get default tokenizer
1303
+ * MiniSearch.getDefault('tokenize')
1304
+ *
1305
+ * // Get default term processor
1306
+ * MiniSearch.getDefault('processTerm')
1307
+ *
1308
+ * // Unknown options will throw an error
1309
+ * MiniSearch.getDefault('notExisting')
1310
+ * // => throws 'MiniSearch: unknown option "notExisting"'
1311
+ * ```
1312
+ */
1313
+ static getDefault(optionName) {
1314
+ if (defaultOptions.hasOwnProperty(optionName)) return getOwnProperty(defaultOptions, optionName);
1315
+ else throw new Error(`MiniSearch: unknown option "${optionName}"`);
1316
+ }
1317
+ /**
1318
+ * @ignore
1319
+ */
1320
+ static loadJS(js, options) {
1321
+ const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
1322
+ const miniSearch = this.instantiateMiniSearch(js, options);
1323
+ miniSearch._documentIds = objectToNumericMap(documentIds);
1324
+ miniSearch._fieldLength = objectToNumericMap(fieldLength);
1325
+ miniSearch._storedFields = objectToNumericMap(storedFields);
1326
+ for (const [shortId, id] of miniSearch._documentIds) miniSearch._idToShortId.set(id, shortId);
1327
+ for (const [term, data] of index) {
1328
+ const dataMap = /* @__PURE__ */ new Map();
1329
+ for (const fieldId of Object.keys(data)) {
1330
+ let indexEntry = data[fieldId];
1331
+ if (serializationVersion === 1) indexEntry = indexEntry.ds;
1332
+ dataMap.set(parseInt(fieldId, 10), objectToNumericMap(indexEntry));
1333
+ }
1334
+ miniSearch._index.set(term, dataMap);
1335
+ }
1336
+ return miniSearch;
1337
+ }
1338
+ /**
1339
+ * @ignore
1340
+ */
1341
+ static async loadJSAsync(js, options) {
1342
+ const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
1343
+ const miniSearch = this.instantiateMiniSearch(js, options);
1344
+ miniSearch._documentIds = await objectToNumericMapAsync(documentIds);
1345
+ miniSearch._fieldLength = await objectToNumericMapAsync(fieldLength);
1346
+ miniSearch._storedFields = await objectToNumericMapAsync(storedFields);
1347
+ for (const [shortId, id] of miniSearch._documentIds) miniSearch._idToShortId.set(id, shortId);
1348
+ let count = 0;
1349
+ for (const [term, data] of index) {
1350
+ const dataMap = /* @__PURE__ */ new Map();
1351
+ for (const fieldId of Object.keys(data)) {
1352
+ let indexEntry = data[fieldId];
1353
+ if (serializationVersion === 1) indexEntry = indexEntry.ds;
1354
+ dataMap.set(parseInt(fieldId, 10), await objectToNumericMapAsync(indexEntry));
1355
+ }
1356
+ if (++count % 1e3 === 0) await wait(0);
1357
+ miniSearch._index.set(term, dataMap);
1358
+ }
1359
+ return miniSearch;
1360
+ }
1361
+ /**
1362
+ * @ignore
1363
+ */
1364
+ static instantiateMiniSearch(js, options) {
1365
+ const { documentCount, nextId, fieldIds, averageFieldLength, dirtCount, serializationVersion } = js;
1366
+ if (serializationVersion !== 1 && serializationVersion !== 2) throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");
1367
+ const miniSearch = new MiniSearch(options);
1368
+ miniSearch._documentCount = documentCount;
1369
+ miniSearch._nextId = nextId;
1370
+ miniSearch._idToShortId = /* @__PURE__ */ new Map();
1371
+ miniSearch._fieldIds = fieldIds;
1372
+ miniSearch._avgFieldLength = averageFieldLength;
1373
+ miniSearch._dirtCount = dirtCount || 0;
1374
+ miniSearch._index = new SearchableMap();
1375
+ return miniSearch;
1376
+ }
1377
+ /**
1378
+ * @ignore
1379
+ */
1380
+ executeQuery(query, searchOptions = {}) {
1381
+ if (query === MiniSearch.wildcard) return this.executeWildcardQuery(searchOptions);
1382
+ if (typeof query !== "string") {
1383
+ const options = {
1384
+ ...searchOptions,
1385
+ ...query,
1386
+ queries: void 0
1387
+ };
1388
+ const results = query.queries.map((subquery) => this.executeQuery(subquery, options));
1389
+ return this.combineResults(results, options.combineWith);
1390
+ }
1391
+ const { tokenize, processTerm, searchOptions: globalSearchOptions } = this._options;
1392
+ const options = {
1393
+ tokenize,
1394
+ processTerm,
1395
+ ...globalSearchOptions,
1396
+ ...searchOptions
1397
+ };
1398
+ const { tokenize: searchTokenize, processTerm: searchProcessTerm } = options;
1399
+ const results = searchTokenize(query).flatMap((term) => searchProcessTerm(term)).filter((term) => !!term).map(termToQuerySpec(options)).map((query) => this.executeQuerySpec(query, options));
1400
+ return this.combineResults(results, options.combineWith);
1401
+ }
1402
+ /**
1403
+ * @ignore
1404
+ */
1405
+ executeQuerySpec(query, searchOptions) {
1406
+ const options = {
1407
+ ...this._options.searchOptions,
1408
+ ...searchOptions
1409
+ };
1410
+ const boosts = (options.fields || this._options.fields).reduce((boosts, field) => ({
1411
+ ...boosts,
1412
+ [field]: getOwnProperty(options.boost, field) || 1
1413
+ }), {});
1414
+ const { boostDocument, weights, maxFuzzy, bm25: bm25params } = options;
1415
+ const { fuzzy: fuzzyWeight, prefix: prefixWeight } = {
1416
+ ...defaultSearchOptions.weights,
1417
+ ...weights
1418
+ };
1419
+ const data = this._index.get(query.term);
1420
+ const results = this.termResults(query.term, query.term, 1, query.termBoost, data, boosts, boostDocument, bm25params);
1421
+ let prefixMatches;
1422
+ let fuzzyMatches;
1423
+ if (query.prefix) prefixMatches = this._index.atPrefix(query.term);
1424
+ if (query.fuzzy) {
1425
+ const fuzzy = query.fuzzy === true ? .2 : query.fuzzy;
1426
+ const maxDistance = fuzzy < 1 ? Math.min(maxFuzzy, Math.round(query.term.length * fuzzy)) : fuzzy;
1427
+ if (maxDistance) fuzzyMatches = this._index.fuzzyGet(query.term, maxDistance);
1428
+ }
1429
+ if (prefixMatches) for (const [term, data] of prefixMatches) {
1430
+ const distance = term.length - query.term.length;
1431
+ if (!distance) continue;
1432
+ fuzzyMatches === null || fuzzyMatches === void 0 || fuzzyMatches.delete(term);
1433
+ const weight = prefixWeight * term.length / (term.length + .3 * distance);
1434
+ this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results);
1435
+ }
1436
+ if (fuzzyMatches) for (const term of fuzzyMatches.keys()) {
1437
+ const [data, distance] = fuzzyMatches.get(term);
1438
+ if (!distance) continue;
1439
+ const weight = fuzzyWeight * term.length / (term.length + distance);
1440
+ this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results);
1441
+ }
1442
+ return results;
1443
+ }
1444
+ /**
1445
+ * @ignore
1446
+ */
1447
+ executeWildcardQuery(searchOptions) {
1448
+ const results = /* @__PURE__ */ new Map();
1449
+ const options = {
1450
+ ...this._options.searchOptions,
1451
+ ...searchOptions
1452
+ };
1453
+ for (const [shortId, id] of this._documentIds) {
1454
+ const score = options.boostDocument ? options.boostDocument(id, "", this._storedFields.get(shortId)) : 1;
1455
+ results.set(shortId, {
1456
+ score,
1457
+ terms: [],
1458
+ match: {}
1459
+ });
1460
+ }
1461
+ return results;
1462
+ }
1463
+ /**
1464
+ * @ignore
1465
+ */
1466
+ combineResults(results, combineWith = OR) {
1467
+ if (results.length === 0) return /* @__PURE__ */ new Map();
1468
+ const combinator = combinators[combineWith.toLowerCase()];
1469
+ if (!combinator) throw new Error(`Invalid combination operator: ${combineWith}`);
1470
+ return results.reduce(combinator) || /* @__PURE__ */ new Map();
1471
+ }
1472
+ /**
1473
+ * Allows serialization of the index to JSON, to possibly store it and later
1474
+ * deserialize it with {@link MiniSearch.loadJSON}.
1475
+ *
1476
+ * Normally one does not directly call this method, but rather call the
1477
+ * standard JavaScript `JSON.stringify()` passing the {@link MiniSearch}
1478
+ * instance, and JavaScript will internally call this method. Upon
1479
+ * deserialization, one must pass to {@link MiniSearch.loadJSON} the same
1480
+ * options used to create the original instance that was serialized.
1481
+ *
1482
+ * ### Usage:
1483
+ *
1484
+ * ```javascript
1485
+ * // Serialize the index:
1486
+ * let miniSearch = new MiniSearch({ fields: ['title', 'text'] })
1487
+ * miniSearch.addAll(documents)
1488
+ * const json = JSON.stringify(miniSearch)
1489
+ *
1490
+ * // Later, to deserialize it:
1491
+ * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] })
1492
+ * ```
1493
+ *
1494
+ * @return A plain-object serializable representation of the search index.
1495
+ */
1496
+ toJSON() {
1497
+ const index = [];
1498
+ for (const [term, fieldIndex] of this._index) {
1499
+ const data = {};
1500
+ for (const [fieldId, freqs] of fieldIndex) data[fieldId] = Object.fromEntries(freqs);
1501
+ index.push([term, data]);
1502
+ }
1503
+ return {
1504
+ documentCount: this._documentCount,
1505
+ nextId: this._nextId,
1506
+ documentIds: Object.fromEntries(this._documentIds),
1507
+ fieldIds: this._fieldIds,
1508
+ fieldLength: Object.fromEntries(this._fieldLength),
1509
+ averageFieldLength: this._avgFieldLength,
1510
+ storedFields: Object.fromEntries(this._storedFields),
1511
+ dirtCount: this._dirtCount,
1512
+ index,
1513
+ serializationVersion: 2
1514
+ };
1515
+ }
1516
+ /**
1517
+ * @ignore
1518
+ */
1519
+ termResults(sourceTerm, derivedTerm, termWeight, termBoost, fieldTermData, fieldBoosts, boostDocumentFn, bm25params, results = /* @__PURE__ */ new Map()) {
1520
+ if (fieldTermData == null) return results;
1521
+ for (const field of Object.keys(fieldBoosts)) {
1522
+ const fieldBoost = fieldBoosts[field];
1523
+ const fieldId = this._fieldIds[field];
1524
+ const fieldTermFreqs = fieldTermData.get(fieldId);
1525
+ if (fieldTermFreqs == null) continue;
1526
+ let matchingFields = fieldTermFreqs.size;
1527
+ const avgFieldLength = this._avgFieldLength[fieldId];
1528
+ for (const docId of fieldTermFreqs.keys()) {
1529
+ if (!this._documentIds.has(docId)) {
1530
+ this.removeTerm(fieldId, docId, derivedTerm);
1531
+ matchingFields -= 1;
1532
+ continue;
1533
+ }
1534
+ const docBoost = boostDocumentFn ? boostDocumentFn(this._documentIds.get(docId), derivedTerm, this._storedFields.get(docId)) : 1;
1535
+ if (!docBoost) continue;
1536
+ const termFreq = fieldTermFreqs.get(docId);
1537
+ const fieldLength = this._fieldLength.get(docId)[fieldId];
1538
+ const rawScore = calcBM25Score(termFreq, matchingFields, this._documentCount, fieldLength, avgFieldLength, bm25params);
1539
+ const weightedScore = termWeight * termBoost * fieldBoost * docBoost * rawScore;
1540
+ const result = results.get(docId);
1541
+ if (result) {
1542
+ result.score += weightedScore;
1543
+ assignUniqueTerm(result.terms, sourceTerm);
1544
+ const match = getOwnProperty(result.match, derivedTerm);
1545
+ if (match) match.push(field);
1546
+ else result.match[derivedTerm] = [field];
1547
+ } else results.set(docId, {
1548
+ score: weightedScore,
1549
+ terms: [sourceTerm],
1550
+ match: { [derivedTerm]: [field] }
1551
+ });
1552
+ }
1553
+ }
1554
+ return results;
1555
+ }
1556
+ /**
1557
+ * @ignore
1558
+ */
1559
+ addTerm(fieldId, documentId, term) {
1560
+ const indexData = this._index.fetch(term, createMap);
1561
+ let fieldIndex = indexData.get(fieldId);
1562
+ if (fieldIndex == null) {
1563
+ fieldIndex = /* @__PURE__ */ new Map();
1564
+ fieldIndex.set(documentId, 1);
1565
+ indexData.set(fieldId, fieldIndex);
1566
+ } else {
1567
+ const docs = fieldIndex.get(documentId);
1568
+ fieldIndex.set(documentId, (docs || 0) + 1);
1569
+ }
1570
+ }
1571
+ /**
1572
+ * @ignore
1573
+ */
1574
+ removeTerm(fieldId, documentId, term) {
1575
+ if (!this._index.has(term)) {
1576
+ this.warnDocumentChanged(documentId, fieldId, term);
1577
+ return;
1578
+ }
1579
+ const indexData = this._index.fetch(term, createMap);
1580
+ const fieldIndex = indexData.get(fieldId);
1581
+ if (fieldIndex == null || fieldIndex.get(documentId) == null) this.warnDocumentChanged(documentId, fieldId, term);
1582
+ else if (fieldIndex.get(documentId) <= 1) {
1583
+ if (fieldIndex.size <= 1) indexData.delete(fieldId);
1584
+ else fieldIndex.delete(documentId);
1585
+ } else fieldIndex.set(documentId, fieldIndex.get(documentId) - 1);
1586
+ if (this._index.get(term).size === 0) this._index.delete(term);
1587
+ }
1588
+ /**
1589
+ * @ignore
1590
+ */
1591
+ warnDocumentChanged(shortDocumentId, fieldId, term) {
1592
+ for (const fieldName of Object.keys(this._fieldIds)) if (this._fieldIds[fieldName] === fieldId) {
1593
+ 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");
1594
+ return;
1595
+ }
1596
+ }
1597
+ /**
1598
+ * @ignore
1599
+ */
1600
+ addDocumentId(documentId) {
1601
+ const shortDocumentId = this._nextId;
1602
+ this._idToShortId.set(documentId, shortDocumentId);
1603
+ this._documentIds.set(shortDocumentId, documentId);
1604
+ this._documentCount += 1;
1605
+ this._nextId += 1;
1606
+ return shortDocumentId;
1607
+ }
1608
+ /**
1609
+ * @ignore
1610
+ */
1611
+ addFields(fields) {
1612
+ for (let i = 0; i < fields.length; i++) this._fieldIds[fields[i]] = i;
1613
+ }
1614
+ /**
1615
+ * @ignore
1616
+ */
1617
+ addFieldLength(documentId, fieldId, count, length) {
1618
+ let fieldLengths = this._fieldLength.get(documentId);
1619
+ if (fieldLengths == null) this._fieldLength.set(documentId, fieldLengths = []);
1620
+ fieldLengths[fieldId] = length;
1621
+ const totalFieldLength = (this._avgFieldLength[fieldId] || 0) * count + length;
1622
+ this._avgFieldLength[fieldId] = totalFieldLength / (count + 1);
1623
+ }
1624
+ /**
1625
+ * @ignore
1626
+ */
1627
+ removeFieldLength(documentId, fieldId, count, length) {
1628
+ if (count === 1) {
1629
+ this._avgFieldLength[fieldId] = 0;
1630
+ return;
1631
+ }
1632
+ const totalFieldLength = this._avgFieldLength[fieldId] * count - length;
1633
+ this._avgFieldLength[fieldId] = totalFieldLength / (count - 1);
1634
+ }
1635
+ /**
1636
+ * @ignore
1637
+ */
1638
+ saveStoredFields(documentId, doc) {
1639
+ const { storeFields, extractField } = this._options;
1640
+ if (storeFields == null || storeFields.length === 0) return;
1641
+ let documentFields = this._storedFields.get(documentId);
1642
+ if (documentFields == null) this._storedFields.set(documentId, documentFields = {});
1643
+ for (const fieldName of storeFields) {
1644
+ const fieldValue = extractField(doc, fieldName);
1645
+ if (fieldValue !== void 0) documentFields[fieldName] = fieldValue;
1646
+ }
1647
+ }
1648
+ };
1649
+ /**
1650
+ * The special wildcard symbol that can be passed to {@link MiniSearch#search}
1651
+ * to match all documents
1652
+ */
1653
+ MiniSearch.wildcard = Symbol("*");
1654
+ var getOwnProperty = (object, property) => Object.prototype.hasOwnProperty.call(object, property) ? object[property] : void 0;
1655
+ var combinators = {
1656
+ [OR]: (a, b) => {
1657
+ for (const docId of b.keys()) {
1658
+ const existing = a.get(docId);
1659
+ if (existing == null) a.set(docId, b.get(docId));
1660
+ else {
1661
+ const { score, terms, match } = b.get(docId);
1662
+ existing.score = existing.score + score;
1663
+ existing.match = Object.assign(existing.match, match);
1664
+ assignUniqueTerms(existing.terms, terms);
1665
+ }
1666
+ }
1667
+ return a;
1668
+ },
1669
+ [AND]: (a, b) => {
1670
+ const combined = /* @__PURE__ */ new Map();
1671
+ for (const docId of b.keys()) {
1672
+ const existing = a.get(docId);
1673
+ if (existing == null) continue;
1674
+ const { score, terms, match } = b.get(docId);
1675
+ assignUniqueTerms(existing.terms, terms);
1676
+ combined.set(docId, {
1677
+ score: existing.score + score,
1678
+ terms: existing.terms,
1679
+ match: Object.assign(existing.match, match)
1680
+ });
1681
+ }
1682
+ return combined;
1683
+ },
1684
+ [AND_NOT]: (a, b) => {
1685
+ for (const docId of b.keys()) a.delete(docId);
1686
+ return a;
1687
+ }
1688
+ };
1689
+ var defaultBM25params = {
1690
+ k: 1.2,
1691
+ b: .7,
1692
+ d: .5
1693
+ };
1694
+ var calcBM25Score = (termFreq, matchingCount, totalCount, fieldLength, avgFieldLength, bm25params) => {
1695
+ const { k, b, d } = bm25params;
1696
+ return Math.log(1 + (totalCount - matchingCount + .5) / (matchingCount + .5)) * (d + termFreq * (k + 1) / (termFreq + k * (1 - b + b * fieldLength / avgFieldLength)));
1697
+ };
1698
+ var termToQuerySpec = (options) => (term, i, terms) => {
1699
+ return {
1700
+ term,
1701
+ fuzzy: typeof options.fuzzy === "function" ? options.fuzzy(term, i, terms) : options.fuzzy || false,
1702
+ prefix: typeof options.prefix === "function" ? options.prefix(term, i, terms) : options.prefix === true,
1703
+ termBoost: typeof options.boostTerm === "function" ? options.boostTerm(term, i, terms) : 1
1704
+ };
1705
+ };
1706
+ var defaultOptions = {
1707
+ idField: "id",
1708
+ extractField: (document, fieldName) => document[fieldName],
1709
+ stringifyField: (fieldValue, fieldName) => fieldValue.toString(),
1710
+ tokenize: (text) => text.split(SPACE_OR_PUNCTUATION),
1711
+ processTerm: (term) => term.toLowerCase(),
1712
+ fields: void 0,
1713
+ searchOptions: void 0,
1714
+ storeFields: [],
1715
+ logger: (level, message) => {
1716
+ if (typeof (console === null || console === void 0 ? void 0 : console[level]) === "function") console[level](message);
1717
+ },
1718
+ autoVacuum: true
1719
+ };
1720
+ var defaultSearchOptions = {
1721
+ combineWith: OR,
1722
+ prefix: false,
1723
+ fuzzy: false,
1724
+ maxFuzzy: 6,
1725
+ boost: {},
1726
+ weights: {
1727
+ fuzzy: .45,
1728
+ prefix: .375
1729
+ },
1730
+ bm25: defaultBM25params
1731
+ };
1732
+ var defaultAutoSuggestOptions = {
1733
+ combineWith: AND,
1734
+ prefix: (term, i, terms) => i === terms.length - 1
1735
+ };
1736
+ var defaultVacuumOptions = {
1737
+ batchSize: 1e3,
1738
+ batchWait: 10
1739
+ };
1740
+ var defaultVacuumConditions = {
1741
+ minDirtFactor: .1,
1742
+ minDirtCount: 20
1743
+ };
1744
+ var defaultAutoVacuumOptions = {
1745
+ ...defaultVacuumOptions,
1746
+ ...defaultVacuumConditions
1747
+ };
1748
+ var assignUniqueTerm = (target, term) => {
1749
+ if (!target.includes(term)) target.push(term);
1750
+ };
1751
+ var assignUniqueTerms = (target, source) => {
1752
+ for (const term of source) if (!target.includes(term)) target.push(term);
1753
+ };
1754
+ var byScore = ({ score: a }, { score: b }) => b - a;
1755
+ var createMap = () => /* @__PURE__ */ new Map();
1756
+ var objectToNumericMap = (object) => {
1757
+ const map = /* @__PURE__ */ new Map();
1758
+ for (const key of Object.keys(object)) map.set(parseInt(key, 10), object[key]);
1759
+ return map;
1760
+ };
1761
+ var objectToNumericMapAsync = async (object) => {
1762
+ const map = /* @__PURE__ */ new Map();
1763
+ let count = 0;
1764
+ for (const key of Object.keys(object)) {
1765
+ map.set(parseInt(key, 10), object[key]);
1766
+ if (++count % 1e3 === 0) await wait(0);
1767
+ }
1768
+ return map;
1769
+ };
1770
+ var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1771
+ var SPACE_OR_PUNCTUATION = /[\n\r\p{Z}\p{P}]+/u;
1772
+ //#endregion
1773
+ export { MiniSearch as default };