@guebbit/css-toolkit 1.3.1 → 1.4.0

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