@fleox-agent-crm/agentcrm 0.0.0-stage → 0.3.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 (129) hide show
  1. package/LICENSE +143 -0
  2. package/README.md +223 -2
  3. package/changelog.json +57 -0
  4. package/dist/admin/admin-files.json +26 -0
  5. package/dist/admin/assets/chartsImpl-CE2akJat.js +91 -0
  6. package/dist/admin/assets/firebase-BHSUggRo.js +2 -0
  7. package/dist/admin/assets/gitJson-BulGh2KV.js +3 -0
  8. package/dist/admin/assets/index-DidVVK7L.js +1181 -0
  9. package/dist/admin/assets/index-hMXwHSvN.css +1 -0
  10. package/dist/admin/assets/index.esm-BFc7vwnl.js +400 -0
  11. package/dist/admin/assets/index.esm-CtEQZRb1.js +1651 -0
  12. package/dist/admin/assets/index.esm-Dum0J07z.js +16 -0
  13. package/dist/admin/assets/index.esm2017-EOzKbpUS.js +390 -0
  14. package/dist/admin/assets/lucide-react.min-DEDlHCPj.js +6 -0
  15. package/dist/admin/assets/sdk-CnrLnlRo.js +1717 -0
  16. package/dist/admin/config.js +3 -0
  17. package/dist/admin/favicon.svg +1 -0
  18. package/dist/admin/index.html +139 -0
  19. package/dist/admin/runtime/agentcrm-runtime.js +104 -0
  20. package/dist/admin/runtime/lucide-react.js +791 -0
  21. package/dist/admin/runtime/react-dom-client.js +17 -0
  22. package/dist/admin/runtime/react-dom.js +20 -0
  23. package/dist/admin/runtime/react-i18next.js +19 -0
  24. package/dist/admin/runtime/react-jsx-runtime.js +17 -0
  25. package/dist/admin/runtime/react.js +22 -0
  26. package/dist/agent/agentcrm.mjs +3932 -0
  27. package/dist/agent/chunks/_commonjsHelpers-ClciMIcB.mjs +14 -0
  28. package/dist/agent/chunks/activities-Cj_SIOay.mjs +227 -0
  29. package/dist/agent/chunks/api-B6OqNVWp.mjs +97 -0
  30. package/dist/agent/chunks/appearance-BaShelzt.mjs +174 -0
  31. package/dist/agent/chunks/automations-BWrvLqP6.mjs +698 -0
  32. package/dist/agent/chunks/backup-ClSmxmFZ.mjs +103 -0
  33. package/dist/agent/chunks/batch-CVETiJj5.mjs +142 -0
  34. package/dist/agent/chunks/compact-CsFPaAAq.mjs +69 -0
  35. package/dist/agent/chunks/context-CxFfqS4D.mjs +65 -0
  36. package/dist/agent/chunks/core-Dy7vY9H6.mjs +255 -0
  37. package/dist/agent/chunks/dedupe-BepmsaHv.mjs +123 -0
  38. package/dist/agent/chunks/encoding-C9MzdP95.mjs +36 -0
  39. package/dist/agent/chunks/exportCsv-B5hRvkNm.mjs +95 -0
  40. package/dist/agent/chunks/extCheck--7lmVvl7.mjs +193 -0
  41. package/dist/agent/chunks/extPackage-BGl5Oqs8.mjs +115 -0
  42. package/dist/agent/chunks/extScaffold-DqxI7R1e.mjs +320 -0
  43. package/dist/agent/chunks/extensionActions-D2HtpQz4.mjs +48 -0
  44. package/dist/agent/chunks/extensions-BP1k60md.mjs +151 -0
  45. package/dist/agent/chunks/featureRegistry-C9nbVShp.mjs +149 -0
  46. package/dist/agent/chunks/fields-B0bitgmr.mjs +476 -0
  47. package/dist/agent/chunks/files-CjsPJSR6.mjs +158 -0
  48. package/dist/agent/chunks/files-q8Xu5bft.mjs +367 -0
  49. package/dist/agent/chunks/firebase-DxGVQV9E.mjs +454 -0
  50. package/dist/agent/chunks/firebaseRules-iori-s7U.mjs +221 -0
  51. package/dist/agent/chunks/forms-BKU5F9WF.mjs +847 -0
  52. package/dist/agent/chunks/gitJson-fjr8mcHe.mjs +528 -0
  53. package/dist/agent/chunks/hosting-Bme7LxPc.mjs +144 -0
  54. package/dist/agent/chunks/http-Bk9ICb7I.mjs +127 -0
  55. package/dist/agent/chunks/ids-CvnmrMJX.mjs +59 -0
  56. package/dist/agent/chunks/ids-u-noYcy5.mjs +14 -0
  57. package/dist/agent/chunks/importCsv-DmE_sBch.mjs +334 -0
  58. package/dist/agent/chunks/index-B-4W0-P4.mjs +535 -0
  59. package/dist/agent/chunks/index-BM8qeGOb.mjs +2489 -0
  60. package/dist/agent/chunks/index-Bnmav-Oh.mjs +311 -0
  61. package/dist/agent/chunks/index-CRkw3_iF.mjs +147 -0
  62. package/dist/agent/chunks/index-CWrrF1wl.mjs +111 -0
  63. package/dist/agent/chunks/index-DUSdTBkz.mjs +2988 -0
  64. package/dist/agent/chunks/index-RCmo-uld.mjs +26 -0
  65. package/dist/agent/chunks/index-w03ReRs4.mjs +9780 -0
  66. package/dist/agent/chunks/install-CpHoUFtL.mjs +188 -0
  67. package/dist/agent/chunks/jsx-runtime-Ca2uwGDr.mjs +76 -0
  68. package/dist/agent/chunks/loader-C9nm3iwx.mjs +184 -0
  69. package/dist/agent/chunks/lucide-react.min-Bt3gtepY.mjs +64 -0
  70. package/dist/agent/chunks/memory-WNR3VHUJ.mjs +56 -0
  71. package/dist/agent/chunks/migrate-CsClnnN8.mjs +182 -0
  72. package/dist/agent/chunks/modules-CqdVQVJb.mjs +177 -0
  73. package/dist/agent/chunks/nodeImport-BPCt5uMu.mjs +38 -0
  74. package/dist/agent/chunks/package-DWbn3t2R.mjs +194 -0
  75. package/dist/agent/chunks/papaparse-DjBYnQM2.mjs +1285 -0
  76. package/dist/agent/chunks/pipelines-DCdRBNBV.mjs +234 -0
  77. package/dist/agent/chunks/plan-C0TBrU92.mjs +254 -0
  78. package/dist/agent/chunks/pluginRegistry-DyHtlkcr.mjs +83 -0
  79. package/dist/agent/chunks/query-C5nJB_3C.mjs +192 -0
  80. package/dist/agent/chunks/records-DoqiT9xR.mjs +2191 -0
  81. package/dist/agent/chunks/registry-Ceexawxl.mjs +182 -0
  82. package/dist/agent/chunks/registry-DijAKZ24.mjs +431 -0
  83. package/dist/agent/chunks/relations-B9TynBmA.mjs +191 -0
  84. package/dist/agent/chunks/reports-BB59N6ke.mjs +189 -0
  85. package/dist/agent/chunks/runtime-DHo7ZEEO.mjs +14852 -0
  86. package/dist/agent/chunks/runtimeConfig-CCOFg1RM.mjs +250 -0
  87. package/dist/agent/chunks/s3-Dz50-NuA.mjs +903 -0
  88. package/dist/agent/chunks/schema-7-4-qtSS.mjs +203 -0
  89. package/dist/agent/chunks/schema-DlHt2PxI.mjs +367 -0
  90. package/dist/agent/chunks/sdk-whvfg786.mjs +43644 -0
  91. package/dist/agent/chunks/seed-CugPGYZL.mjs +523 -0
  92. package/dist/agent/chunks/server-ISwlDRCN.mjs +242 -0
  93. package/dist/agent/chunks/settings-BtvR_jdm.mjs +76 -0
  94. package/dist/agent/chunks/standardObjects-CheqfDqa.mjs +243 -0
  95. package/dist/agent/chunks/stats-CfeJssSS.mjs +51 -0
  96. package/dist/agent/chunks/store-5gqRSKXg.mjs +122 -0
  97. package/dist/agent/chunks/themes-DPZFv3yc.mjs +43 -0
  98. package/dist/agent/chunks/tools-Bew8lxKx.mjs +844 -0
  99. package/dist/agent/chunks/types-BOy9PUl7.mjs +44 -0
  100. package/dist/agent/chunks/users-DI1BvS0f.mjs +107 -0
  101. package/dist/agent/chunks/utils-DmI8FtXP.mjs +83 -0
  102. package/dist/agent/chunks/views-fO_BM5U_.mjs +109 -0
  103. package/dist/version.json +7 -0
  104. package/package.json +97 -4
  105. package/plugin/.claude-plugin/plugin.json +17 -0
  106. package/plugin/skills/agentcrm-admin/SKILL.md +191 -0
  107. package/plugin/skills/agentcrm-admin/references/appearance.md +26 -0
  108. package/plugin/skills/agentcrm-admin/references/import.md +16 -0
  109. package/plugin/skills/agentcrm-admin/references/records.md +30 -0
  110. package/plugin/skills/agentcrm-admin/references/schema.md +59 -0
  111. package/plugin/skills/agentcrm-extensions/SKILL.md +93 -0
  112. package/plugin/skills/agentcrm-extensions/references/module-recipes.md +213 -0
  113. package/plugin/skills/agentcrm-extensions/references/runtime-api.md +41 -0
  114. package/plugin/skills/agentcrm-extensions/references/testing.md +76 -0
  115. package/plugin/skills/agentcrm-extensions/references/theme-recipes.md +65 -0
  116. package/plugin/skills/agentcrm-install/SKILL.md +116 -0
  117. package/plugin/skills/agentcrm-install/references/firebase.md +18 -0
  118. package/plugin/skills/agentcrm-install/references/github.md +20 -0
  119. package/plugin/skills/agentcrm-install/references/mcp.md +17 -0
  120. package/plugin/skills/agentcrm-install/references/plans.md +45 -0
  121. package/plugin/skills/agentcrm-install/references/s3.md +24 -0
  122. package/plugin/skills/agentcrm-manage/SKILL.md +108 -0
  123. package/plugin/skills/agentcrm-manage/references/cron.md +11 -0
  124. package/plugin/skills/agentcrm-manage/references/doctor.md +18 -0
  125. package/plugin/skills/agentcrm-sales/SKILL.md +92 -0
  126. package/plugin/skills/agentcrm-sales/references/enrichment.md +13 -0
  127. package/plugin/skills/agentcrm-sales/references/playbooks.md +29 -0
  128. package/plugin/skills/agentcrm-sales/references/weekly-report.md +27 -0
  129. package/types/agentcrm-runtime.d.ts +894 -0
@@ -0,0 +1,2191 @@
1
+ import { createRequire as __acrmRequire } from "node:module";
2
+ import { fileURLToPath as __acrmPath } from "node:url";
3
+ import { dirname as __acrmDirname } from "node:path";
4
+ const require2 = __acrmRequire(import.meta.url);
5
+ const __filename = __acrmPath(import.meta.url);
6
+ const __dirname = __acrmDirname(__filename);
7
+ import { normalizeDomain, recordLabel, validateRecordFields, defaultFieldValues, isEmptyFieldValue, FieldValidationError, normalizeEmail } from "./fields-B0bitgmr.mjs";
8
+ import { n as newId } from "./ids-CvnmrMJX.mjs";
9
+ import { b as applyFilters, a as applySorts, p as paginate } from "./query-C5nJB_3C.mjs";
10
+ import { n as normalizeStandardFields } from "./standardObjects-CheqfDqa.mjs";
11
+ import { assertCan, OpsError, actorId, emit } from "./context-CxFfqS4D.mjs";
12
+ import { i as inverseRelations, j as expandRelations, l as labelOf, v as validateRelationValue, c as rewriteReferences, b as fileCleanupMutations } from "./relations-B9TynBmA.mjs";
13
+ import { activitiesOf, recordsOf, objectsOf, requireObject, requireRecord, recordOf, asDoc, userOf, pipelinesOf } from "./store-5gqRSKXg.mjs";
14
+ import "./pluginRegistry-DyHtlkcr.mjs";
15
+ const ENTRIES = "ENTRIES";
16
+ const KEYS = "KEYS";
17
+ const VALUES = "VALUES";
18
+ const LEAF = "";
19
+ class TreeIterator {
20
+ constructor(set, type) {
21
+ const node = set._tree;
22
+ const keys = Array.from(node.keys());
23
+ this.set = set;
24
+ this._type = type;
25
+ this._path = keys.length > 0 ? [{ node, keys }] : [];
26
+ }
27
+ next() {
28
+ const value = this.dive();
29
+ this.backtrack();
30
+ return value;
31
+ }
32
+ dive() {
33
+ if (this._path.length === 0) {
34
+ return { done: true, value: void 0 };
35
+ }
36
+ const { node, keys } = last$1(this._path);
37
+ if (last$1(keys) === LEAF) {
38
+ return { done: false, value: this.result() };
39
+ }
40
+ const child = node.get(last$1(keys));
41
+ this._path.push({ node: child, keys: Array.from(child.keys()) });
42
+ return this.dive();
43
+ }
44
+ backtrack() {
45
+ if (this._path.length === 0) {
46
+ return;
47
+ }
48
+ const keys = last$1(this._path).keys;
49
+ keys.pop();
50
+ if (keys.length > 0) {
51
+ return;
52
+ }
53
+ this._path.pop();
54
+ this.backtrack();
55
+ }
56
+ key() {
57
+ return this.set._prefix + this._path.map(({ keys }) => last$1(keys)).filter((key) => key !== LEAF).join("");
58
+ }
59
+ value() {
60
+ return last$1(this._path).node.get(LEAF);
61
+ }
62
+ result() {
63
+ switch (this._type) {
64
+ case VALUES:
65
+ return this.value();
66
+ case KEYS:
67
+ return this.key();
68
+ default:
69
+ return [this.key(), this.value()];
70
+ }
71
+ }
72
+ [Symbol.iterator]() {
73
+ return this;
74
+ }
75
+ }
76
+ const last$1 = (array) => {
77
+ return array[array.length - 1];
78
+ };
79
+ const fuzzySearch = (node, query, maxDistance) => {
80
+ const results = /* @__PURE__ */ new Map();
81
+ if (query === void 0)
82
+ return results;
83
+ const n = query.length + 1;
84
+ const m = n + maxDistance;
85
+ const matrix = new Uint8Array(m * n).fill(maxDistance + 1);
86
+ for (let j = 0; j < n; ++j)
87
+ matrix[j] = j;
88
+ for (let i = 1; i < m; ++i)
89
+ matrix[i * n] = i;
90
+ recurse(node, query, maxDistance, results, matrix, 1, n, "");
91
+ return results;
92
+ };
93
+ const recurse = (node, query, maxDistance, results, matrix, m, n, prefix) => {
94
+ const offset = m * n;
95
+ key: for (const key of node.keys()) {
96
+ if (key === LEAF) {
97
+ const distance = matrix[offset - 1];
98
+ if (distance <= maxDistance) {
99
+ results.set(prefix, [node.get(key), distance]);
100
+ }
101
+ } else {
102
+ let i = m;
103
+ for (let pos = 0; pos < key.length; ++pos, ++i) {
104
+ const char = key[pos];
105
+ const thisRowOffset = n * i;
106
+ const prevRowOffset = thisRowOffset - n;
107
+ let minDistance = matrix[thisRowOffset];
108
+ const jmin = Math.max(0, i - maxDistance - 1);
109
+ const jmax = Math.min(n - 1, i + maxDistance);
110
+ for (let j = jmin; j < jmax; ++j) {
111
+ const different = char !== query[j];
112
+ const rpl = matrix[prevRowOffset + j] + +different;
113
+ const del = matrix[prevRowOffset + j + 1] + 1;
114
+ const ins = matrix[thisRowOffset + j] + 1;
115
+ const dist = matrix[thisRowOffset + j + 1] = Math.min(rpl, del, ins);
116
+ if (dist < minDistance)
117
+ minDistance = dist;
118
+ }
119
+ if (minDistance > maxDistance) {
120
+ continue key;
121
+ }
122
+ }
123
+ recurse(node.get(key), query, maxDistance, results, matrix, i, n, prefix + key);
124
+ }
125
+ }
126
+ };
127
+ class SearchableMap {
128
+ /**
129
+ * The constructor is normally called without arguments, creating an empty
130
+ * map. In order to create a {@link SearchableMap} from an iterable or from an
131
+ * object, check {@link SearchableMap.from} and {@link
132
+ * SearchableMap.fromObject}.
133
+ *
134
+ * The constructor arguments are for internal use, when creating derived
135
+ * mutable views of a map at a prefix.
136
+ */
137
+ constructor(tree = /* @__PURE__ */ new Map(), prefix = "") {
138
+ this._size = void 0;
139
+ this._tree = tree;
140
+ this._prefix = prefix;
141
+ }
142
+ /**
143
+ * Creates and returns a mutable view of this {@link SearchableMap},
144
+ * containing only entries that share the given prefix.
145
+ *
146
+ * ### Usage:
147
+ *
148
+ * ```javascript
149
+ * let map = new SearchableMap()
150
+ * map.set("unicorn", 1)
151
+ * map.set("universe", 2)
152
+ * map.set("university", 3)
153
+ * map.set("unique", 4)
154
+ * map.set("hello", 5)
155
+ *
156
+ * let uni = map.atPrefix("uni")
157
+ * uni.get("unique") // => 4
158
+ * uni.get("unicorn") // => 1
159
+ * uni.get("hello") // => undefined
160
+ *
161
+ * let univer = map.atPrefix("univer")
162
+ * univer.get("unique") // => undefined
163
+ * univer.get("universe") // => 2
164
+ * univer.get("university") // => 3
165
+ * ```
166
+ *
167
+ * @param prefix The prefix
168
+ * @return A {@link SearchableMap} representing a mutable view of the original
169
+ * Map at the given prefix
170
+ */
171
+ atPrefix(prefix) {
172
+ if (!prefix.startsWith(this._prefix)) {
173
+ throw new Error("Mismatched prefix");
174
+ }
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()) {
179
+ if (k !== LEAF && k.startsWith(key)) {
180
+ const node2 = /* @__PURE__ */ new Map();
181
+ node2.set(k.slice(key.length), parentNode.get(k));
182
+ return new SearchableMap(node2, prefix);
183
+ }
184
+ }
185
+ }
186
+ return new SearchableMap(node, prefix);
187
+ }
188
+ /**
189
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/clear
190
+ */
191
+ clear() {
192
+ this._size = void 0;
193
+ this._tree.clear();
194
+ }
195
+ /**
196
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/delete
197
+ * @param key Key to delete
198
+ */
199
+ delete(key) {
200
+ this._size = void 0;
201
+ return remove(this._tree, key);
202
+ }
203
+ /**
204
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries
205
+ * @return An iterator iterating through `[key, value]` entries.
206
+ */
207
+ entries() {
208
+ return new TreeIterator(this, ENTRIES);
209
+ }
210
+ /**
211
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach
212
+ * @param fn Iteration function
213
+ */
214
+ forEach(fn) {
215
+ for (const [key, value] of this) {
216
+ fn(key, value, this);
217
+ }
218
+ }
219
+ /**
220
+ * Returns a Map of all the entries that have a key within the given edit
221
+ * distance from the search key. The keys of the returned Map are the matching
222
+ * keys, while the values are two-element arrays where the first element is
223
+ * the value associated to the key, and the second is the edit distance of the
224
+ * key to the search key.
225
+ *
226
+ * ### Usage:
227
+ *
228
+ * ```javascript
229
+ * let map = new SearchableMap()
230
+ * map.set('hello', 'world')
231
+ * map.set('hell', 'yeah')
232
+ * map.set('ciao', 'mondo')
233
+ *
234
+ * // Get all entries that match the key 'hallo' with a maximum edit distance of 2
235
+ * map.fuzzyGet('hallo', 2)
236
+ * // => Map(2) { 'hello' => ['world', 1], 'hell' => ['yeah', 2] }
237
+ *
238
+ * // In the example, the "hello" key has value "world" and edit distance of 1
239
+ * // (change "e" to "a"), the key "hell" has value "yeah" and edit distance of 2
240
+ * // (change "e" to "a", delete "o")
241
+ * ```
242
+ *
243
+ * @param key The search key
244
+ * @param maxEditDistance The maximum edit distance (Levenshtein)
245
+ * @return A Map of the matching keys to their value and edit distance
246
+ */
247
+ fuzzyGet(key, maxEditDistance) {
248
+ return fuzzySearch(this._tree, key, maxEditDistance);
249
+ }
250
+ /**
251
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get
252
+ * @param key Key to get
253
+ * @return Value associated to the key, or `undefined` if the key is not
254
+ * found.
255
+ */
256
+ get(key) {
257
+ const node = lookup(this._tree, key);
258
+ return node !== void 0 ? node.get(LEAF) : void 0;
259
+ }
260
+ /**
261
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has
262
+ * @param key Key
263
+ * @return True if the key is in the map, false otherwise
264
+ */
265
+ has(key) {
266
+ const node = lookup(this._tree, key);
267
+ return node !== void 0 && node.has(LEAF);
268
+ }
269
+ /**
270
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys
271
+ * @return An `Iterable` iterating through keys
272
+ */
273
+ keys() {
274
+ return new TreeIterator(this, KEYS);
275
+ }
276
+ /**
277
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/set
278
+ * @param key Key to set
279
+ * @param value Value to associate to the key
280
+ * @return The {@link SearchableMap} itself, to allow chaining
281
+ */
282
+ set(key, value) {
283
+ if (typeof key !== "string") {
284
+ throw new Error("key must be a string");
285
+ }
286
+ this._size = void 0;
287
+ const node = createPath(this._tree, key);
288
+ node.set(LEAF, value);
289
+ return this;
290
+ }
291
+ /**
292
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/size
293
+ */
294
+ get size() {
295
+ if (this._size) {
296
+ return this._size;
297
+ }
298
+ this._size = 0;
299
+ const iter = this.entries();
300
+ while (!iter.next().done)
301
+ this._size += 1;
302
+ return this._size;
303
+ }
304
+ /**
305
+ * Updates the value at the given key using the provided function. The function
306
+ * is called with the current value at the key, and its return value is used as
307
+ * the new value to be set.
308
+ *
309
+ * ### Example:
310
+ *
311
+ * ```javascript
312
+ * // Increment the current value by one
313
+ * searchableMap.update('somekey', (currentValue) => currentValue == null ? 0 : currentValue + 1)
314
+ * ```
315
+ *
316
+ * If the value at the given key is or will be an object, it might not require
317
+ * re-assignment. In that case it is better to use `fetch()`, because it is
318
+ * faster.
319
+ *
320
+ * @param key The key to update
321
+ * @param fn The function used to compute the new value from the current one
322
+ * @return The {@link SearchableMap} itself, to allow chaining
323
+ */
324
+ update(key, fn) {
325
+ if (typeof key !== "string") {
326
+ throw new Error("key must be a string");
327
+ }
328
+ this._size = void 0;
329
+ const node = createPath(this._tree, key);
330
+ node.set(LEAF, fn(node.get(LEAF)));
331
+ return this;
332
+ }
333
+ /**
334
+ * Fetches the value of the given key. If the value does not exist, calls the
335
+ * given function to create a new value, which is inserted at the given key
336
+ * and subsequently returned.
337
+ *
338
+ * ### Example:
339
+ *
340
+ * ```javascript
341
+ * const map = searchableMap.fetch('somekey', () => new Map())
342
+ * map.set('foo', 'bar')
343
+ * ```
344
+ *
345
+ * @param key The key to update
346
+ * @param initial A function that creates a new value if the key does not exist
347
+ * @return The existing or new value at the given key
348
+ */
349
+ fetch(key, initial) {
350
+ if (typeof key !== "string") {
351
+ throw new Error("key must be a string");
352
+ }
353
+ this._size = void 0;
354
+ const node = createPath(this._tree, key);
355
+ let value = node.get(LEAF);
356
+ if (value === void 0) {
357
+ node.set(LEAF, value = initial());
358
+ }
359
+ return value;
360
+ }
361
+ /**
362
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/values
363
+ * @return An `Iterable` iterating through values.
364
+ */
365
+ values() {
366
+ return new TreeIterator(this, VALUES);
367
+ }
368
+ /**
369
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator
370
+ */
371
+ [Symbol.iterator]() {
372
+ return this.entries();
373
+ }
374
+ /**
375
+ * Creates a {@link SearchableMap} from an `Iterable` of entries
376
+ *
377
+ * @param entries Entries to be inserted in the {@link SearchableMap}
378
+ * @return A new {@link SearchableMap} with the given entries
379
+ */
380
+ static from(entries) {
381
+ const tree = new SearchableMap();
382
+ for (const [key, value] of entries) {
383
+ tree.set(key, value);
384
+ }
385
+ return tree;
386
+ }
387
+ /**
388
+ * Creates a {@link SearchableMap} from the iterable properties of a JavaScript object
389
+ *
390
+ * @param object Object of entries for the {@link SearchableMap}
391
+ * @return A new {@link SearchableMap} with the given entries
392
+ */
393
+ static fromObject(object) {
394
+ return SearchableMap.from(Object.entries(object));
395
+ }
396
+ }
397
+ const trackDown = (tree, key, path = []) => {
398
+ if (key.length === 0 || tree == null) {
399
+ return [tree, path];
400
+ }
401
+ for (const k of tree.keys()) {
402
+ if (k !== LEAF && key.startsWith(k)) {
403
+ path.push([tree, k]);
404
+ return trackDown(tree.get(k), key.slice(k.length), path);
405
+ }
406
+ }
407
+ path.push([tree, key]);
408
+ return trackDown(void 0, "", path);
409
+ };
410
+ const lookup = (tree, key) => {
411
+ if (key.length === 0 || tree == null) {
412
+ return tree;
413
+ }
414
+ for (const k of tree.keys()) {
415
+ if (k !== LEAF && key.startsWith(k)) {
416
+ return lookup(tree.get(k), key.slice(k.length));
417
+ }
418
+ }
419
+ };
420
+ const createPath = (node, key) => {
421
+ const keyLength = key.length;
422
+ outer: for (let pos = 0; node && pos < keyLength; ) {
423
+ for (const k of node.keys()) {
424
+ if (k !== LEAF && key[pos] === k[0]) {
425
+ const len = Math.min(keyLength - pos, k.length);
426
+ let offset = 1;
427
+ while (offset < len && key[pos + offset] === k[offset])
428
+ ++offset;
429
+ const child2 = node.get(k);
430
+ if (offset === k.length) {
431
+ node = child2;
432
+ } else {
433
+ const intermediate = /* @__PURE__ */ new Map();
434
+ intermediate.set(k.slice(offset), child2);
435
+ node.set(key.slice(pos, pos + offset), intermediate);
436
+ node.delete(k);
437
+ node = intermediate;
438
+ }
439
+ pos += offset;
440
+ continue outer;
441
+ }
442
+ }
443
+ const child = /* @__PURE__ */ new Map();
444
+ node.set(key.slice(pos), child);
445
+ return child;
446
+ }
447
+ return node;
448
+ };
449
+ const remove = (tree, key) => {
450
+ const [node, path] = trackDown(tree, key);
451
+ if (node === void 0) {
452
+ return;
453
+ }
454
+ node.delete(LEAF);
455
+ if (node.size === 0) {
456
+ cleanup(path);
457
+ } else if (node.size === 1) {
458
+ const [key2, value] = node.entries().next().value;
459
+ merge(path, key2, value);
460
+ }
461
+ };
462
+ const cleanup = (path) => {
463
+ if (path.length === 0) {
464
+ return;
465
+ }
466
+ const [node, key] = last(path);
467
+ node.delete(key);
468
+ if (node.size === 0) {
469
+ cleanup(path.slice(0, -1));
470
+ } else if (node.size === 1) {
471
+ const [key2, value] = node.entries().next().value;
472
+ if (key2 !== LEAF) {
473
+ merge(path.slice(0, -1), key2, value);
474
+ }
475
+ }
476
+ };
477
+ const merge = (path, key, value) => {
478
+ if (path.length === 0) {
479
+ return;
480
+ }
481
+ const [node, nodeKey] = last(path);
482
+ node.set(nodeKey + key, value);
483
+ node.delete(nodeKey);
484
+ };
485
+ const last = (array) => {
486
+ return array[array.length - 1];
487
+ };
488
+ const OR = "or";
489
+ const AND = "and";
490
+ const AND_NOT = "and_not";
491
+ class MiniSearch {
492
+ /**
493
+ * @param options Configuration options
494
+ *
495
+ * ### Examples:
496
+ *
497
+ * ```javascript
498
+ * // Create a search engine that indexes the 'title' and 'text' fields of your
499
+ * // documents:
500
+ * const miniSearch = new MiniSearch({ fields: ['title', 'text'] })
501
+ * ```
502
+ *
503
+ * ### ID Field:
504
+ *
505
+ * ```javascript
506
+ * // Your documents are assumed to include a unique 'id' field, but if you want
507
+ * // to use a different field for document identification, you can set the
508
+ * // 'idField' option:
509
+ * const miniSearch = new MiniSearch({ idField: 'key', fields: ['title', 'text'] })
510
+ * ```
511
+ *
512
+ * ### Options and defaults:
513
+ *
514
+ * ```javascript
515
+ * // The full set of options (here with their default value) is:
516
+ * const miniSearch = new MiniSearch({
517
+ * // idField: field that uniquely identifies a document
518
+ * idField: 'id',
519
+ *
520
+ * // extractField: function used to get the value of a field in a document.
521
+ * // By default, it assumes the document is a flat object with field names as
522
+ * // property keys and field values as string property values, but custom logic
523
+ * // can be implemented by setting this option to a custom extractor function.
524
+ * extractField: (document, fieldName) => document[fieldName],
525
+ *
526
+ * // tokenize: function used to split fields into individual terms. By
527
+ * // default, it is also used to tokenize search queries, unless a specific
528
+ * // `tokenize` search option is supplied. When tokenizing an indexed field,
529
+ * // the field name is passed as the second argument.
530
+ * tokenize: (string, _fieldName) => string.split(SPACE_OR_PUNCTUATION),
531
+ *
532
+ * // processTerm: function used to process each tokenized term before
533
+ * // indexing. It can be used for stemming and normalization. Return a falsy
534
+ * // value in order to discard a term. By default, it is also used to process
535
+ * // search queries, unless a specific `processTerm` option is supplied as a
536
+ * // search option. When processing a term from a indexed field, the field
537
+ * // name is passed as the second argument.
538
+ * processTerm: (term, _fieldName) => term.toLowerCase(),
539
+ *
540
+ * // searchOptions: default search options, see the `search` method for
541
+ * // details
542
+ * searchOptions: undefined,
543
+ *
544
+ * // fields: document fields to be indexed. Mandatory, but not set by default
545
+ * fields: undefined
546
+ *
547
+ * // storeFields: document fields to be stored and returned as part of the
548
+ * // search results.
549
+ * storeFields: []
550
+ * })
551
+ * ```
552
+ */
553
+ constructor(options) {
554
+ if ((options === null || options === void 0 ? void 0 : options.fields) == null) {
555
+ throw new Error('MiniSearch: option "fields" must be provided');
556
+ }
557
+ const autoVacuum = options.autoVacuum == null || options.autoVacuum === true ? defaultAutoVacuumOptions : options.autoVacuum;
558
+ this._options = {
559
+ ...defaultOptions,
560
+ ...options,
561
+ autoVacuum,
562
+ searchOptions: { ...defaultSearchOptions, ...options.searchOptions || {} },
563
+ autoSuggestOptions: { ...defaultAutoSuggestOptions, ...options.autoSuggestOptions || {} }
564
+ };
565
+ this._index = new SearchableMap();
566
+ this._documentCount = 0;
567
+ this._documentIds = /* @__PURE__ */ new Map();
568
+ this._idToShortId = /* @__PURE__ */ new Map();
569
+ this._fieldIds = {};
570
+ this._fieldLength = /* @__PURE__ */ new Map();
571
+ this._avgFieldLength = [];
572
+ this._nextId = 0;
573
+ this._storedFields = /* @__PURE__ */ new Map();
574
+ this._dirtCount = 0;
575
+ this._currentVacuum = null;
576
+ this._enqueuedVacuum = null;
577
+ this._enqueuedVacuumConditions = defaultVacuumConditions;
578
+ this.addFields(this._options.fields);
579
+ }
580
+ /**
581
+ * Adds a document to the index
582
+ *
583
+ * @param document The document to be indexed
584
+ */
585
+ add(document) {
586
+ const { extractField, stringifyField, tokenize, processTerm, fields, idField } = this._options;
587
+ const id = extractField(document, idField);
588
+ if (id == null) {
589
+ throw new Error(`MiniSearch: document does not have ID field "${idField}"`);
590
+ }
591
+ if (this._idToShortId.has(id)) {
592
+ throw new Error(`MiniSearch: duplicate ID ${id}`);
593
+ }
594
+ const shortDocumentId = this.addDocumentId(id);
595
+ this.saveStoredFields(shortDocumentId, document);
596
+ for (const field of fields) {
597
+ const fieldValue = extractField(document, field);
598
+ if (fieldValue == null)
599
+ continue;
600
+ const tokens = tokenize(stringifyField(fieldValue, field), field);
601
+ const fieldId = this._fieldIds[field];
602
+ const uniqueTerms = new Set(tokens).size;
603
+ this.addFieldLength(shortDocumentId, fieldId, this._documentCount - 1, uniqueTerms);
604
+ for (const term of tokens) {
605
+ const processedTerm = processTerm(term, field);
606
+ if (Array.isArray(processedTerm)) {
607
+ for (const t of processedTerm) {
608
+ this.addTerm(fieldId, shortDocumentId, t);
609
+ }
610
+ } else if (processedTerm) {
611
+ this.addTerm(fieldId, shortDocumentId, processedTerm);
612
+ }
613
+ }
614
+ }
615
+ }
616
+ /**
617
+ * Adds all the given documents to the index
618
+ *
619
+ * @param documents An array of documents to be indexed
620
+ */
621
+ addAll(documents) {
622
+ for (const document of documents)
623
+ this.add(document);
624
+ }
625
+ /**
626
+ * Adds all the given documents to the index asynchronously.
627
+ *
628
+ * Returns a promise that resolves (to `undefined`) when the indexing is done.
629
+ * This method is useful when index many documents, to avoid blocking the main
630
+ * thread. The indexing is performed asynchronously and in chunks.
631
+ *
632
+ * @param documents An array of documents to be indexed
633
+ * @param options Configuration options
634
+ * @return A promise resolving to `undefined` when the indexing is done
635
+ */
636
+ addAllAsync(documents, options = {}) {
637
+ const { chunkSize = 10 } = options;
638
+ const acc = { chunk: [], promise: Promise.resolve() };
639
+ const { chunk, promise } = documents.reduce(({ chunk: chunk2, promise: promise2 }, document, i) => {
640
+ chunk2.push(document);
641
+ if ((i + 1) % chunkSize === 0) {
642
+ return {
643
+ chunk: [],
644
+ promise: promise2.then(() => new Promise((resolve) => setTimeout(resolve, 0))).then(() => this.addAll(chunk2))
645
+ };
646
+ } else {
647
+ return { chunk: chunk2, promise: promise2 };
648
+ }
649
+ }, acc);
650
+ return promise.then(() => this.addAll(chunk));
651
+ }
652
+ /**
653
+ * Removes the given document from the index.
654
+ *
655
+ * The document to remove must NOT have changed between indexing and removal,
656
+ * otherwise the index will be corrupted.
657
+ *
658
+ * This method requires passing the full document to be removed (not just the
659
+ * ID), and immediately removes the document from the inverted index, allowing
660
+ * memory to be released. A convenient alternative is {@link
661
+ * MiniSearch#discard}, which needs only the document ID, and has the same
662
+ * visible effect, but delays cleaning up the index until the next vacuuming.
663
+ *
664
+ * @param document The document to be removed
665
+ */
666
+ remove(document) {
667
+ const { tokenize, processTerm, extractField, stringifyField, fields, idField } = this._options;
668
+ const id = extractField(document, idField);
669
+ if (id == null) {
670
+ throw new Error(`MiniSearch: document does not have ID field "${idField}"`);
671
+ }
672
+ const shortId = this._idToShortId.get(id);
673
+ if (shortId == null) {
674
+ throw new Error(`MiniSearch: cannot remove document with ID ${id}: it is not in the index`);
675
+ }
676
+ for (const field of fields) {
677
+ const fieldValue = extractField(document, field);
678
+ if (fieldValue == null)
679
+ continue;
680
+ const tokens = tokenize(stringifyField(fieldValue, field), field);
681
+ const fieldId = this._fieldIds[field];
682
+ const uniqueTerms = new Set(tokens).size;
683
+ this.removeFieldLength(shortId, fieldId, this._documentCount, uniqueTerms);
684
+ for (const term of tokens) {
685
+ const processedTerm = processTerm(term, field);
686
+ if (Array.isArray(processedTerm)) {
687
+ for (const t of processedTerm) {
688
+ this.removeTerm(fieldId, shortId, t);
689
+ }
690
+ } else if (processedTerm) {
691
+ this.removeTerm(fieldId, shortId, processedTerm);
692
+ }
693
+ }
694
+ }
695
+ this._storedFields.delete(shortId);
696
+ this._documentIds.delete(shortId);
697
+ this._idToShortId.delete(id);
698
+ this._fieldLength.delete(shortId);
699
+ this._documentCount -= 1;
700
+ }
701
+ /**
702
+ * Removes all the given documents from the index. If called with no arguments,
703
+ * it removes _all_ documents from the index.
704
+ *
705
+ * @param documents The documents to be removed. If this argument is omitted,
706
+ * all documents are removed. Note that, for removing all documents, it is
707
+ * more efficient to call this method with no arguments than to pass all
708
+ * documents.
709
+ */
710
+ removeAll(documents) {
711
+ if (documents) {
712
+ for (const document of documents)
713
+ this.remove(document);
714
+ } else if (arguments.length > 0) {
715
+ throw new Error("Expected documents to be present. Omit the argument to remove all documents.");
716
+ } else {
717
+ this._index = new SearchableMap();
718
+ this._documentCount = 0;
719
+ this._documentIds = /* @__PURE__ */ new Map();
720
+ this._idToShortId = /* @__PURE__ */ new Map();
721
+ this._fieldLength = /* @__PURE__ */ new Map();
722
+ this._avgFieldLength = [];
723
+ this._storedFields = /* @__PURE__ */ new Map();
724
+ this._nextId = 0;
725
+ }
726
+ }
727
+ /**
728
+ * Discards the document with the given ID, so it won't appear in search results
729
+ *
730
+ * It has the same visible effect of {@link MiniSearch.remove} (both cause the
731
+ * document to stop appearing in searches), but a different effect on the
732
+ * internal data structures:
733
+ *
734
+ * - {@link MiniSearch#remove} requires passing the full document to be
735
+ * removed as argument, and removes it from the inverted index immediately.
736
+ *
737
+ * - {@link MiniSearch#discard} instead only needs the document ID, and
738
+ * works by marking the current version of the document as discarded, so it
739
+ * is immediately ignored by searches. This is faster and more convenient
740
+ * than {@link MiniSearch#remove}, but the index is not immediately
741
+ * modified. To take care of that, vacuuming is performed after a certain
742
+ * number of documents are discarded, cleaning up the index and allowing
743
+ * memory to be released.
744
+ *
745
+ * After discarding a document, it is possible to re-add a new version, and
746
+ * only the new version will appear in searches. In other words, discarding
747
+ * and re-adding a document works exactly like removing and re-adding it. The
748
+ * {@link MiniSearch.replace} method can also be used to replace a document
749
+ * with a new version.
750
+ *
751
+ * #### Details about vacuuming
752
+ *
753
+ * Repetite calls to this method would leave obsolete document references in
754
+ * the index, invisible to searches. Two mechanisms take care of cleaning up:
755
+ * clean up during search, and vacuuming.
756
+ *
757
+ * - Upon search, whenever a discarded ID is found (and ignored for the
758
+ * results), references to the discarded document are removed from the
759
+ * inverted index entries for the search terms. This ensures that subsequent
760
+ * searches for the same terms do not need to skip these obsolete references
761
+ * again.
762
+ *
763
+ * - In addition, vacuuming is performed automatically by default (see the
764
+ * `autoVacuum` field in {@link Options}) after a certain number of
765
+ * documents are discarded. Vacuuming traverses all terms in the index,
766
+ * cleaning up all references to discarded documents. Vacuuming can also be
767
+ * triggered manually by calling {@link MiniSearch#vacuum}.
768
+ *
769
+ * @param id The ID of the document to be discarded
770
+ */
771
+ discard(id) {
772
+ const shortId = this._idToShortId.get(id);
773
+ if (shortId == null) {
774
+ throw new Error(`MiniSearch: cannot discard document with ID ${id}: it is not in the index`);
775
+ }
776
+ this._idToShortId.delete(id);
777
+ this._documentIds.delete(shortId);
778
+ this._storedFields.delete(shortId);
779
+ (this._fieldLength.get(shortId) || []).forEach((fieldLength, fieldId) => {
780
+ this.removeFieldLength(shortId, fieldId, this._documentCount, fieldLength);
781
+ });
782
+ this._fieldLength.delete(shortId);
783
+ this._documentCount -= 1;
784
+ this._dirtCount += 1;
785
+ this.maybeAutoVacuum();
786
+ }
787
+ maybeAutoVacuum() {
788
+ if (this._options.autoVacuum === false) {
789
+ return;
790
+ }
791
+ const { minDirtFactor, minDirtCount, batchSize, batchWait } = this._options.autoVacuum;
792
+ this.conditionalVacuum({ batchSize, batchWait }, { minDirtCount, minDirtFactor });
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) {
811
+ this.discard(id);
812
+ }
813
+ } finally {
814
+ this._options.autoVacuum = autoVacuum;
815
+ }
816
+ this.maybeAutoVacuum();
817
+ }
818
+ /**
819
+ * It replaces an existing document with the given updated version
820
+ *
821
+ * It works by discarding the current version and adding the updated one, so
822
+ * it is functionally equivalent to calling {@link MiniSearch#discard}
823
+ * followed by {@link MiniSearch#add}. The ID of the updated document should
824
+ * be the same as the original one.
825
+ *
826
+ * Since it uses {@link MiniSearch#discard} internally, this method relies on
827
+ * vacuuming to clean up obsolete document references from the index, allowing
828
+ * memory to be released (see {@link MiniSearch#discard}).
829
+ *
830
+ * @param updatedDocument The updated document to replace the old version
831
+ * with
832
+ */
833
+ replace(updatedDocument) {
834
+ const { idField, extractField } = this._options;
835
+ const id = extractField(updatedDocument, idField);
836
+ this.discard(id);
837
+ this.add(updatedDocument);
838
+ }
839
+ /**
840
+ * Triggers a manual vacuuming, cleaning up references to discarded documents
841
+ * from the inverted index
842
+ *
843
+ * Vacuuming is only useful for applications that use the {@link
844
+ * MiniSearch#discard} or {@link MiniSearch#replace} methods.
845
+ *
846
+ * By default, vacuuming is performed automatically when needed (controlled by
847
+ * the `autoVacuum` field in {@link Options}), so there is usually no need to
848
+ * call this method, unless one wants to make sure to perform vacuuming at a
849
+ * specific moment.
850
+ *
851
+ * Vacuuming traverses all terms in the inverted index in batches, and cleans
852
+ * up references to discarded documents from the posting list, allowing memory
853
+ * to be released.
854
+ *
855
+ * The method takes an optional object as argument with the following keys:
856
+ *
857
+ * - `batchSize`: the size of each batch (1000 by default)
858
+ *
859
+ * - `batchWait`: the number of milliseconds to wait between batches (10 by
860
+ * default)
861
+ *
862
+ * On large indexes, vacuuming could have a non-negligible cost: batching
863
+ * avoids blocking the thread for long, diluting this cost so that it is not
864
+ * negatively affecting the application. Nonetheless, this method should only
865
+ * be called when necessary, and relying on automatic vacuuming is usually
866
+ * better.
867
+ *
868
+ * It returns a promise that resolves (to undefined) when the clean up is
869
+ * completed. If vacuuming is already ongoing at the time this method is
870
+ * called, a new one is enqueued immediately after the ongoing one, and a
871
+ * corresponding promise is returned. However, no more than one vacuuming is
872
+ * enqueued on top of the ongoing one, even if this method is called more
873
+ * times (enqueuing multiple ones would be useless).
874
+ *
875
+ * @param options Configuration options for the batch size and delay. See
876
+ * {@link VacuumOptions}.
877
+ */
878
+ vacuum(options = {}) {
879
+ return this.conditionalVacuum(options);
880
+ }
881
+ conditionalVacuum(options, conditions) {
882
+ if (this._currentVacuum) {
883
+ this._enqueuedVacuumConditions = this._enqueuedVacuumConditions && conditions;
884
+ if (this._enqueuedVacuum != null) {
885
+ return this._enqueuedVacuum;
886
+ }
887
+ this._enqueuedVacuum = this._currentVacuum.then(() => {
888
+ const conditions2 = this._enqueuedVacuumConditions;
889
+ this._enqueuedVacuumConditions = defaultVacuumConditions;
890
+ return this.performVacuuming(options, conditions2);
891
+ });
892
+ return this._enqueuedVacuum;
893
+ }
894
+ if (this.vacuumConditionsMet(conditions) === false) {
895
+ return Promise.resolve();
896
+ }
897
+ this._currentVacuum = this.performVacuuming(options);
898
+ return this._currentVacuum;
899
+ }
900
+ async performVacuuming(options, conditions) {
901
+ const initialDirtCount = this._dirtCount;
902
+ if (this.vacuumConditionsMet(conditions)) {
903
+ const batchSize = options.batchSize || defaultVacuumOptions.batchSize;
904
+ const batchWait = options.batchWait || defaultVacuumOptions.batchWait;
905
+ let i = 1;
906
+ for (const [term, fieldsData] of this._index) {
907
+ for (const [fieldId, fieldIndex] of fieldsData) {
908
+ for (const [shortId] of fieldIndex) {
909
+ if (this._documentIds.has(shortId)) {
910
+ continue;
911
+ }
912
+ if (fieldIndex.size <= 1) {
913
+ fieldsData.delete(fieldId);
914
+ } else {
915
+ fieldIndex.delete(shortId);
916
+ }
917
+ }
918
+ }
919
+ if (this._index.get(term).size === 0) {
920
+ this._index.delete(term);
921
+ }
922
+ if (i % batchSize === 0) {
923
+ await new Promise((resolve) => setTimeout(resolve, batchWait));
924
+ }
925
+ i += 1;
926
+ }
927
+ this._dirtCount -= initialDirtCount;
928
+ }
929
+ await null;
930
+ this._currentVacuum = this._enqueuedVacuum;
931
+ this._enqueuedVacuum = null;
932
+ }
933
+ vacuumConditionsMet(conditions) {
934
+ if (conditions == null) {
935
+ return true;
936
+ }
937
+ let { minDirtCount, minDirtFactor } = conditions;
938
+ minDirtCount = minDirtCount || defaultAutoVacuumOptions.minDirtCount;
939
+ minDirtFactor = minDirtFactor || defaultAutoVacuumOptions.minDirtFactor;
940
+ return this.dirtCount >= minDirtCount && this.dirtFactor >= minDirtFactor;
941
+ }
942
+ /**
943
+ * Is `true` if a vacuuming operation is ongoing, `false` otherwise
944
+ */
945
+ get isVacuuming() {
946
+ return this._currentVacuum != null;
947
+ }
948
+ /**
949
+ * The number of documents discarded since the most recent vacuuming
950
+ */
951
+ get dirtCount() {
952
+ return this._dirtCount;
953
+ }
954
+ /**
955
+ * A number between 0 and 1 giving an indication about the proportion of
956
+ * documents that are discarded, and can therefore be cleaned up by vacuuming.
957
+ * A value close to 0 means that the index is relatively clean, while a higher
958
+ * value means that the index is relatively dirty, and vacuuming could release
959
+ * memory.
960
+ */
961
+ get dirtFactor() {
962
+ return this._dirtCount / (1 + this._documentCount + this._dirtCount);
963
+ }
964
+ /**
965
+ * Returns `true` if a document with the given ID is present in the index and
966
+ * available for search, `false` otherwise
967
+ *
968
+ * @param id The document ID
969
+ */
970
+ has(id) {
971
+ return this._idToShortId.has(id);
972
+ }
973
+ /**
974
+ * Returns the stored fields (as configured in the `storeFields` constructor
975
+ * option) for the given document ID. Returns `undefined` if the document is
976
+ * not present in the index.
977
+ *
978
+ * @param id The document ID
979
+ */
980
+ getStoredFields(id) {
981
+ const shortId = this._idToShortId.get(id);
982
+ if (shortId == null) {
983
+ return void 0;
984
+ }
985
+ return this._storedFields.get(shortId);
986
+ }
987
+ /**
988
+ * Search for documents matching the given search query.
989
+ *
990
+ * The result is a list of scored document IDs matching the query, sorted by
991
+ * descending score, and each including data about which terms were matched and
992
+ * in which fields.
993
+ *
994
+ * ### Basic usage:
995
+ *
996
+ * ```javascript
997
+ * // Search for "zen art motorcycle" with default options: terms have to match
998
+ * // exactly, and individual terms are joined with OR
999
+ * miniSearch.search('zen art motorcycle')
1000
+ * // => [ { id: 2, score: 2.77258, match: { ... } }, { id: 4, score: 1.38629, match: { ... } } ]
1001
+ * ```
1002
+ *
1003
+ * ### Restrict search to specific fields:
1004
+ *
1005
+ * ```javascript
1006
+ * // Search only in the 'title' field
1007
+ * miniSearch.search('zen', { fields: ['title'] })
1008
+ * ```
1009
+ *
1010
+ * ### Field boosting:
1011
+ *
1012
+ * ```javascript
1013
+ * // Boost a field
1014
+ * miniSearch.search('zen', { boost: { title: 2 } })
1015
+ * ```
1016
+ *
1017
+ * ### Prefix search:
1018
+ *
1019
+ * ```javascript
1020
+ * // Search for "moto" with prefix search (it will match documents
1021
+ * // containing terms that start with "moto" or "neuro")
1022
+ * miniSearch.search('moto neuro', { prefix: true })
1023
+ * ```
1024
+ *
1025
+ * ### Fuzzy search:
1026
+ *
1027
+ * ```javascript
1028
+ * // Search for "ismael" with fuzzy search (it will match documents containing
1029
+ * // terms similar to "ismael", with a maximum edit distance of 0.2 term.length
1030
+ * // (rounded to nearest integer)
1031
+ * miniSearch.search('ismael', { fuzzy: 0.2 })
1032
+ * ```
1033
+ *
1034
+ * ### Combining strategies:
1035
+ *
1036
+ * ```javascript
1037
+ * // Mix of exact match, prefix search, and fuzzy search
1038
+ * miniSearch.search('ismael mob', {
1039
+ * prefix: true,
1040
+ * fuzzy: 0.2
1041
+ * })
1042
+ * ```
1043
+ *
1044
+ * ### Advanced prefix and fuzzy search:
1045
+ *
1046
+ * ```javascript
1047
+ * // Perform fuzzy and prefix search depending on the search term. Here
1048
+ * // performing prefix and fuzzy search only on terms longer than 3 characters
1049
+ * miniSearch.search('ismael mob', {
1050
+ * prefix: term => term.length > 3
1051
+ * fuzzy: term => term.length > 3 ? 0.2 : null
1052
+ * })
1053
+ * ```
1054
+ *
1055
+ * ### Combine with AND:
1056
+ *
1057
+ * ```javascript
1058
+ * // Combine search terms with AND (to match only documents that contain both
1059
+ * // "motorcycle" and "art")
1060
+ * miniSearch.search('motorcycle art', { combineWith: 'AND' })
1061
+ * ```
1062
+ *
1063
+ * ### Combine with AND_NOT:
1064
+ *
1065
+ * There is also an AND_NOT combinator, that finds documents that match the
1066
+ * first term, but do not match any of the other terms. This combinator is
1067
+ * rarely useful with simple queries, and is meant to be used with advanced
1068
+ * query combinations (see later for more details).
1069
+ *
1070
+ * ### Filtering results:
1071
+ *
1072
+ * ```javascript
1073
+ * // Filter only results in the 'fiction' category (assuming that 'category'
1074
+ * // is a stored field)
1075
+ * miniSearch.search('motorcycle art', {
1076
+ * filter: (result) => result.category === 'fiction'
1077
+ * })
1078
+ * ```
1079
+ *
1080
+ * ### Wildcard query
1081
+ *
1082
+ * Searching for an empty string (assuming the default tokenizer) returns no
1083
+ * results. Sometimes though, one needs to match all documents, like in a
1084
+ * "wildcard" search. This is possible by passing the special value
1085
+ * {@link MiniSearch.wildcard} as the query:
1086
+ *
1087
+ * ```javascript
1088
+ * // Return search results for all documents
1089
+ * miniSearch.search(MiniSearch.wildcard)
1090
+ * ```
1091
+ *
1092
+ * Note that search options such as `filter` and `boostDocument` are still
1093
+ * applied, influencing which results are returned, and their order:
1094
+ *
1095
+ * ```javascript
1096
+ * // Return search results for all documents in the 'fiction' category
1097
+ * miniSearch.search(MiniSearch.wildcard, {
1098
+ * filter: (result) => result.category === 'fiction'
1099
+ * })
1100
+ * ```
1101
+ *
1102
+ * ### Advanced combination of queries:
1103
+ *
1104
+ * It is possible to combine different subqueries with OR, AND, and AND_NOT,
1105
+ * and even with different search options, by passing a query expression
1106
+ * tree object as the first argument, instead of a string.
1107
+ *
1108
+ * ```javascript
1109
+ * // Search for documents that contain "zen" and ("motorcycle" or "archery")
1110
+ * miniSearch.search({
1111
+ * combineWith: 'AND',
1112
+ * queries: [
1113
+ * 'zen',
1114
+ * {
1115
+ * combineWith: 'OR',
1116
+ * queries: ['motorcycle', 'archery']
1117
+ * }
1118
+ * ]
1119
+ * })
1120
+ *
1121
+ * // Search for documents that contain ("apple" or "pear") but not "juice" and
1122
+ * // not "tree"
1123
+ * miniSearch.search({
1124
+ * combineWith: 'AND_NOT',
1125
+ * queries: [
1126
+ * {
1127
+ * combineWith: 'OR',
1128
+ * queries: ['apple', 'pear']
1129
+ * },
1130
+ * 'juice',
1131
+ * 'tree'
1132
+ * ]
1133
+ * })
1134
+ * ```
1135
+ *
1136
+ * Each node in the expression tree can be either a string, or an object that
1137
+ * supports all {@link SearchOptions} fields, plus a `queries` array field for
1138
+ * subqueries.
1139
+ *
1140
+ * Note that, while this can become complicated to do by hand for complex or
1141
+ * deeply nested queries, it provides a formalized expression tree API for
1142
+ * external libraries that implement a parser for custom query languages.
1143
+ *
1144
+ * @param query Search query
1145
+ * @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.
1146
+ */
1147
+ search(query, searchOptions = {}) {
1148
+ const { searchOptions: globalSearchOptions } = this._options;
1149
+ const searchOptionsWithDefaults = { ...globalSearchOptions, ...searchOptions };
1150
+ const rawResults = this.executeQuery(query, searchOptions);
1151
+ const results = [];
1152
+ for (const [docId, { score, terms, match }] of rawResults) {
1153
+ const quality = terms.length || 1;
1154
+ const result = {
1155
+ id: this._documentIds.get(docId),
1156
+ score: score * quality,
1157
+ terms: Object.keys(match),
1158
+ queryTerms: terms,
1159
+ match
1160
+ };
1161
+ Object.assign(result, this._storedFields.get(docId));
1162
+ if (searchOptionsWithDefaults.filter == null || searchOptionsWithDefaults.filter(result)) {
1163
+ results.push(result);
1164
+ }
1165
+ }
1166
+ if (query === MiniSearch.wildcard && searchOptionsWithDefaults.boostDocument == null) {
1167
+ return results;
1168
+ }
1169
+ results.sort(byScore);
1170
+ return results;
1171
+ }
1172
+ /**
1173
+ * Provide suggestions for the given search query
1174
+ *
1175
+ * The result is a list of suggested modified search queries, derived from the
1176
+ * given search query, each with a relevance score, sorted by descending score.
1177
+ *
1178
+ * By default, it uses the same options used for search, except that by
1179
+ * default it performs prefix search on the last term of the query, and
1180
+ * combine terms with `'AND'` (requiring all query terms to match). Custom
1181
+ * options can be passed as a second argument. Defaults can be changed upon
1182
+ * calling the {@link MiniSearch} constructor, by passing a
1183
+ * `autoSuggestOptions` option.
1184
+ *
1185
+ * ### Basic usage:
1186
+ *
1187
+ * ```javascript
1188
+ * // Get suggestions for 'neuro':
1189
+ * miniSearch.autoSuggest('neuro')
1190
+ * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 0.46240 } ]
1191
+ * ```
1192
+ *
1193
+ * ### Multiple words:
1194
+ *
1195
+ * ```javascript
1196
+ * // Get suggestions for 'zen ar':
1197
+ * miniSearch.autoSuggest('zen ar')
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
+ * ### Fuzzy suggestions:
1205
+ *
1206
+ * ```javascript
1207
+ * // Correct spelling mistakes using fuzzy search:
1208
+ * miniSearch.autoSuggest('neromancer', { fuzzy: 0.2 })
1209
+ * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 1.03998 } ]
1210
+ * ```
1211
+ *
1212
+ * ### Filtering:
1213
+ *
1214
+ * ```javascript
1215
+ * // Get suggestions for 'zen ar', but only within the 'fiction' category
1216
+ * // (assuming that 'category' is a stored field):
1217
+ * miniSearch.autoSuggest('zen ar', {
1218
+ * filter: (result) => result.category === 'fiction'
1219
+ * })
1220
+ * // => [
1221
+ * // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 },
1222
+ * // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 }
1223
+ * // ]
1224
+ * ```
1225
+ *
1226
+ * @param queryString Query string to be expanded into suggestions
1227
+ * @param options Search options. The supported options and default values
1228
+ * are the same as for the {@link MiniSearch#search} method, except that by
1229
+ * default prefix search is performed on the last term in the query, and terms
1230
+ * are combined with `'AND'`.
1231
+ * @return A sorted array of suggestions sorted by relevance score.
1232
+ */
1233
+ autoSuggest(queryString, options = {}) {
1234
+ options = { ...this._options.autoSuggestOptions, ...options };
1235
+ const suggestions = /* @__PURE__ */ new Map();
1236
+ for (const { score, terms } of this.search(queryString, options)) {
1237
+ const phrase = terms.join(" ");
1238
+ const suggestion = suggestions.get(phrase);
1239
+ if (suggestion != null) {
1240
+ suggestion.score += score;
1241
+ suggestion.count += 1;
1242
+ } else {
1243
+ suggestions.set(phrase, { score, terms, count: 1 });
1244
+ }
1245
+ }
1246
+ const results = [];
1247
+ for (const [suggestion, { score, terms, count }] of suggestions) {
1248
+ results.push({ suggestion, terms, score: score / count });
1249
+ }
1250
+ results.sort(byScore);
1251
+ return results;
1252
+ }
1253
+ /**
1254
+ * Total number of documents available to search
1255
+ */
1256
+ get documentCount() {
1257
+ return this._documentCount;
1258
+ }
1259
+ /**
1260
+ * Number of terms in the index
1261
+ */
1262
+ get termCount() {
1263
+ return this._index.size;
1264
+ }
1265
+ /**
1266
+ * Deserializes a JSON index (serialized with `JSON.stringify(miniSearch)`)
1267
+ * and instantiates a MiniSearch instance. It should be given the same options
1268
+ * originally used when serializing the index.
1269
+ *
1270
+ * ### Usage:
1271
+ *
1272
+ * ```javascript
1273
+ * // If the index was serialized with:
1274
+ * let miniSearch = new MiniSearch({ fields: ['title', 'text'] })
1275
+ * miniSearch.addAll(documents)
1276
+ *
1277
+ * const json = JSON.stringify(miniSearch)
1278
+ * // It can later be deserialized like this:
1279
+ * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] })
1280
+ * ```
1281
+ *
1282
+ * @param json JSON-serialized index
1283
+ * @param options configuration options, same as the constructor
1284
+ * @return An instance of MiniSearch deserialized from the given JSON.
1285
+ */
1286
+ static loadJSON(json, options) {
1287
+ if (options == null) {
1288
+ throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");
1289
+ }
1290
+ return this.loadJS(JSON.parse(json), options);
1291
+ }
1292
+ /**
1293
+ * Async equivalent of {@link MiniSearch.loadJSON}
1294
+ *
1295
+ * This function is an alternative to {@link MiniSearch.loadJSON} that returns
1296
+ * a promise, and loads the index in batches, leaving pauses between them to avoid
1297
+ * blocking the main thread. It tends to be slower than the synchronous
1298
+ * version, but does not block the main thread, so it can be a better choice
1299
+ * when deserializing very large indexes.
1300
+ *
1301
+ * @param json JSON-serialized index
1302
+ * @param options configuration options, same as the constructor
1303
+ * @return A Promise that will resolve to an instance of MiniSearch deserialized from the given JSON.
1304
+ */
1305
+ static async loadJSONAsync(json, options) {
1306
+ if (options == null) {
1307
+ throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");
1308
+ }
1309
+ return this.loadJSAsync(JSON.parse(json), options);
1310
+ }
1311
+ /**
1312
+ * Returns the default value of an option. It will throw an error if no option
1313
+ * with the given name exists.
1314
+ *
1315
+ * @param optionName Name of the option
1316
+ * @return The default value of the given option
1317
+ *
1318
+ * ### Usage:
1319
+ *
1320
+ * ```javascript
1321
+ * // Get default tokenizer
1322
+ * MiniSearch.getDefault('tokenize')
1323
+ *
1324
+ * // Get default term processor
1325
+ * MiniSearch.getDefault('processTerm')
1326
+ *
1327
+ * // Unknown options will throw an error
1328
+ * MiniSearch.getDefault('notExisting')
1329
+ * // => throws 'MiniSearch: unknown option "notExisting"'
1330
+ * ```
1331
+ */
1332
+ static getDefault(optionName) {
1333
+ if (defaultOptions.hasOwnProperty(optionName)) {
1334
+ return getOwnProperty(defaultOptions, optionName);
1335
+ } else {
1336
+ throw new Error(`MiniSearch: unknown option "${optionName}"`);
1337
+ }
1338
+ }
1339
+ /**
1340
+ * @ignore
1341
+ */
1342
+ static loadJS(js, options) {
1343
+ const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
1344
+ const miniSearch = this.instantiateMiniSearch(js, options);
1345
+ miniSearch._documentIds = objectToNumericMap(documentIds);
1346
+ miniSearch._fieldLength = objectToNumericMap(fieldLength);
1347
+ miniSearch._storedFields = objectToNumericMap(storedFields);
1348
+ for (const [shortId, id] of miniSearch._documentIds) {
1349
+ miniSearch._idToShortId.set(id, shortId);
1350
+ }
1351
+ for (const [term, data] of index) {
1352
+ const dataMap = /* @__PURE__ */ new Map();
1353
+ for (const fieldId of Object.keys(data)) {
1354
+ let indexEntry = data[fieldId];
1355
+ if (serializationVersion === 1) {
1356
+ indexEntry = indexEntry.ds;
1357
+ }
1358
+ dataMap.set(parseInt(fieldId, 10), objectToNumericMap(indexEntry));
1359
+ }
1360
+ miniSearch._index.set(term, dataMap);
1361
+ }
1362
+ return miniSearch;
1363
+ }
1364
+ /**
1365
+ * @ignore
1366
+ */
1367
+ static async loadJSAsync(js, options) {
1368
+ const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
1369
+ const miniSearch = this.instantiateMiniSearch(js, options);
1370
+ miniSearch._documentIds = await objectToNumericMapAsync(documentIds);
1371
+ miniSearch._fieldLength = await objectToNumericMapAsync(fieldLength);
1372
+ miniSearch._storedFields = await objectToNumericMapAsync(storedFields);
1373
+ for (const [shortId, id] of miniSearch._documentIds) {
1374
+ miniSearch._idToShortId.set(id, shortId);
1375
+ }
1376
+ let count = 0;
1377
+ for (const [term, data] of index) {
1378
+ const dataMap = /* @__PURE__ */ new Map();
1379
+ for (const fieldId of Object.keys(data)) {
1380
+ let indexEntry = data[fieldId];
1381
+ if (serializationVersion === 1) {
1382
+ indexEntry = indexEntry.ds;
1383
+ }
1384
+ dataMap.set(parseInt(fieldId, 10), await objectToNumericMapAsync(indexEntry));
1385
+ }
1386
+ if (++count % 1e3 === 0)
1387
+ await wait(0);
1388
+ miniSearch._index.set(term, dataMap);
1389
+ }
1390
+ return miniSearch;
1391
+ }
1392
+ /**
1393
+ * @ignore
1394
+ */
1395
+ static instantiateMiniSearch(js, options) {
1396
+ const { documentCount, nextId, fieldIds, averageFieldLength, dirtCount, serializationVersion } = js;
1397
+ if (serializationVersion !== 1 && serializationVersion !== 2) {
1398
+ throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");
1399
+ }
1400
+ const miniSearch = new MiniSearch(options);
1401
+ miniSearch._documentCount = documentCount;
1402
+ miniSearch._nextId = nextId;
1403
+ miniSearch._idToShortId = /* @__PURE__ */ new Map();
1404
+ miniSearch._fieldIds = fieldIds;
1405
+ miniSearch._avgFieldLength = averageFieldLength;
1406
+ miniSearch._dirtCount = dirtCount || 0;
1407
+ miniSearch._index = new SearchableMap();
1408
+ return miniSearch;
1409
+ }
1410
+ /**
1411
+ * @ignore
1412
+ */
1413
+ executeQuery(query, searchOptions = {}) {
1414
+ if (query === MiniSearch.wildcard) {
1415
+ return this.executeWildcardQuery(searchOptions);
1416
+ }
1417
+ if (typeof query !== "string") {
1418
+ const options2 = { ...searchOptions, ...query, queries: void 0 };
1419
+ const results2 = query.queries.map((subquery) => this.executeQuery(subquery, options2));
1420
+ return this.combineResults(results2, options2.combineWith);
1421
+ }
1422
+ const { tokenize, processTerm, searchOptions: globalSearchOptions } = this._options;
1423
+ const options = { tokenize, processTerm, ...globalSearchOptions, ...searchOptions };
1424
+ const { tokenize: searchTokenize, processTerm: searchProcessTerm } = options;
1425
+ const terms = searchTokenize(query).flatMap((term) => searchProcessTerm(term)).filter((term) => !!term);
1426
+ const queries = terms.map(termToQuerySpec(options));
1427
+ const results = queries.map((query2) => this.executeQuerySpec(query2, options));
1428
+ return this.combineResults(results, options.combineWith);
1429
+ }
1430
+ /**
1431
+ * @ignore
1432
+ */
1433
+ executeQuerySpec(query, searchOptions) {
1434
+ const options = { ...this._options.searchOptions, ...searchOptions };
1435
+ const boosts = (options.fields || this._options.fields).reduce((boosts2, field) => ({ ...boosts2, [field]: getOwnProperty(options.boost, field) || 1 }), {});
1436
+ const { boostDocument, weights, maxFuzzy, bm25: bm25params } = options;
1437
+ const { fuzzy: fuzzyWeight, prefix: prefixWeight } = { ...defaultSearchOptions.weights, ...weights };
1438
+ const data = this._index.get(query.term);
1439
+ const results = this.termResults(query.term, query.term, 1, query.termBoost, data, boosts, boostDocument, bm25params);
1440
+ let prefixMatches;
1441
+ let fuzzyMatches;
1442
+ if (query.prefix) {
1443
+ prefixMatches = this._index.atPrefix(query.term);
1444
+ }
1445
+ if (query.fuzzy) {
1446
+ const fuzzy = query.fuzzy === true ? 0.2 : query.fuzzy;
1447
+ const maxDistance = fuzzy < 1 ? Math.min(maxFuzzy, Math.round(query.term.length * fuzzy)) : fuzzy;
1448
+ if (maxDistance)
1449
+ fuzzyMatches = this._index.fuzzyGet(query.term, maxDistance);
1450
+ }
1451
+ if (prefixMatches) {
1452
+ for (const [term, data2] of prefixMatches) {
1453
+ const distance = term.length - query.term.length;
1454
+ if (!distance) {
1455
+ continue;
1456
+ }
1457
+ fuzzyMatches === null || fuzzyMatches === void 0 ? void 0 : fuzzyMatches.delete(term);
1458
+ const weight = prefixWeight * term.length / (term.length + 0.3 * distance);
1459
+ this.termResults(query.term, term, weight, query.termBoost, data2, boosts, boostDocument, bm25params, results);
1460
+ }
1461
+ }
1462
+ if (fuzzyMatches) {
1463
+ for (const term of fuzzyMatches.keys()) {
1464
+ const [data2, distance] = fuzzyMatches.get(term);
1465
+ if (!distance) {
1466
+ continue;
1467
+ }
1468
+ const weight = fuzzyWeight * term.length / (term.length + distance);
1469
+ this.termResults(query.term, term, weight, query.termBoost, data2, boosts, boostDocument, bm25params, results);
1470
+ }
1471
+ }
1472
+ return results;
1473
+ }
1474
+ /**
1475
+ * @ignore
1476
+ */
1477
+ executeWildcardQuery(searchOptions) {
1478
+ const results = /* @__PURE__ */ new Map();
1479
+ const options = { ...this._options.searchOptions, ...searchOptions };
1480
+ for (const [shortId, id] of this._documentIds) {
1481
+ const score = options.boostDocument ? options.boostDocument(id, "", this._storedFields.get(shortId)) : 1;
1482
+ results.set(shortId, {
1483
+ score,
1484
+ terms: [],
1485
+ match: {}
1486
+ });
1487
+ }
1488
+ return results;
1489
+ }
1490
+ /**
1491
+ * @ignore
1492
+ */
1493
+ combineResults(results, combineWith = OR) {
1494
+ if (results.length === 0) {
1495
+ return /* @__PURE__ */ new Map();
1496
+ }
1497
+ const operator = combineWith.toLowerCase();
1498
+ const combinator = combinators[operator];
1499
+ if (!combinator) {
1500
+ throw new Error(`Invalid combination operator: ${combineWith}`);
1501
+ }
1502
+ return results.reduce(combinator) || /* @__PURE__ */ new Map();
1503
+ }
1504
+ /**
1505
+ * Allows serialization of the index to JSON, to possibly store it and later
1506
+ * deserialize it with {@link MiniSearch.loadJSON}.
1507
+ *
1508
+ * Normally one does not directly call this method, but rather call the
1509
+ * standard JavaScript `JSON.stringify()` passing the {@link MiniSearch}
1510
+ * instance, and JavaScript will internally call this method. Upon
1511
+ * deserialization, one must pass to {@link MiniSearch.loadJSON} the same
1512
+ * options used to create the original instance that was serialized.
1513
+ *
1514
+ * ### Usage:
1515
+ *
1516
+ * ```javascript
1517
+ * // Serialize the index:
1518
+ * let miniSearch = new MiniSearch({ fields: ['title', 'text'] })
1519
+ * miniSearch.addAll(documents)
1520
+ * const json = JSON.stringify(miniSearch)
1521
+ *
1522
+ * // Later, to deserialize it:
1523
+ * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] })
1524
+ * ```
1525
+ *
1526
+ * @return A plain-object serializable representation of the search index.
1527
+ */
1528
+ toJSON() {
1529
+ const index = [];
1530
+ for (const [term, fieldIndex] of this._index) {
1531
+ const data = {};
1532
+ for (const [fieldId, freqs] of fieldIndex) {
1533
+ data[fieldId] = Object.fromEntries(freqs);
1534
+ }
1535
+ index.push([term, data]);
1536
+ }
1537
+ return {
1538
+ documentCount: this._documentCount,
1539
+ nextId: this._nextId,
1540
+ documentIds: Object.fromEntries(this._documentIds),
1541
+ fieldIds: this._fieldIds,
1542
+ fieldLength: Object.fromEntries(this._fieldLength),
1543
+ averageFieldLength: this._avgFieldLength,
1544
+ storedFields: Object.fromEntries(this._storedFields),
1545
+ dirtCount: this._dirtCount,
1546
+ index,
1547
+ serializationVersion: 2
1548
+ };
1549
+ }
1550
+ /**
1551
+ * @ignore
1552
+ */
1553
+ termResults(sourceTerm, derivedTerm, termWeight, termBoost, fieldTermData, fieldBoosts, boostDocumentFn, bm25params, results = /* @__PURE__ */ new Map()) {
1554
+ if (fieldTermData == null)
1555
+ return results;
1556
+ for (const field of Object.keys(fieldBoosts)) {
1557
+ const fieldBoost = fieldBoosts[field];
1558
+ const fieldId = this._fieldIds[field];
1559
+ const fieldTermFreqs = fieldTermData.get(fieldId);
1560
+ if (fieldTermFreqs == null)
1561
+ continue;
1562
+ let matchingFields = fieldTermFreqs.size;
1563
+ const avgFieldLength = this._avgFieldLength[fieldId];
1564
+ for (const docId of fieldTermFreqs.keys()) {
1565
+ if (!this._documentIds.has(docId)) {
1566
+ this.removeTerm(fieldId, docId, derivedTerm);
1567
+ matchingFields -= 1;
1568
+ continue;
1569
+ }
1570
+ const docBoost = boostDocumentFn ? boostDocumentFn(this._documentIds.get(docId), derivedTerm, this._storedFields.get(docId)) : 1;
1571
+ if (!docBoost)
1572
+ continue;
1573
+ const termFreq = fieldTermFreqs.get(docId);
1574
+ const fieldLength = this._fieldLength.get(docId)[fieldId];
1575
+ const rawScore = calcBM25Score(termFreq, matchingFields, this._documentCount, fieldLength, avgFieldLength, bm25params);
1576
+ const weightedScore = termWeight * termBoost * fieldBoost * docBoost * rawScore;
1577
+ const result = results.get(docId);
1578
+ if (result) {
1579
+ result.score += weightedScore;
1580
+ assignUniqueTerm(result.terms, sourceTerm);
1581
+ const match = getOwnProperty(result.match, derivedTerm);
1582
+ if (match) {
1583
+ match.push(field);
1584
+ } else {
1585
+ result.match[derivedTerm] = [field];
1586
+ }
1587
+ } else {
1588
+ results.set(docId, {
1589
+ score: weightedScore,
1590
+ terms: [sourceTerm],
1591
+ match: { [derivedTerm]: [field] }
1592
+ });
1593
+ }
1594
+ }
1595
+ }
1596
+ return results;
1597
+ }
1598
+ /**
1599
+ * @ignore
1600
+ */
1601
+ addTerm(fieldId, documentId, term) {
1602
+ const indexData = this._index.fetch(term, createMap);
1603
+ let fieldIndex = indexData.get(fieldId);
1604
+ if (fieldIndex == null) {
1605
+ fieldIndex = /* @__PURE__ */ new Map();
1606
+ fieldIndex.set(documentId, 1);
1607
+ indexData.set(fieldId, fieldIndex);
1608
+ } else {
1609
+ const docs = fieldIndex.get(documentId);
1610
+ fieldIndex.set(documentId, (docs || 0) + 1);
1611
+ }
1612
+ }
1613
+ /**
1614
+ * @ignore
1615
+ */
1616
+ removeTerm(fieldId, documentId, term) {
1617
+ if (!this._index.has(term)) {
1618
+ this.warnDocumentChanged(documentId, fieldId, term);
1619
+ return;
1620
+ }
1621
+ const indexData = this._index.fetch(term, createMap);
1622
+ const fieldIndex = indexData.get(fieldId);
1623
+ if (fieldIndex == null || fieldIndex.get(documentId) == null) {
1624
+ this.warnDocumentChanged(documentId, fieldId, term);
1625
+ } else if (fieldIndex.get(documentId) <= 1) {
1626
+ if (fieldIndex.size <= 1) {
1627
+ indexData.delete(fieldId);
1628
+ } else {
1629
+ fieldIndex.delete(documentId);
1630
+ }
1631
+ } else {
1632
+ fieldIndex.set(documentId, fieldIndex.get(documentId) - 1);
1633
+ }
1634
+ if (this._index.get(term).size === 0) {
1635
+ this._index.delete(term);
1636
+ }
1637
+ }
1638
+ /**
1639
+ * @ignore
1640
+ */
1641
+ warnDocumentChanged(shortDocumentId, fieldId, term) {
1642
+ for (const fieldName of Object.keys(this._fieldIds)) {
1643
+ if (this._fieldIds[fieldName] === fieldId) {
1644
+ 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");
1645
+ return;
1646
+ }
1647
+ }
1648
+ }
1649
+ /**
1650
+ * @ignore
1651
+ */
1652
+ addDocumentId(documentId) {
1653
+ const shortDocumentId = this._nextId;
1654
+ this._idToShortId.set(documentId, shortDocumentId);
1655
+ this._documentIds.set(shortDocumentId, documentId);
1656
+ this._documentCount += 1;
1657
+ this._nextId += 1;
1658
+ return shortDocumentId;
1659
+ }
1660
+ /**
1661
+ * @ignore
1662
+ */
1663
+ addFields(fields) {
1664
+ for (let i = 0; i < fields.length; i++) {
1665
+ this._fieldIds[fields[i]] = i;
1666
+ }
1667
+ }
1668
+ /**
1669
+ * @ignore
1670
+ */
1671
+ addFieldLength(documentId, fieldId, count, length) {
1672
+ let fieldLengths = this._fieldLength.get(documentId);
1673
+ if (fieldLengths == null)
1674
+ this._fieldLength.set(documentId, fieldLengths = []);
1675
+ fieldLengths[fieldId] = length;
1676
+ const averageFieldLength = this._avgFieldLength[fieldId] || 0;
1677
+ const totalFieldLength = averageFieldLength * count + length;
1678
+ this._avgFieldLength[fieldId] = totalFieldLength / (count + 1);
1679
+ }
1680
+ /**
1681
+ * @ignore
1682
+ */
1683
+ removeFieldLength(documentId, fieldId, count, length) {
1684
+ if (count === 1) {
1685
+ this._avgFieldLength[fieldId] = 0;
1686
+ return;
1687
+ }
1688
+ const totalFieldLength = this._avgFieldLength[fieldId] * count - length;
1689
+ this._avgFieldLength[fieldId] = totalFieldLength / (count - 1);
1690
+ }
1691
+ /**
1692
+ * @ignore
1693
+ */
1694
+ saveStoredFields(documentId, doc) {
1695
+ const { storeFields, extractField } = this._options;
1696
+ if (storeFields == null || storeFields.length === 0) {
1697
+ return;
1698
+ }
1699
+ let documentFields = this._storedFields.get(documentId);
1700
+ if (documentFields == null)
1701
+ this._storedFields.set(documentId, documentFields = {});
1702
+ for (const fieldName of storeFields) {
1703
+ const fieldValue = extractField(doc, fieldName);
1704
+ if (fieldValue !== void 0)
1705
+ documentFields[fieldName] = fieldValue;
1706
+ }
1707
+ }
1708
+ }
1709
+ MiniSearch.wildcard = Symbol("*");
1710
+ const getOwnProperty = (object, property) => Object.prototype.hasOwnProperty.call(object, property) ? object[property] : void 0;
1711
+ const combinators = {
1712
+ [OR]: (a, b) => {
1713
+ for (const docId of b.keys()) {
1714
+ const existing = a.get(docId);
1715
+ if (existing == null) {
1716
+ a.set(docId, b.get(docId));
1717
+ } else {
1718
+ const { score, terms, match } = b.get(docId);
1719
+ existing.score = existing.score + score;
1720
+ existing.match = Object.assign(existing.match, match);
1721
+ assignUniqueTerms(existing.terms, terms);
1722
+ }
1723
+ }
1724
+ return a;
1725
+ },
1726
+ [AND]: (a, b) => {
1727
+ const combined = /* @__PURE__ */ new Map();
1728
+ for (const docId of b.keys()) {
1729
+ const existing = a.get(docId);
1730
+ if (existing == null)
1731
+ continue;
1732
+ const { score, terms, match } = b.get(docId);
1733
+ assignUniqueTerms(existing.terms, terms);
1734
+ combined.set(docId, {
1735
+ score: existing.score + score,
1736
+ terms: existing.terms,
1737
+ match: Object.assign(existing.match, match)
1738
+ });
1739
+ }
1740
+ return combined;
1741
+ },
1742
+ [AND_NOT]: (a, b) => {
1743
+ for (const docId of b.keys())
1744
+ a.delete(docId);
1745
+ return a;
1746
+ }
1747
+ };
1748
+ const defaultBM25params = { k: 1.2, b: 0.7, d: 0.5 };
1749
+ const calcBM25Score = (termFreq, matchingCount, totalCount, fieldLength, avgFieldLength, bm25params) => {
1750
+ const { k, b, d } = bm25params;
1751
+ const invDocFreq = Math.log(1 + (totalCount - matchingCount + 0.5) / (matchingCount + 0.5));
1752
+ return invDocFreq * (d + termFreq * (k + 1) / (termFreq + k * (1 - b + b * fieldLength / avgFieldLength)));
1753
+ };
1754
+ const termToQuerySpec = (options) => (term, i, terms) => {
1755
+ const fuzzy = typeof options.fuzzy === "function" ? options.fuzzy(term, i, terms) : options.fuzzy || false;
1756
+ const prefix = typeof options.prefix === "function" ? options.prefix(term, i, terms) : options.prefix === true;
1757
+ const termBoost = typeof options.boostTerm === "function" ? options.boostTerm(term, i, terms) : 1;
1758
+ return { term, fuzzy, prefix, termBoost };
1759
+ };
1760
+ const defaultOptions = {
1761
+ idField: "id",
1762
+ extractField: (document, fieldName) => document[fieldName],
1763
+ stringifyField: (fieldValue, fieldName) => fieldValue.toString(),
1764
+ tokenize: (text) => text.split(SPACE_OR_PUNCTUATION),
1765
+ processTerm: (term) => term.toLowerCase(),
1766
+ fields: void 0,
1767
+ searchOptions: void 0,
1768
+ storeFields: [],
1769
+ logger: (level, message) => {
1770
+ if (typeof (console === null || console === void 0 ? void 0 : console[level]) === "function")
1771
+ console[level](message);
1772
+ },
1773
+ autoVacuum: true
1774
+ };
1775
+ const defaultSearchOptions = {
1776
+ combineWith: OR,
1777
+ prefix: false,
1778
+ fuzzy: false,
1779
+ maxFuzzy: 6,
1780
+ boost: {},
1781
+ weights: { fuzzy: 0.45, prefix: 0.375 },
1782
+ bm25: defaultBM25params
1783
+ };
1784
+ const defaultAutoSuggestOptions = {
1785
+ combineWith: AND,
1786
+ prefix: (term, i, terms) => i === terms.length - 1
1787
+ };
1788
+ const defaultVacuumOptions = { batchSize: 1e3, batchWait: 10 };
1789
+ const defaultVacuumConditions = { minDirtFactor: 0.1, minDirtCount: 20 };
1790
+ const defaultAutoVacuumOptions = { ...defaultVacuumOptions, ...defaultVacuumConditions };
1791
+ const assignUniqueTerm = (target, term) => {
1792
+ if (!target.includes(term))
1793
+ target.push(term);
1794
+ };
1795
+ const assignUniqueTerms = (target, source) => {
1796
+ for (const term of source) {
1797
+ if (!target.includes(term))
1798
+ target.push(term);
1799
+ }
1800
+ };
1801
+ const byScore = ({ score: a }, { score: b }) => b - a;
1802
+ const createMap = () => /* @__PURE__ */ new Map();
1803
+ const objectToNumericMap = (object) => {
1804
+ const map = /* @__PURE__ */ new Map();
1805
+ for (const key of Object.keys(object)) {
1806
+ map.set(parseInt(key, 10), object[key]);
1807
+ }
1808
+ return map;
1809
+ };
1810
+ const objectToNumericMapAsync = async (object) => {
1811
+ const map = /* @__PURE__ */ new Map();
1812
+ let count = 0;
1813
+ for (const key of Object.keys(object)) {
1814
+ map.set(parseInt(key, 10), object[key]);
1815
+ if (++count % 1e3 === 0) {
1816
+ await wait(0);
1817
+ }
1818
+ }
1819
+ return map;
1820
+ };
1821
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1822
+ const SPACE_OR_PUNCTUATION = /[\n\r\p{Z}\p{P}]+/u;
1823
+ const TEXT_TYPES = /* @__PURE__ */ new Set(["text", "email", "phone", "url", "tags", "select", "multiSelect"]);
1824
+ function recordDoc(object, r) {
1825
+ const f = r.fields;
1826
+ const email = typeof f.email === "string" ? f.email : "";
1827
+ const domainRaw = typeof f.domain === "string" ? f.domain : "";
1828
+ const phone = typeof f.phone === "string" ? f.phone : "";
1829
+ const extra = [];
1830
+ for (const field of object?.fields ?? []) {
1831
+ if (!TEXT_TYPES.has(field.type)) continue;
1832
+ const v = f[field.id];
1833
+ if (field.type === "select") {
1834
+ const o = field.options?.find((x) => x.id === v);
1835
+ if (o) extra.push(o.label);
1836
+ } else if (Array.isArray(v)) extra.push(...v.map(String));
1837
+ else if (typeof v === "string") extra.push(v);
1838
+ }
1839
+ const domain = normalizeDomain(domainRaw);
1840
+ return {
1841
+ key: `r:${r.id}`,
1842
+ kind: "record",
1843
+ id: r.id,
1844
+ object: r.object,
1845
+ label: recordLabel(object, r),
1846
+ email,
1847
+ // "acme.com" + "acme" so a search for the brand finds the domain.
1848
+ domain: domain ? `${domain} ${domain.split(".")[0]}` : "",
1849
+ phone: phone.replace(/[^\d+]/g, ""),
1850
+ text: extra.join(" "),
1851
+ sub: email || domain || "",
1852
+ deleted: !!r.deletedAt
1853
+ };
1854
+ }
1855
+ function activityDoc(a) {
1856
+ return {
1857
+ key: `a:${a.id}`,
1858
+ kind: "activity",
1859
+ id: a.id,
1860
+ object: "activities",
1861
+ label: a.title,
1862
+ email: "",
1863
+ domain: "",
1864
+ phone: "",
1865
+ text: (a.body ?? "").slice(0, 500),
1866
+ sub: a.type,
1867
+ deleted: !!a.deletedAt
1868
+ };
1869
+ }
1870
+ function buildSearchIndex(input) {
1871
+ const objects = new Map(input.objects.map((o) => [o.id, o]));
1872
+ const mini = new MiniSearch({
1873
+ idField: "key",
1874
+ fields: ["label", "email", "domain", "phone", "text"],
1875
+ storeFields: ["kind", "id", "object", "label", "sub", "deleted"],
1876
+ searchOptions: {
1877
+ boost: { label: 3, email: 2, domain: 2, phone: 1.5, text: 0.5 },
1878
+ prefix: true,
1879
+ fuzzy: (term) => term.length > 3 ? 0.2 : false,
1880
+ combineWith: "AND"
1881
+ },
1882
+ // Accent-insensitive.
1883
+ processTerm: (term) => term.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase()
1884
+ });
1885
+ mini.addAll([...input.records.map((r) => recordDoc(objects.get(r.object), r)), ...(input.activities ?? []).map(activityDoc)]);
1886
+ function upsert(doc) {
1887
+ if (mini.has(doc.key)) mini.replace(doc);
1888
+ else mini.add(doc);
1889
+ }
1890
+ return {
1891
+ get size() {
1892
+ return mini.documentCount;
1893
+ },
1894
+ search(query, opts = {}) {
1895
+ const q = query.trim();
1896
+ if (!q) return [];
1897
+ const phoneDigits = q.replace(/[^\d+]/g, "");
1898
+ const queryText = /^[+\d\s().-]{4,}$/.test(q) ? phoneDigits : q;
1899
+ const results = mini.search(queryText, {
1900
+ filter: (r) => (opts.includeDeleted || !r.deleted) && (!opts.objects || opts.objects.includes(r.object))
1901
+ });
1902
+ return results.slice(0, opts.limit ?? 20).map((r) => ({
1903
+ kind: r.kind,
1904
+ id: r.id,
1905
+ object: r.object,
1906
+ label: r.label,
1907
+ sub: r.sub || void 0,
1908
+ score: r.score
1909
+ }));
1910
+ },
1911
+ upsertRecord(record) {
1912
+ upsert(recordDoc(objects.get(record.object), record));
1913
+ },
1914
+ removeRecord(id) {
1915
+ if (mini.has(`r:${id}`)) mini.discard(`r:${id}`);
1916
+ },
1917
+ upsertActivity(activity) {
1918
+ upsert(activityDoc(activity));
1919
+ },
1920
+ removeActivity(id) {
1921
+ if (mini.has(`a:${id}`)) mini.discard(`a:${id}`);
1922
+ }
1923
+ };
1924
+ }
1925
+ function queryContext(ctx, object) {
1926
+ return {
1927
+ object,
1928
+ now: ctx.now(),
1929
+ recordLabel: (_o, id) => labelOf(ctx, id),
1930
+ userName: (id) => userOf(ctx.store, id)?.name
1931
+ };
1932
+ }
1933
+ function listRecords(ctx, objectId, opts = {}) {
1934
+ assertCan(ctx, "records.read");
1935
+ const object = requireObject(ctx.store, objectId);
1936
+ let filters = opts.filters ?? [];
1937
+ let sorts = opts.sorts ?? [];
1938
+ if (opts.viewId) {
1939
+ const view = ctx.store.get("views", opts.viewId);
1940
+ if (!view || view.object !== objectId) throw new OpsError("notFound", `View "${opts.viewId}" not found on ${object.labelPlural}.`);
1941
+ filters = [...view.filters, ...filters];
1942
+ if (!opts.sorts?.length) sorts = view.sorts;
1943
+ }
1944
+ let records = recordsOf(ctx.store, objectId, { includeDeleted: opts.includeDeleted || opts.onlyDeleted });
1945
+ if (opts.onlyDeleted) records = records.filter((r) => r.deletedAt);
1946
+ if (opts.ownerId) records = records.filter((r) => r.ownerId === opts.ownerId);
1947
+ const qctx = queryContext(ctx, object);
1948
+ records = applyFilters(records, filters, qctx);
1949
+ if (opts.search?.trim()) {
1950
+ const index = buildSearchIndex({ objects: objectsOf(ctx.store), records });
1951
+ const hits = index.search(opts.search, { objects: [objectId], limit: records.length, includeDeleted: true });
1952
+ const byId = new Map(records.map((r) => [r.id, r]));
1953
+ records = hits.map((h) => byId.get(h.id)).filter((r) => !!r);
1954
+ if (sorts.length && opts.sorts?.length) records = applySorts(records, sorts, qctx);
1955
+ } else {
1956
+ records = applySorts(records, sorts.length ? sorts : [{ field: "createdAt", dir: "desc" }], qctx);
1957
+ }
1958
+ return paginate(records, { offset: opts.offset, limit: opts.limit });
1959
+ }
1960
+ function getRecord(ctx, id, opts = {}) {
1961
+ assertCan(ctx, "records.read");
1962
+ return requireRecord(ctx.store, id, opts);
1963
+ }
1964
+ function getRecordDetails(ctx, id) {
1965
+ assertCan(ctx, "records.read");
1966
+ const record = requireRecord(ctx.store, id, { includeDeleted: true });
1967
+ const object = requireObject(ctx.store, record.object);
1968
+ return {
1969
+ record,
1970
+ label: recordLabel(object, record),
1971
+ object: { id: object.id, labelSingular: object.labelSingular, labelPlural: object.labelPlural },
1972
+ relations: expandRelations(ctx, record),
1973
+ inverse: inverseRelations(ctx, record),
1974
+ activityCount: activitiesOf(ctx.store).filter((a) => a.targets.some((t) => t.id === id)).length
1975
+ };
1976
+ }
1977
+ function searchRecords(ctx, query, opts = {}) {
1978
+ assertCan(ctx, "records.read");
1979
+ const index = buildSearchIndex({ objects: objectsOf(ctx.store), records: recordsOf(ctx.store), activities: activitiesOf(ctx.store) });
1980
+ return index.search(query, { objects: opts.objects, limit: opts.limit ?? 20 });
1981
+ }
1982
+ function sameValue(a, b) {
1983
+ return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
1984
+ }
1985
+ function uniqueKey(type, value) {
1986
+ if (type === "email") return normalizeEmail(value);
1987
+ if (type === "url") return normalizeDomain(value) || String(value).toLowerCase();
1988
+ return typeof value === "string" ? value.trim().toLowerCase() : JSON.stringify(value);
1989
+ }
1990
+ function prepareRecordFields(ctx, object, input, previous, opts = {}) {
1991
+ const res = validateRecordFields(object, input, { partial: !!previous, unknownFields: opts.unknownFields, dayFirst: opts.dayFirst });
1992
+ const errors = [...res.errors];
1993
+ let merged = previous ? { ...previous.fields } : { ...defaultFieldValues(object) };
1994
+ for (const [k, v] of Object.entries(res.values)) {
1995
+ if (v === void 0) delete merged[k];
1996
+ else merged[k] = v;
1997
+ }
1998
+ merged = normalizeStandardFields(object.id, merged, previous?.fields ?? null);
1999
+ let stageChange = null;
2000
+ for (const pipeline of pipelinesOf(ctx.store, object.id)) {
2001
+ const stageField = pipeline.stageField;
2002
+ const prevStage = previous?.fields[stageField] ?? null;
2003
+ const stage = merged[stageField];
2004
+ const hasPipelineField = object.fields.some((f) => f.id === "pipeline");
2005
+ const pipelineOfRecord = hasPipelineField ? merged.pipeline : pipeline.id;
2006
+ const stageInThis = stage ? pipeline.stages.find((s) => s.id === stage) : void 0;
2007
+ if (stageInThis) {
2008
+ if (hasPipelineField && pipelineOfRecord !== pipeline.id) merged.pipeline = pipeline.id;
2009
+ if (stage !== prevStage) {
2010
+ stageChange = { pipelineId: pipeline.id, from: prevStage, to: stage };
2011
+ if (object.fields.some((f) => f.id === "probability") && !Object.prototype.hasOwnProperty.call(input, "probability")) {
2012
+ merged.probability = stageInThis.probability;
2013
+ }
2014
+ }
2015
+ } else if (hasPipelineField && pipelineOfRecord === pipeline.id && !stage && pipeline.stages[0]) {
2016
+ merged[stageField] = pipeline.stages[0].id;
2017
+ if (object.fields.some((f) => f.id === "probability") && merged.probability === void 0) merged.probability = pipeline.stages[0].probability;
2018
+ stageChange = { pipelineId: pipeline.id, from: prevStage, to: pipeline.stages[0].id };
2019
+ }
2020
+ }
2021
+ const others = recordsOf(ctx.store, object.id).filter((r) => r.id !== previous?.id);
2022
+ for (const field of object.fields) {
2023
+ const value = merged[field.id];
2024
+ const touched = !previous || Object.prototype.hasOwnProperty.call(res.values, field.id) || !sameValue(value, previous.fields[field.id]);
2025
+ if (!touched || isEmptyFieldValue(field, value)) continue;
2026
+ if (field.type === "relation") {
2027
+ const err = validateRelationValue(ctx, field, value);
2028
+ if (err) errors.push({ field: field.id, code: "invalidRelation", message: err });
2029
+ } else if (field.type === "user") {
2030
+ if (!userOf(ctx.store, String(value))) errors.push({ field: field.id, code: "invalidUser", message: `${field.label}: unknown user "${value}".` });
2031
+ }
2032
+ if (field.unique) {
2033
+ const key = uniqueKey(field.type, value);
2034
+ const clash = others.find((r) => !isEmptyFieldValue(field, r.fields[field.id]) && uniqueKey(field.type, r.fields[field.id]) === key);
2035
+ if (clash) {
2036
+ errors.push({
2037
+ field: field.id,
2038
+ code: "notUnique",
2039
+ message: `${field.label} "${String(value)}" is already used by ${recordLabel(object, clash)} (${clash.id}).`
2040
+ });
2041
+ }
2042
+ }
2043
+ }
2044
+ if (errors.length) throw new OpsError("validation", new FieldValidationError(errors).message, errors);
2045
+ const changed = previous ? [.../* @__PURE__ */ new Set([...Object.keys(merged), ...Object.keys(previous.fields)])].filter((k) => !sameValue(merged[k], previous.fields[k])) : Object.keys(merged);
2046
+ return { fields: merged, changed, stageChange };
2047
+ }
2048
+ function checkOwner(ctx, ownerId) {
2049
+ if (ownerId && !userOf(ctx.store, ownerId)) throw new OpsError("validation", `Unknown owner "${ownerId}".`);
2050
+ }
2051
+ async function createRecord(ctx, objectId, input, opts = {}) {
2052
+ assertCan(ctx, "records.write");
2053
+ const object = requireObject(ctx.store, objectId);
2054
+ const prepared = prepareRecordFields(ctx, object, input, null, opts);
2055
+ const now = ctx.now();
2056
+ const ownerId = opts.ownerId === void 0 ? actorId(ctx) : opts.ownerId ?? void 0;
2057
+ checkOwner(ctx, ownerId);
2058
+ const id = opts.id ?? newId(now);
2059
+ if (recordOf(ctx.store, id)) throw new OpsError("conflict", `Record "${id}" already exists.`);
2060
+ const record = {
2061
+ id,
2062
+ object: object.id,
2063
+ fields: prepared.fields,
2064
+ ...ownerId ? { ownerId } : {},
2065
+ createdAt: now,
2066
+ updatedAt: now,
2067
+ ...actorId(ctx) ? { createdBy: actorId(ctx), updatedBy: actorId(ctx) } : {}
2068
+ };
2069
+ await ctx.store.write([{ op: "set", collection: "records", doc: asDoc(record) }], { message: opts.message ?? `Create ${object.labelSingular}` });
2070
+ const stored = requireRecord(ctx.store, id);
2071
+ if (!opts.silent) {
2072
+ await emit(ctx, "record.created", { record: stored });
2073
+ if (prepared.stageChange) await emit(ctx, "stage.changed", { record: stored, ...prepared.stageChange, from: null });
2074
+ }
2075
+ return stored;
2076
+ }
2077
+ function recordPatchMutation(ctx, previous, fields, changed, extra = {}) {
2078
+ const patch = { updatedAt: ctx.now(), ...extra };
2079
+ if (actorId(ctx)) patch.updatedBy = actorId(ctx);
2080
+ for (const k of changed) patch[`fields.${k}`] = fields[k];
2081
+ return { op: "patch", collection: "records", id: previous.id, fields: patch };
2082
+ }
2083
+ async function updateRecord(ctx, id, input, opts = {}) {
2084
+ assertCan(ctx, "records.write");
2085
+ const before = requireRecord(ctx.store, id);
2086
+ const object = requireObject(ctx.store, before.object);
2087
+ const prepared = prepareRecordFields(ctx, object, input, before, opts);
2088
+ const extra = {};
2089
+ if (opts.ownerId !== void 0 && opts.ownerId !== before.ownerId) {
2090
+ checkOwner(ctx, opts.ownerId);
2091
+ extra.ownerId = opts.ownerId ?? void 0;
2092
+ }
2093
+ if (!prepared.changed.length && !Object.keys(extra).length) return before;
2094
+ await ctx.store.write([recordPatchMutation(ctx, before, prepared.fields, prepared.changed, extra)], { message: opts.message ?? `Update ${object.labelSingular}` });
2095
+ const record = requireRecord(ctx.store, id);
2096
+ if (!opts.silent) {
2097
+ await emit(ctx, "record.updated", { record, before, changed: [...prepared.changed, ...Object.keys(extra)] });
2098
+ if (prepared.stageChange) await emit(ctx, "stage.changed", { record, ...prepared.stageChange });
2099
+ }
2100
+ return record;
2101
+ }
2102
+ async function setRecordOwner(ctx, id, ownerId) {
2103
+ return updateRecord(ctx, id, {}, { ownerId });
2104
+ }
2105
+ async function deleteRecord(ctx, id, opts = {}) {
2106
+ assertCan(ctx, "records.delete");
2107
+ const record = requireRecord(ctx.store, id, { includeDeleted: opts.hard });
2108
+ const object = objectsOf(ctx.store).find((o) => o.id === record.object);
2109
+ const mutations = opts.hard ? hardDeleteMutations(ctx, [id]) : [{ op: "patch", collection: "records", id, fields: { deletedAt: ctx.now(), updatedAt: ctx.now(), ...actorId(ctx) ? { updatedBy: actorId(ctx) } : {} } }];
2110
+ await ctx.store.write(mutations, { message: `Delete ${object?.labelSingular ?? "record"}` });
2111
+ if (!opts.silent) await emit(ctx, "record.deleted", { record, hard: !!opts.hard });
2112
+ return { id, hard: !!opts.hard };
2113
+ }
2114
+ function hardDeleteMutations(ctx, ids) {
2115
+ const doomed = new Set(ids);
2116
+ const out = ids.map((id) => ({ op: "delete", collection: "records", id }));
2117
+ out.push(...rewriteReferences(ctx, ids, null));
2118
+ const doomedActivities = [];
2119
+ for (const a of activitiesOf(ctx.store, { includeDeleted: true })) {
2120
+ if (!a.targets.some((t) => doomed.has(t.id))) continue;
2121
+ const rest = a.targets.filter((t) => !doomed.has(t.id));
2122
+ if (rest.length === 0) {
2123
+ out.push({ op: "delete", collection: "activities", id: a.id });
2124
+ doomedActivities.push(a.id);
2125
+ } else out.push({ op: "patch", collection: "activities", id: a.id, fields: { targets: rest, updatedAt: ctx.now() } });
2126
+ }
2127
+ out.push(...fileCleanupMutations(ctx, { records: ids, activities: doomedActivities }));
2128
+ return out;
2129
+ }
2130
+ async function restoreRecord(ctx, id) {
2131
+ assertCan(ctx, "records.write");
2132
+ const record = requireRecord(ctx.store, id, { includeDeleted: true });
2133
+ if (!record.deletedAt) return record;
2134
+ await ctx.store.write([{ op: "patch", collection: "records", id, fields: { deletedAt: void 0, updatedAt: ctx.now() } }], { message: "Restore record" });
2135
+ const restored = requireRecord(ctx.store, id);
2136
+ await emit(ctx, "record.restored", { record: restored });
2137
+ return restored;
2138
+ }
2139
+ async function bulkUpdate(ctx, ids, input, opts = {}) {
2140
+ assertCan(ctx, "records.write");
2141
+ const mutations = [];
2142
+ const events = [];
2143
+ const errors = [];
2144
+ for (const id of ids) {
2145
+ try {
2146
+ const before = requireRecord(ctx.store, id);
2147
+ const object = requireObject(ctx.store, before.object);
2148
+ const prepared = prepareRecordFields(ctx, object, input, before, opts);
2149
+ if (!prepared.changed.length) continue;
2150
+ mutations.push(recordPatchMutation(ctx, before, prepared.fields, prepared.changed));
2151
+ events.push({ before, changed: prepared.changed, stage: prepared.stageChange });
2152
+ } catch (err) {
2153
+ errors.push({ id, message: err.message });
2154
+ }
2155
+ }
2156
+ if (mutations.length) await ctx.store.write(mutations, { message: opts.message ?? `Update ${mutations.length} records` });
2157
+ if (!opts.silent) {
2158
+ for (const e of events) {
2159
+ const record = requireRecord(ctx.store, e.before.id);
2160
+ await emit(ctx, "record.updated", { record, before: e.before, changed: e.changed });
2161
+ if (e.stage) await emit(ctx, "stage.changed", { record, ...e.stage });
2162
+ }
2163
+ }
2164
+ return { updated: events.map((e) => e.before.id), errors };
2165
+ }
2166
+ async function bulkDelete(ctx, ids, opts = {}) {
2167
+ assertCan(ctx, "records.delete");
2168
+ const records = ids.map((id) => requireRecord(ctx.store, id, { includeDeleted: opts.hard }));
2169
+ const now = ctx.now();
2170
+ const mutations = opts.hard ? hardDeleteMutations(ctx, ids) : ids.map((id) => ({ op: "patch", collection: "records", id, fields: { deletedAt: now, updatedAt: now } }));
2171
+ if (mutations.length) await ctx.store.write(mutations, { message: `Delete ${ids.length} records` });
2172
+ for (const record of records) await emit(ctx, "record.deleted", { record, hard: !!opts.hard });
2173
+ return { deleted: ids };
2174
+ }
2175
+ export {
2176
+ bulkDelete,
2177
+ bulkUpdate,
2178
+ createRecord,
2179
+ deleteRecord,
2180
+ getRecord,
2181
+ getRecordDetails,
2182
+ hardDeleteMutations,
2183
+ listRecords,
2184
+ prepareRecordFields,
2185
+ queryContext,
2186
+ recordPatchMutation,
2187
+ restoreRecord,
2188
+ searchRecords,
2189
+ setRecordOwner,
2190
+ updateRecord
2191
+ };