zerochat 7.3.0__py3-none-any.whl

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 (130) hide show
  1. zerochat-7.3.0.dist-info/METADATA +70 -0
  2. zerochat-7.3.0.dist-info/RECORD +130 -0
  3. zerochat-7.3.0.dist-info/WHEEL +5 -0
  4. zerochat-7.3.0.dist-info/entry_points.txt +2 -0
  5. zerochat-7.3.0.dist-info/licenses/LICENSE +34 -0
  6. zerochat-7.3.0.dist-info/top_level.txt +2 -0
  7. zerochat.py +2004 -0
  8. zerochat_runtime/__init__.py +1 -0
  9. zerochat_runtime/assets/css/base.css +199 -0
  10. zerochat_runtime/assets/css/components/composer.css +1258 -0
  11. zerochat_runtime/assets/css/components/debug.css +777 -0
  12. zerochat_runtime/assets/css/components/header.css +97 -0
  13. zerochat_runtime/assets/css/components/icons.css +39 -0
  14. zerochat_runtime/assets/css/components/markdown.css +685 -0
  15. zerochat_runtime/assets/css/components/messages.css +473 -0
  16. zerochat_runtime/assets/css/components/modals.css +1319 -0
  17. zerochat_runtime/assets/css/components/sidebar.css +622 -0
  18. zerochat_runtime/assets/css/components/tools.css +1223 -0
  19. zerochat_runtime/assets/css/layout.css +171 -0
  20. zerochat_runtime/assets/css/print.css +120 -0
  21. zerochat_runtime/assets/css/styles.css +18 -0
  22. zerochat_runtime/assets/css/theme-overrides.css +555 -0
  23. zerochat_runtime/assets/css/tokens.css +165 -0
  24. zerochat_runtime/assets/help/architecture.html +247 -0
  25. zerochat_runtime/assets/help/composer.html +134 -0
  26. zerochat_runtime/assets/help/conversations.html +105 -0
  27. zerochat_runtime/assets/help/debug.html +108 -0
  28. zerochat_runtime/assets/help/en/architecture.html +247 -0
  29. zerochat_runtime/assets/help/en/composer.html +134 -0
  30. zerochat_runtime/assets/help/en/conversations.html +104 -0
  31. zerochat_runtime/assets/help/en/debug.html +105 -0
  32. zerochat_runtime/assets/help/en/gemini-free.html +39 -0
  33. zerochat_runtime/assets/help/en/index.html +191 -0
  34. zerochat_runtime/assets/help/en/learning.html +71 -0
  35. zerochat_runtime/assets/help/en/mcp.html +143 -0
  36. zerochat_runtime/assets/help/en/openrouter-free.html +39 -0
  37. zerochat_runtime/assets/help/en/profiles.html +173 -0
  38. zerochat_runtime/assets/help/en/rag.html +130 -0
  39. zerochat_runtime/assets/help/en/reasoning-telemetry.html +108 -0
  40. zerochat_runtime/assets/help/en/tools-agent.html +133 -0
  41. zerochat_runtime/assets/help/en/webllm.html +355 -0
  42. zerochat_runtime/assets/help/gemini-free.html +39 -0
  43. zerochat_runtime/assets/help/help.css +604 -0
  44. zerochat_runtime/assets/help/help.js +51 -0
  45. zerochat_runtime/assets/help/index.html +194 -0
  46. zerochat_runtime/assets/help/learning.html +71 -0
  47. zerochat_runtime/assets/help/mcp.html +143 -0
  48. zerochat_runtime/assets/help/openrouter-free.html +39 -0
  49. zerochat_runtime/assets/help/profiles.html +174 -0
  50. zerochat_runtime/assets/help/rag.html +130 -0
  51. zerochat_runtime/assets/help/reasoning-telemetry.html +111 -0
  52. zerochat_runtime/assets/help/tools-agent.html +133 -0
  53. zerochat_runtime/assets/help/webllm.html +359 -0
  54. zerochat_runtime/assets/js/agent-core.js +1553 -0
  55. zerochat_runtime/assets/js/api.js +844 -0
  56. zerochat_runtime/assets/js/app.js +2558 -0
  57. zerochat_runtime/assets/js/attachments.js +220 -0
  58. zerochat_runtime/assets/js/charts.js +338 -0
  59. zerochat_runtime/assets/js/chat-engine.js +566 -0
  60. zerochat_runtime/assets/js/config-store.js +207 -0
  61. zerochat_runtime/assets/js/context-manager.js +584 -0
  62. zerochat_runtime/assets/js/conversation-service.js +484 -0
  63. zerochat_runtime/assets/js/cookies.js +688 -0
  64. zerochat_runtime/assets/js/data-reset-service.js +136 -0
  65. zerochat_runtime/assets/js/debug.js +508 -0
  66. zerochat_runtime/assets/js/defaults.js +16 -0
  67. zerochat_runtime/assets/js/export.js +179 -0
  68. zerochat_runtime/assets/js/file-parser.js +2088 -0
  69. zerochat_runtime/assets/js/generation-controller.js +417 -0
  70. zerochat_runtime/assets/js/i18n.js +1483 -0
  71. zerochat_runtime/assets/js/icons.js +156 -0
  72. zerochat_runtime/assets/js/ingestionEngine.js +436 -0
  73. zerochat_runtime/assets/js/markdown.js +588 -0
  74. zerochat_runtime/assets/js/mcp.js +1271 -0
  75. zerochat_runtime/assets/js/message-turns.js +62 -0
  76. zerochat_runtime/assets/js/profile-backup.js +118 -0
  77. zerochat_runtime/assets/js/profile-export-bundle.js +481 -0
  78. zerochat_runtime/assets/js/profile-repository.js +213 -0
  79. zerochat_runtime/assets/js/providers-webllm.js +486 -0
  80. zerochat_runtime/assets/js/providers.js +1560 -0
  81. zerochat_runtime/assets/js/rag-index.js +295 -0
  82. zerochat_runtime/assets/js/rag-service.js +530 -0
  83. zerochat_runtime/assets/js/rag-ui.js +997 -0
  84. zerochat_runtime/assets/js/ragStorage.js +676 -0
  85. zerochat_runtime/assets/js/sandbox.js +449 -0
  86. zerochat_runtime/assets/js/state.js +704 -0
  87. zerochat_runtime/assets/js/storage-db.js +144 -0
  88. zerochat_runtime/assets/js/tool-cards.js +330 -0
  89. zerochat_runtime/assets/js/tool-security.js +653 -0
  90. zerochat_runtime/assets/js/tools/README.md +50 -0
  91. zerochat_runtime/assets/js/tools/builtin/agent-checkpoint.tool.js +212 -0
  92. zerochat_runtime/assets/js/tools/builtin/download-pdf.tool.js +111 -0
  93. zerochat_runtime/assets/js/tools/builtin/execute-javascript.tool.js +219 -0
  94. zerochat_runtime/assets/js/tools/builtin/fetch-web-page.tool.js +112 -0
  95. zerochat_runtime/assets/js/tools/builtin/list-documents.tool.js +117 -0
  96. zerochat_runtime/assets/js/tools/builtin/read-knowledge-chunk.tool.js +129 -0
  97. zerochat_runtime/assets/js/tools/builtin/read-knowledge-image.tool.js +95 -0
  98. zerochat_runtime/assets/js/tools/builtin/render-chart.tool.js +90 -0
  99. zerochat_runtime/assets/js/tools/builtin/search-knowledge-base.tool.js +124 -0
  100. zerochat_runtime/assets/js/tools/builtin/search-web.tool.js +125 -0
  101. zerochat_runtime/assets/js/tools/tool-manifest.js +53 -0
  102. zerochat_runtime/assets/js/tools/tool-runtime.js +77 -0
  103. zerochat_runtime/assets/js/ui-composer.js +319 -0
  104. zerochat_runtime/assets/js/ui-conversation.js +655 -0
  105. zerochat_runtime/assets/js/ui-dialogs.js +132 -0
  106. zerochat_runtime/assets/js/ui-generation-status.js +119 -0
  107. zerochat_runtime/assets/js/ui-inspector.js +804 -0
  108. zerochat_runtime/assets/js/ui-mcp.js +604 -0
  109. zerochat_runtime/assets/js/ui-profiles.js +824 -0
  110. zerochat_runtime/assets/js/ui-reasoning.js +146 -0
  111. zerochat_runtime/assets/js/ui-settings.js +825 -0
  112. zerochat_runtime/assets/js/ui-shell.js +215 -0
  113. zerochat_runtime/assets/js/ui-sidebar.js +429 -0
  114. zerochat_runtime/assets/js/ui-telemetry.js +404 -0
  115. zerochat_runtime/assets/js/ui-transfer.js +262 -0
  116. zerochat_runtime/assets/js/utils.js +216 -0
  117. zerochat_runtime/assets/js/vendor/orama.browser.js +11 -0
  118. zerochat_runtime/assets/js/web-browser.js +569 -0
  119. zerochat_runtime/assets/js/web-search.js +519 -0
  120. zerochat_runtime/assets/manifest.webmanifest +20 -0
  121. zerochat_runtime/assets/services/dummy_mcp/dummy_mcp_server.py +47 -0
  122. zerochat_runtime/assets/services/dummy_mcp/service.json +22 -0
  123. zerochat_runtime/assets/services/lsp/installer.json +9 -0
  124. zerochat_runtime/assets/services/lsp/service.json +22 -0
  125. zerochat_runtime/assets/services/memory/installer.json +9 -0
  126. zerochat_runtime/assets/services/memory/service.json +24 -0
  127. zerochat_runtime/assets/services/playwright/installer.json +10 -0
  128. zerochat_runtime/assets/services/playwright/service.json +39 -0
  129. zerochat_runtime/assets/sw.js +164 -0
  130. zerochat_runtime/assets/zerochat.html +671 -0
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Módulo Universal de Utilidades Compartidas para ZeroChat.
3
+ * ZeroChat - js/utils.js
4
+ *
5
+ * Centraliza funciones utilitarias esenciales (escapeHtml, fetchWithTimeout,
6
+ * serializeContent, clone, formatShortValue, resolveDep, etc.) para eliminar
7
+ * duplicación en toda la base de código.
8
+ */
9
+ (function (root, factory) {
10
+ if (typeof exports === 'object' && typeof module !== 'undefined') {
11
+ module.exports = factory();
12
+ } else {
13
+ root.ChatUtils = factory();
14
+ }
15
+ })(typeof self !== 'undefined' ? self : this, function () {
16
+ 'use strict';
17
+
18
+ /**
19
+ * Escapa caracteres especiales de HTML para prevenir inyecciones XSS.
20
+ * @param {*} str
21
+ * @returns {string}
22
+ */
23
+ function escapeHtml(str) {
24
+ if (str === null || str === undefined) return '';
25
+ return String(str)
26
+ .replace(/&/g, '&')
27
+ .replace(/</g, '&lt;')
28
+ .replace(/>/g, '&gt;')
29
+ .replace(/"/g, '&quot;')
30
+ .replace(/'/g, '&#39;');
31
+ }
32
+
33
+ /** Normaliza una URL no confiable para usarla en un atributo href. */
34
+ function sanitizeUrl(rawUrl) {
35
+ if (!rawUrl || typeof rawUrl !== 'string') return '#';
36
+ const trimmed = rawUrl.trim();
37
+ if (/^(?:https?:\/\/|mailto:|tel:)/i.test(trimmed)) return escapeHtml(trimmed);
38
+ if (!/^[a-z][a-z0-9+.-]*:/i.test(trimmed) && !/^[\\/]{2}/.test(trimmed)) return escapeHtml(trimmed);
39
+ return '#';
40
+ }
41
+
42
+ /** Normaliza una URL no confiable para usarla como origen de una imagen. */
43
+ function sanitizeImageUrl(rawUrl) {
44
+ if (!rawUrl || typeof rawUrl !== 'string') return '';
45
+ const trimmed = rawUrl.trim();
46
+ if (/^https?:\/\/[^\s"'<>]+/i.test(trimmed)) return escapeHtml(trimmed);
47
+ if (/^data:image\/(?:png|jpeg|jpg|gif|webp|svg\+xml);base64,[A-Za-z0-9+/=\s.]+/i.test(trimmed)) return trimmed.replace(/\s+/g, '');
48
+ if (/^blob:[^\s"'<>]+/i.test(trimmed) || /^rag-image:\/\/[a-zA-Z0-9_\-:]+/i.test(trimmed)) return escapeHtml(trimmed);
49
+ return '';
50
+ }
51
+
52
+ /**
53
+ * Asigna contenido no confiable como texto, sin interpretarlo como HTML.
54
+ * @param {Element|Object|null|undefined} element
55
+ * @param {*} value
56
+ * @returns {Element|Object|null|undefined}
57
+ */
58
+ function setText(element, value) {
59
+ if (element) element.textContent = value === null || value === undefined ? '' : String(value);
60
+ return element;
61
+ }
62
+
63
+ /**
64
+ * Elimina el contenido de un contenedor sin analizar HTML.
65
+ * @param {Element|Object|null|undefined} element
66
+ * @returns {Element|Object|null|undefined}
67
+ */
68
+ function clearElement(element) {
69
+ if (!element) return element;
70
+ if (typeof element.replaceChildren === 'function') element.replaceChildren();
71
+ else setText(element, '');
72
+ return element;
73
+ }
74
+
75
+ /**
76
+ * Añade un elemento cuyo contenido se asigna siempre mediante textContent.
77
+ * @param {Element|null|undefined} parent
78
+ * @param {string} tagName
79
+ * @param {*} value
80
+ * @param {{ className?: string }} [options]
81
+ * @returns {Element|null}
82
+ */
83
+ function appendTextElement(parent, tagName, value, options = {}) {
84
+ const doc = parent?.ownerDocument || (typeof document !== 'undefined' ? document : null);
85
+ if (!parent || !doc?.createElement || typeof parent.appendChild !== 'function') return null;
86
+ const element = doc.createElement(tagName);
87
+ if (options.className) element.className = options.className;
88
+ setText(element, value);
89
+ parent.appendChild(element);
90
+ return element;
91
+ }
92
+
93
+ /**
94
+ * Inserta HTML generado exclusivamente por código propio (por ejemplo SVGs).
95
+ * Nunca debe recibir datos de red, proveedores, herramientas o usuarios.
96
+ * @param {Element|Object|null|undefined} element
97
+ * @param {string} html
98
+ * @returns {Element|Object|null|undefined}
99
+ */
100
+ function setTrustedHtml(element, html) {
101
+ if (element) element.innerHTML = html || '';
102
+ return element;
103
+ }
104
+
105
+ /**
106
+ * Realiza una petición fetch con timeout configurable.
107
+ * @param {string|Request} resource
108
+ * @param {Object} [options={}]
109
+ * @param {number} [timeoutMs=8000]
110
+ * @returns {Promise<Response>}
111
+ */
112
+ async function fetchWithTimeout(resource, options = {}, timeoutMs = 8000) {
113
+ const controller = new AbortController();
114
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
115
+ try {
116
+ const response = await fetch(resource, {
117
+ ...options,
118
+ signal: controller.signal
119
+ });
120
+ return response;
121
+ } finally {
122
+ clearTimeout(timer);
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Serializa contenido multipart o texto a una cadena plana.
128
+ * @param {*} content
129
+ * @returns {string}
130
+ */
131
+ function serializeContent(content) {
132
+ if (typeof content === 'string') return content;
133
+ if (Array.isArray(content)) {
134
+ return content
135
+ .map((part) => {
136
+ if (!part) return '';
137
+ if (typeof part === 'string') return part;
138
+ if (typeof part.text === 'string') return part.text;
139
+ if (typeof part.content === 'string') return part.content;
140
+ return '';
141
+ })
142
+ .filter(Boolean)
143
+ .join('\n');
144
+ }
145
+ if (content && typeof content === 'object') {
146
+ if (typeof content.text === 'string') return content.text;
147
+ if (typeof content.content === 'string') return content.content;
148
+ }
149
+ return '';
150
+ }
151
+
152
+ /**
153
+ * Clona profundamente estructuras de datos JSON serializables.
154
+ * @template T
155
+ * @param {T} value
156
+ * @returns {T}
157
+ */
158
+ function clone(value) {
159
+ if (value === undefined || value === null) return value;
160
+ if (typeof structuredClone === 'function') {
161
+ try {
162
+ return structuredClone(value);
163
+ } catch (_) {
164
+ // Fallback a JSON si contiene tipos no clonables nativamente
165
+ }
166
+ }
167
+ return JSON.parse(JSON.stringify(value));
168
+ }
169
+
170
+ /**
171
+ * Formatea números de forma compacta (ej: 1500 -> 1.5k).
172
+ * @param {number} val
173
+ * @returns {string|number}
174
+ */
175
+ function formatShortValue(val) {
176
+ const num = Number(val);
177
+ if (!Number.isFinite(num)) return '0';
178
+ return num >= 1000 ? (num / 1000).toFixed(1) + 'k' : num;
179
+ }
180
+
181
+ /**
182
+ * Resuelve dependencias de forma segura en entornos UMD (Browser / Node.js).
183
+ * @param {string} globalName - Nombre en window/globalThis.
184
+ * @param {string} [modulePath] - Ruta para require() en Node.js.
185
+ * @returns {*}
186
+ */
187
+ function resolveDep(globalName, modulePath) {
188
+ if (typeof window !== 'undefined' && window[globalName]) {
189
+ return window[globalName];
190
+ }
191
+ if (typeof globalThis !== 'undefined' && globalThis[globalName]) {
192
+ return globalThis[globalName];
193
+ }
194
+ if (modulePath && typeof require === 'function') {
195
+ try {
196
+ return require(modulePath);
197
+ } catch (_) {}
198
+ }
199
+ return null;
200
+ }
201
+
202
+ return {
203
+ escapeHtml,
204
+ sanitizeUrl,
205
+ sanitizeImageUrl,
206
+ setText,
207
+ clearElement,
208
+ appendTextElement,
209
+ setTrustedHtml,
210
+ fetchWithTimeout,
211
+ serializeContent,
212
+ clone,
213
+ formatShortValue,
214
+ resolveDep
215
+ };
216
+ });
@@ -0,0 +1,11 @@
1
+ var ZeroChatOrama=(()=>{var le=Object.defineProperty;var Ft=Object.getOwnPropertyDescriptor;var Vt=Object.getOwnPropertyNames;var zt=Object.prototype.hasOwnProperty;var Wt=(e,t,n)=>t in e?le(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Gt=(e,t)=>{for(var n in t)le(e,n,{get:t[n],enumerable:!0})},$t=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Vt(t))!zt.call(e,o)&&o!==n&&le(e,o,{get:()=>t[o],enumerable:!(r=Ft(t,o))||r.enumerable});return e};var Yt=e=>$t(le({},"__esModule",{value:!0}),e);var D=(e,t,n)=>Wt(e,typeof t!="symbol"?t+"":t,n);var Wr={};Gt(Wr,{create:()=>Be,insertMultiple:()=>Ve,search:()=>xe});var Je={arabic:"ar",armenian:"am",bulgarian:"bg",czech:"cz",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"},He={dutch:/[^A-Za-zàèéìòóù0-9_'-]+/gim,english:/[^A-Za-zàèéìòóù0-9_'-]+/gim,french:/[^a-z0-9äâàéèëêïîöôùüûœç-]+/gim,italian:/[^A-Za-zàèéìòóù0-9_'-]+/gim,norwegian:/[^a-z0-9_æøåÆØÅäÄöÖüÜ]+/gim,portuguese:/[^a-z0-9à-úÀ-Ú]/gim,russian:/[^a-z0-9а-яА-ЯёЁ]+/gim,spanish:/[^a-z0-9A-Zá-úÁ-ÚñÑüÜ]+/gim,swedish:/[^a-z0-9_åÅäÄöÖüÜ-]+/gim,german:/[^a-z0-9A-ZäöüÄÖÜß]+/gim,finnish:/[^a-z0-9äöÄÖ]+/gim,danish:/[^a-z0-9æøåÆØÅ]+/gim,hungarian:/[^a-z0-9áéíóöőúüűÁÉÍÓÖŐÚÜŰ]+/gim,romanian:/[^a-z0-9ăâîșțĂÂÎȘȚ]+/gim,serbian:/[^a-z0-9čćžšđČĆŽŠĐ]+/gim,turkish:/[^a-z0-9çÇğĞıİöÖşŞüÜ]+/gim,lithuanian:/[^a-z0-9ąčęėįšųūžĄČĘĖĮŠŲŪŽ]+/gim,arabic:/[^a-z0-9أ-ي]+/gim,nepali:/[^a-z0-9अ-ह]+/gim,irish:/[^a-z0-9áéíóúÁÉÍÓÚ]+/gim,indian:/[^a-z0-9अ-ह]+/gim,armenian:/[^a-z0-9ա-ֆ]+/gim,greek:/[^a-z0-9α-ωά-ώ]+/gim,indonesian:/[^a-z0-9]+/gim,ukrainian:/[^a-z0-9а-яА-ЯіїєІЇЄ]+/gim,slovenian:/[^a-z0-9螚ȎŠ]+/gim,bulgarian:/[^a-z0-9а-яА-Я]+/gim,tamil:/[^a-z0-9அ-ஹ]+/gim,sanskrit:/[^a-z0-9A-Zāīūṛḷṃṁḥśṣṭḍṇṅñḻḹṝ]+/gim,czech:/[^A-Z0-9a-zěščřžýáíéúůóťďĚŠČŘŽÝÁÍÉÓÚŮŤĎ-]+/gim},q=Object.keys(Je);function qe(e){return e!==void 0&&q.includes(e)?Je[e]:void 0}var jt=Date.now().toString().slice(5),Kt=0;var Xe=BigInt(1e3),Ze=BigInt(1e6),Qe=BigInt(1e9);var Ne=65535;function X(e,t){if(t.length<Ne)Array.prototype.push.apply(e,t);else{let n=t.length;for(let r=0;r<n;r+=Ne)Array.prototype.push.apply(e,t.slice(r,r+Ne))}}function nt(e,...t){return e.replace(/%(?:(?<position>\d+)\$)?(?<width>-?\d*\.?\d*)(?<type>[dfs])/g,function(...n){let r=n[n.length-1],{width:o,type:s,position:c}=r,i=c?t[Number.parseInt(c)-1]:t.shift(),l=o===""?0:Number.parseInt(o);switch(s){case"d":return i.toString().padStart(l,"0");case"f":{let u=i,[a,f]=o.split(".").map(d=>Number.parseFloat(d));return typeof f=="number"&&f>=0&&(u=u.toFixed(f)),typeof a=="number"&&a>=0?u.toString().padStart(l,"0"):u.toString()}case"s":return l<0?i.toString().padEnd(-l," "):i.toString().padStart(l," ");default:return i}})}function Jt(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Ht(){return typeof process<"u"&&process.release&&process.release.name==="node"}function et(){return BigInt(Math.floor(performance.now()*1e6))}function k(e){return typeof e=="number"&&(e=BigInt(e)),e<Xe?`${e}ns`:e<Ze?`${e/Xe}\u03BCs`:e<Qe?`${e/Ze}ms`:`${e/Qe}s`}function P(){return Jt()?et():Ht()||typeof process<"u"&&typeof process?.hrtime?.bigint=="function"?process.hrtime.bigint():typeof performance<"u"?et():BigInt(0)}function Z(){return`${jt}-${Kt++}`}function ue(e,t){return Object.hasOwn===void 0?Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0:Object.hasOwn(e,t)?e[t]:void 0}function fe(e,t){return t[1]===e[1]?e[0]-t[0]:t[1]-e[1]}function rt(e){if(e.length===0)return[];if(e.length===1)return e[0];for(let n=1;n<e.length;n++)if(e[n].length<e[0].length){let r=e[0];e[0]=e[n],e[n]=r}let t=new Map;for(let n of e[0])t.set(n,1);for(let n=1;n<e.length;n++){let r=0;for(let o of e[n]){let s=t.get(o);s===n&&(t.set(o,s+1),r++)}if(r===0)return[]}return e[0].filter(n=>{let r=t.get(n);return r!==void 0&&t.set(n,0),r===e.length})}function ae(e,t){let n={},r=t.length;for(let o=0;o<r;o++){let s=t[o],c=s.split("."),i=e,l=c.length;for(let u=0;u<l;u++)if(i=i[c[u]],typeof i=="object"){if(i!==null&&"lat"in i&&"lon"in i&&typeof i.lat=="number"&&typeof i.lon=="number"){i=n[s]=i;break}else if(!Array.isArray(i)&&i!==null&&u===l-1){i=void 0;break}}else if((i===null||typeof i!="object")&&u<l-1){i=void 0;break}typeof i<"u"&&(n[s]=i)}return n}function V(e,t){return ae(e,[t])[t]}var qt={cm:.01,m:1,km:1e3,ft:.3048,yd:.9144,mi:1609.344};function de(e,t){let n=qt[t];if(n===void 0)throw new Error(I("INVALID_DISTANCE_SUFFIX",e).message);return e*n}function pe(e,t){e.hits=e.hits.map(n=>({...n,document:{...n.document,...t.reduce((r,o)=>{let s=o.split("."),c=s.pop(),i=r;for(let l of s)i[l]=i[l]??{},i=i[l];return i[c]=null,r},n.document)}}))}function E(e){return Array.isArray(e)?e.some(t=>E(t)):e?.constructor?.name==="AsyncFunction"}var tt="intersection"in new Set;function he(...e){if(e.length===0)return new Set;if(e.length===1)return e[0];if(e.length===2){let r=e[0],o=e[1];if(tt)return r.intersection(o);let s=new Set,c=r.size<o.size?r:o,i=c===r?o:r;for(let l of c)i.has(l)&&s.add(l);return s}let t={index:0,size:e[0].size};for(let r=1;r<e.length;r++)e[r].size<t.size&&(t.index=r,t.size=e[r].size);if(tt){let r=e[t.index];for(let o=0;o<e.length;o++)o!==t.index&&(r=r.intersection(e[o]));return r}let n=e[t.index];for(let r=0;r<e.length;r++){if(r===t.index)continue;let o=e[r];for(let s of n)o.has(s)||n.delete(s)}return n}var Xt="union"in new Set;function z(e,t){return Xt?e?e.union(t):t:e?new Set([...e,...t]):new Set(t)}function we(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function Oe(e){if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let t=new Int32Array(new SharedArrayBuffer(4));if((e>0&&e<1/0)===!1)throw typeof e!="number"&&typeof e!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(t,0,0,Number(e))}else{if((e>0&&e<1/0)===!1)throw typeof e!="number"&&typeof e!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(e);for(;n>Date.now(););}}var Zt=q.join(`
2
+ - `),Qt={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
3
+ Supported languages are:
4
+ - ${Zt}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.orama.com/docs/orama-js/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.orama.com/docs/orama-js for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',UNKNOWN_VECTOR_PROPERTY:'Unknown vector property "%s". Make sure the property exists in the schema and is configured as a vector.',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
5
+ Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.
6
+ Please install it before proceeding with creating an answer session.
7
+ Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#plugin-secure-proxy
8
+ `,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration.
9
+ Please provide a chat model before proceeding with creating an answer session.
10
+ Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#plugin-secure-proxy
11
+ `,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.",PLUGIN_COMPONENT_CONFLICT:'The component "%s" is already defined. The plugin "%s" is trying to redefine it.'};function I(e,...t){let n=new Error(nt(Qt[e]??`Unsupported Orama Error code: ${e}`,...t));return n.code=e,"captureStackTrace"in Error.prototype&&Error.captureStackTrace(n),n}function ot(e){return{raw:Number(e),formatted:k(e)}}function st(e){if(e.id){if(typeof e.id!="string")throw I("DOCUMENT_ID_MUST_BE_STRING",typeof e.id);return e.id}return Z()}function Ee(e,t){for(let[n,r]of Object.entries(t)){let o=e[n];if(!(typeof o>"u")&&!(r==="geopoint"&&typeof o=="object"&&typeof o.lon=="number"&&typeof o.lat=="number")&&!(r==="enum"&&(typeof o=="string"||typeof o=="number"))){if(r==="enum[]"&&Array.isArray(o)){let s=o.length;for(let c=0;c<s;c++)if(typeof o[c]!="string"&&typeof o[c]!="number")return n+"."+c;continue}if(M(r)){let s=Pe(r);if(!Array.isArray(o)||o.length!==s)throw I("INVALID_INPUT_VECTOR",n,s,o.length);continue}if(W(r)){if(!Array.isArray(o))return n;let s=Re(r),c=o.length;for(let i=0;i<c;i++)if(typeof o[i]!==s)return n+"."+i;continue}if(typeof r=="object"){if(!o||typeof o!="object")return n;let s=Ee(o,r);if(s)return n+"."+s;continue}if(typeof o!==r)return n}}}var en={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},tn={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"};function it(e){return e==="geopoint"}function M(e){return typeof e=="string"&&/^vector\[\d+\]$/.test(e)}function W(e){return typeof e=="string"&&en[e]}function Re(e){return tn[e]}function Pe(e){let t=Number(e.slice(7,-1));switch(!0){case isNaN(t):throw I("INVALID_VECTOR_VALUE",e);case t<=0:throw I("INVALID_VECTOR_SIZE",e);default:return t}}function ct(){return{idToInternalId:new Map,internalIdToId:[],save:nn,load:rn}}function nn(e){return{internalIdToId:e.internalIdToId}}function rn(e,t){let{internalIdToId:n}=t;e.internalDocumentIDStore.idToInternalId.clear(),e.internalDocumentIDStore.internalIdToId=[];let r=n.length;for(let o=0;o<r;o++){let s=n[o];e.internalDocumentIDStore.idToInternalId.set(s,o+1),e.internalDocumentIDStore.internalIdToId.push(s)}}function w(e,t){if(typeof t=="string"){let n=e.idToInternalId.get(t);if(n)return n;let r=e.idToInternalId.size+1;return e.idToInternalId.set(t,r),e.internalIdToId.push(t),r}return t>e.internalIdToId.length?w(e,t.toString()):t}function v(e,t){if(e.internalIdToId.length<t)throw new Error(`Invalid internalId ${t}`);return e.internalIdToId[t-1]}function sn(e,t){return{sharedInternalDocumentStore:t,docs:{},count:0}}function cn(e,t){let n=w(e.sharedInternalDocumentStore,t);return e.docs[n]}function ln(e,t){let n=t.length,r=Array.from({length:n});for(let o=0;o<n;o++){let s=w(e.sharedInternalDocumentStore,t[o]);r[o]=e.docs[s]}return r}function un(e){return e.docs}function fn(e,t,n,r){return typeof e.docs[n]<"u"?!1:(e.docs[n]=r,e.count++,!0)}function an(e,t){let n=w(e.sharedInternalDocumentStore,t);return typeof e.docs[n]>"u"?!1:(delete e.docs[n],e.count--,!0)}function dn(e){return e.count}function pn(e,t){let n=t;return{docs:n.docs,count:n.count,sharedInternalDocumentStore:e}}function hn(e){return{docs:e.docs,count:e.count}}function lt(){return{create:sn,get:cn,getMultiple:ln,getAll:un,store:fn,remove:an,count:dn,load:pn,save:hn}}var ut=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeUpsert","afterUpsert","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeUpsertMultiple","afterUpsertMultiple","beforeLoad","afterLoad","afterCreate"];function ft(e,t){let n=[],r=e.plugins?.length;if(!r)return n;for(let o=0;o<r;o++)try{let s=e.plugins[o];typeof s[t]=="function"&&n.push(s[t])}catch(s){throw console.error("Caught error in getAllPluginsByHook:",s),I("PLUGIN_CRASHED")}return n}var at=["tokenizer","index","documentsStore","sorter","pinning"],_e=["validateSchema","getDocumentIndexId","getDocumentProperties","formatElapsedTime"];function L(e,t,n,r){if(e.some(E))return(async()=>{for(let s of e)await s(t,n,r)})();for(let s of e)s(t,n,r)}function G(e,t,n){if(e.some(E))return(async()=>{for(let o of e)await o(t,n)})();for(let o of e)o(t,n)}function $(e,t,n,r,o){if(e.some(E))return(async()=>{for(let c of e)await c(t,n,r,o)})();for(let c of e)c(t,n,r,o)}function Y(e,t,n,r){if(e.some(E))return(async()=>{for(let s of e)await s(t,n,r)})();for(let s of e)s(t,n,r)}function dt(e,t){if(e.some(E))return(async()=>{for(let r of e)await r(t)})();for(let r of e)r(t)}var B=class e{constructor(t,n){D(this,"k");D(this,"v");D(this,"l",null);D(this,"r",null);D(this,"h",1);this.k=t,this.v=new Set(n)}updateHeight(){this.h=Math.max(e.getHeight(this.l),e.getHeight(this.r))+1}static getHeight(t){return t?t.h:0}getBalanceFactor(){return e.getHeight(this.l)-e.getHeight(this.r)}rotateLeft(){let t=this.r;return this.r=t.l,t.l=this,this.updateHeight(),t.updateHeight(),t}rotateRight(){let t=this.l;return this.l=t.r,t.r=this,this.updateHeight(),t.updateHeight(),t}toJSON(){return{k:this.k,v:Array.from(this.v),l:this.l?this.l.toJSON():null,r:this.r?this.r.toJSON():null,h:this.h}}static fromJSON(t){let n=new e(t.k,t.v);return n.l=t.l?e.fromJSON(t.l):null,n.r=t.r?e.fromJSON(t.r):null,n.h=t.h,n}},Q=class e{constructor(t,n){D(this,"root",null);D(this,"insertCount",0);t!==void 0&&n!==void 0&&(this.root=new B(t,n))}insert(t,n,r=1e3){this.root=this.insertNode(this.root,t,n,r)}insertMultiple(t,n,r=1e3){for(let o of n)this.insert(t,o,r)}rebalance(){this.root&&(this.root=this.rebalanceNode(this.root))}toJSON(){return{root:this.root?this.root.toJSON():null,insertCount:this.insertCount}}static fromJSON(t){let n=new e;return n.root=t.root?B.fromJSON(t.root):null,n.insertCount=t.insertCount||0,n}insertNode(t,n,r,o){if(t===null)return new B(n,[r]);let s=[],c=t,i=null;for(;c!==null;)if(s.push({parent:i,node:c}),n<c.k)if(c.l===null){c.l=new B(n,[r]),s.push({parent:c,node:c.l});break}else i=c,c=c.l;else if(n>c.k)if(c.r===null){c.r=new B(n,[r]),s.push({parent:c,node:c.r});break}else i=c,c=c.r;else return c.v.add(r),t;let l=!1;this.insertCount++%o===0&&(l=!0);for(let u=s.length-1;u>=0;u--){let{parent:a,node:f}=s[u];if(f.updateHeight(),l){let d=this.rebalanceNode(f);a?a.l===f?a.l=d:a.r===f&&(a.r=d):t=d}}return t}rebalanceNode(t){let n=t.getBalanceFactor();if(n>1){if(t.l&&t.l.getBalanceFactor()>=0)return t.rotateRight();if(t.l)return t.l=t.l.rotateLeft(),t.rotateRight()}if(n<-1){if(t.r&&t.r.getBalanceFactor()<=0)return t.rotateLeft();if(t.r)return t.r=t.r.rotateRight(),t.rotateLeft()}return t}find(t){let n=this.findNodeByKey(t);return n?n.v:null}contains(t){return this.find(t)!==null}getSize(){let t=0,n=[],r=this.root;for(;r||n.length>0;){for(;r;)n.push(r),r=r.l;r=n.pop(),t++,r=r.r}return t}isBalanced(){if(!this.root)return!0;let t=[this.root];for(;t.length>0;){let n=t.pop(),r=n.getBalanceFactor();if(Math.abs(r)>1)return!1;n.l&&t.push(n.l),n.r&&t.push(n.r)}return!0}remove(t){this.root=this.removeNode(this.root,t)}removeDocument(t,n){let r=this.findNodeByKey(t);r&&(r.v.size===1?this.root=this.removeNode(this.root,t):r.v=new Set([...r.v.values()].filter(o=>o!==n)))}findNodeByKey(t){let n=this.root;for(;n;)if(t<n.k)n=n.l;else if(t>n.k)n=n.r;else return n;return null}removeNode(t,n){if(t===null)return null;let r=[],o=t;for(;o!==null&&o.k!==n;)r.push(o),n<o.k?o=o.l:o=o.r;if(o===null)return t;if(o.l===null||o.r===null){let s=o.l?o.l:o.r;if(r.length===0)t=s;else{let c=r[r.length-1];c.l===o?c.l=s:c.r=s}}else{let s=o,c=o.r;for(;c.l!==null;)s=c,c=c.l;o.k=c.k,o.v=c.v,s.l===c?s.l=c.r:s.r=c.r,o=s}r.push(o);for(let s=r.length-1;s>=0;s--){let c=r[s];c.updateHeight();let i=this.rebalanceNode(c);if(s>0){let l=r[s-1];l.l===c?l.l=i:l.r===c&&(l.r=i)}else t=i}return t}rangeSearch(t,n){let r=new Set,o=[],s=this.root;for(;s||o.length>0;){for(;s;)o.push(s),s=s.l;if(s=o.pop(),s.k>=t&&s.k<=n)for(let c of s.v)r.add(c);if(s.k>n)break;s=s.r}return r}greaterThan(t,n=!1){let r=new Set,o=[],s=this.root;for(;s||o.length>0;){for(;s;)o.push(s),s=s.r;if(s=o.pop(),n&&s.k>=t||!n&&s.k>t)for(let c of s.v)r.add(c);else if(s.k<=t)break;s=s.l}return r}lessThan(t,n=!1){let r=new Set,o=[],s=this.root;for(;s||o.length>0;){for(;s;)o.push(s),s=s.l;if(s=o.pop(),n&&s.k<=t||!n&&s.k<t)for(let c of s.v)r.add(c);else if(s.k>t)break;s=s.r}return r}};var ee=class e{constructor(){D(this,"numberToDocumentId");this.numberToDocumentId=new Map}insert(t,n){this.numberToDocumentId.has(t)?this.numberToDocumentId.get(t).add(n):this.numberToDocumentId.set(t,new Set([n]))}find(t){let n=this.numberToDocumentId.get(t);return n?Array.from(n):null}remove(t){this.numberToDocumentId.delete(t)}removeDocument(t,n){let r=this.numberToDocumentId.get(n);r&&(r.delete(t),r.size===0&&this.numberToDocumentId.delete(n))}contains(t){return this.numberToDocumentId.has(t)}getSize(){let t=0;for(let n of this.numberToDocumentId.values())t+=n.size;return t}filter(t){let n=Object.keys(t);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"eq":{let o=t[r],s=this.numberToDocumentId.get(o);return s?Array.from(s):[]}case"in":{let o=t[r],s=new Set;for(let c of o){let i=this.numberToDocumentId.get(c);if(i)for(let l of i)s.add(l)}return Array.from(s)}case"nin":{let o=new Set(t[r]),s=new Set;for(let[c,i]of this.numberToDocumentId.entries())if(!o.has(c))for(let l of i)s.add(l);return Array.from(s)}default:throw new Error("Invalid operation")}}filterArr(t){let n=Object.keys(t);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"containsAll":{let s=t[r].map(i=>this.numberToDocumentId.get(i)??new Set);if(s.length===0)return[];let c=s.reduce((i,l)=>new Set([...i].filter(u=>l.has(u))));return Array.from(c)}case"containsAny":{let s=t[r].map(i=>this.numberToDocumentId.get(i)??new Set);if(s.length===0)return[];let c=s.reduce((i,l)=>new Set([...i,...l]));return Array.from(c)}default:throw new Error("Invalid operation")}}static fromJSON(t){if(!t.numberToDocumentId)throw new Error("Invalid Flat Tree JSON");let n=new e;for(let[r,o]of t.numberToDocumentId)n.numberToDocumentId.set(r,new Set(o));return n}toJSON(){return{numberToDocumentId:Array.from(this.numberToDocumentId.entries()).map(([t,n])=>[t,Array.from(n)])}}};function mn(e,t,n){if(n<0)return-1;if(e===t)return 0;let r=e.length,o=t.length;if(r===0)return o<=n?o:-1;if(o===0)return r<=n?r:-1;let s=Math.abs(r-o);if(e.startsWith(t))return s<=n?s:-1;if(t.startsWith(e))return 0;if(s>n)return-1;let c=[];for(let i=0;i<=r;i++){c[i]=[i];for(let l=1;l<=o;l++)c[i][l]=i===0?l:0}for(let i=1;i<=r;i++){let l=1/0;for(let u=1;u<=o;u++)e[i-1]===t[u-1]?c[i][u]=c[i-1][u-1]:c[i][u]=Math.min(c[i-1][u]+1,c[i][u-1]+1,c[i-1][u-1]+1),l=Math.min(l,c[i][u]);if(l>n)return-1}return c[r][o]<=n?c[r][o]:-1}function Me(e,t,n){let r=mn(e,t,n);return{distance:r,isBounded:r>=0}}var ge=class e{constructor(t,n,r){D(this,"k");D(this,"s");D(this,"c",new Map);D(this,"d",new Set);D(this,"e");D(this,"w","");this.k=t,this.s=n,this.e=r}updateParent(t){this.w=t.w+this.s}addDocument(t){this.d.add(t)}removeDocument(t){return this.d.delete(t)}findAllWords(t,n,r,o){let s=[this];for(;s.length>0;){let c=s.pop();if(c.e){let{w:i,d:l}=c;if(r&&i!==n)continue;if(ue(t,i)!==null)if(o)if(Math.abs(n.length-i.length)<=o&&Me(n,i,o).isBounded)t[i]=[];else continue;else t[i]=[];if(ue(t,i)!=null&&l.size>0){let u=t[i];for(let a of l)u.includes(a)||u.push(a)}}c.c.size>0&&s.push(...c.c.values())}return t}insert(t,n){let r=this,o=0,s=t.length;for(;o<s;){let c=t[o],i=r.c.get(c);if(i){let l=i.s,u=l.length,a=0;for(;a<u&&o+a<s&&l[a]===t[o+a];)a++;if(a===u){if(r=i,o+=a,o===s){i.e||(i.e=!0),i.addDocument(n);return}continue}let f=l.slice(0,a),d=l.slice(a),p=t.slice(o+a),h=new e(f[0],f,!1);if(r.c.set(f[0],h),h.updateParent(r),i.s=d,i.k=d[0],h.c.set(d[0],i),i.updateParent(h),p){let y=new e(p[0],p,!0);y.addDocument(n),h.c.set(p[0],y),y.updateParent(h)}else h.e=!0,h.addDocument(n);return}else{let l=new e(c,t.slice(o),!0);l.addDocument(n),r.c.set(c,l),l.updateParent(r);return}}r.e||(r.e=!0),r.addDocument(n)}_findLevenshtein(t,n,r,o,s){let c=[{node:this,index:n,tolerance:r}];for(;c.length>0;){let{node:i,index:l,tolerance:u}=c.pop();if(i.w.startsWith(t)){i.findAllWords(s,t,!1,0);continue}if(u<0)continue;if(i.e){let{w:f,d}=i;if(f&&(Me(t,f,o).isBounded&&(s[f]=[]),ue(s,f)!==void 0&&d.size>0)){let p=new Set(s[f]);for(let h of d)p.add(h);s[f]=Array.from(p)}}if(l>=t.length)continue;let a=t[l];if(i.c.has(a)){let f=i.c.get(a);c.push({node:f,index:l+1,tolerance:u})}c.push({node:i,index:l+1,tolerance:u-1});for(let[f,d]of i.c)c.push({node:d,index:l,tolerance:u-1}),f!==a&&c.push({node:d,index:l+1,tolerance:u-1})}}find(t){let{term:n,exact:r,tolerance:o}=t;if(o&&!r){let s={};return this._findLevenshtein(n,0,o,o,s),s}else{let s=this,c=0,i=n.length;for(;c<i;){let u=n[c],a=s.c.get(u);if(a){let f=a.s,d=f.length,p=0;for(;p<d&&c+p<i&&f[p]===n[c+p];)p++;if(p===d)s=a,c+=p;else if(c+p===i)if(p===i-c){if(r)return{};{let h={};return a.findAllWords(h,n,r,o),h}}else return{};else return{}}else return{}}let l={};return s.findAllWords(l,n,r,o),l}}contains(t){let n=this,r=0,o=t.length;for(;r<o;){let s=t[r],c=n.c.get(s);if(c){let i=c.s,l=i.length,u=0;for(;u<l&&r+u<o&&i[u]===t[r+u];)u++;if(u<l)return!1;r+=l,n=c}else return!1}return!0}removeWord(t){if(!t)return!1;let n=this,r=t.length,o=[];for(let s=0;s<r;s++){let c=t[s];if(n.c.has(c)){let i=n.c.get(c);o.push({parent:n,character:c}),s+=i.s.length-1,n=i}else return!1}for(n.d.clear(),n.e=!1;o.length>0&&n.c.size===0&&!n.e&&n.d.size===0;){let{parent:s,character:c}=o.pop();s.c.delete(c),n=s}return!0}removeDocumentByWord(t,n,r=!0){if(!t)return!0;let o=this,s=t.length;for(let c=0;c<s;c++){let i=t[c];if(o.c.has(i)){let l=o.c.get(i);c+=l.s.length-1,o=l,r&&o.w!==t||o.removeDocument(n)}else return!1}return!0}static getCommonPrefix(t,n){let r=Math.min(t.length,n.length),o=0;for(;o<r&&t.charCodeAt(o)===n.charCodeAt(o);)o++;return t.slice(0,o)}toJSON(){return{w:this.w,s:this.s,e:this.e,k:this.k,d:Array.from(this.d),c:Array.from(this.c?.entries())?.map(([t,n])=>[t,n.toJSON()])}}static fromJSON(t){let n=new e(t.k,t.s,t.e);return n.w=t.w,n.d=new Set(t.d),n.c=new Map(t?.c?.map(([r,o])=>[r,e.fromJSON(o)])||[]),n}},te=class e extends ge{constructor(){super("","",!1)}static fromJSON(t){let n=new e;return n.w=t.w,n.s=t.s,n.e=t.e,n.k=t.k,n.d=new Set(t.d),n.c=new Map(t?.c?.map(([r,o])=>[r,ge.fromJSON(o)])||[]),n}toJSON(){return super.toJSON()}};var me=class e{constructor(t,n){D(this,"point");D(this,"docIDs");D(this,"left");D(this,"right");D(this,"parent");this.point=t,this.docIDs=new Set(n),this.left=null,this.right=null,this.parent=null}toJSON(){return{point:this.point,docIDs:Array.from(this.docIDs),left:this.left?this.left.toJSON():null,right:this.right?this.right.toJSON():null}}static fromJSON(t,n=null){let r=new e(t.point,t.docIDs);return r.parent=n,t.left&&(r.left=e.fromJSON(t.left,r)),t.right&&(r.right=e.fromJSON(t.right,r)),r}},U=class e{constructor(){D(this,"root");D(this,"nodeMap");this.root=null,this.nodeMap=new Map}getPointKey(t){return`${t.lon},${t.lat}`}insert(t,n){let r=this.getPointKey(t),o=this.nodeMap.get(r);if(o){n.forEach(l=>o.docIDs.add(l));return}let s=new me(t,n);if(this.nodeMap.set(r,s),this.root==null){this.root=s;return}let c=this.root,i=0;for(;;){if(i%2===0)if(t.lon<c.point.lon){if(c.left==null){c.left=s,s.parent=c;return}c=c.left}else{if(c.right==null){c.right=s,s.parent=c;return}c=c.right}else if(t.lat<c.point.lat){if(c.left==null){c.left=s,s.parent=c;return}c=c.left}else{if(c.right==null){c.right=s,s.parent=c;return}c=c.right}i++}}contains(t){let n=this.getPointKey(t);return this.nodeMap.has(n)}getDocIDsByCoordinates(t){let n=this.getPointKey(t),r=this.nodeMap.get(n);return r?Array.from(r.docIDs):null}removeDocByID(t,n){let r=this.getPointKey(t),o=this.nodeMap.get(r);o&&(o.docIDs.delete(n),o.docIDs.size===0&&(this.nodeMap.delete(r),this.deleteNode(o)))}deleteNode(t){let n=t.parent,r=t.left?t.left:t.right;r&&(r.parent=n),n?n.left===t?n.left=r:n.right===t&&(n.right=r):(this.root=r,this.root&&(this.root.parent=null))}searchByRadius(t,n,r=!0,o="asc",s=!1){let c=s?e.vincentyDistance:e.haversineDistance,i=[{node:this.root,depth:0}],l=[];for(;i.length>0;){let{node:u,depth:a}=i.pop();if(u==null)continue;let f=c(t,u.point);(r?f<=n:f>n)&&l.push({point:u.point,docIDs:Array.from(u.docIDs)}),u.left!=null&&i.push({node:u.left,depth:a+1}),u.right!=null&&i.push({node:u.right,depth:a+1})}return o&&l.sort((u,a)=>{let f=c(t,u.point),d=c(t,a.point);return o.toLowerCase()==="asc"?f-d:d-f}),l}searchByPolygon(t,n=!0,r=null,o=!1){let s=[{node:this.root,depth:0}],c=[];for(;s.length>0;){let{node:l,depth:u}=s.pop();if(l==null)continue;l.left!=null&&s.push({node:l.left,depth:u+1}),l.right!=null&&s.push({node:l.right,depth:u+1});let a=e.isPointInPolygon(t,l.point);(a&&n||!a&&!n)&&c.push({point:l.point,docIDs:Array.from(l.docIDs)})}let i=e.calculatePolygonCentroid(t);if(r){let l=o?e.vincentyDistance:e.haversineDistance;c.sort((u,a)=>{let f=l(i,u.point),d=l(i,a.point);return r.toLowerCase()==="asc"?f-d:d-f})}return c}toJSON(){return{root:this.root?this.root.toJSON():null}}static fromJSON(t){let n=new e;return t.root&&(n.root=me.fromJSON(t.root),n.buildNodeMap(n.root)),n}buildNodeMap(t){if(t==null)return;let n=this.getPointKey(t.point);this.nodeMap.set(n,t),t.left&&this.buildNodeMap(t.left),t.right&&this.buildNodeMap(t.right)}static calculatePolygonCentroid(t){let n=0,r=0,o=0,s=t.length;for(let i=0,l=s-1;i<s;l=i++){let u=t[i].lon,a=t[i].lat,f=t[l].lon,d=t[l].lat,p=u*d-f*a;n+=p,r+=(u+f)*p,o+=(a+d)*p}n/=2;let c=6*n;return r/=c,o/=c,{lon:r,lat:o}}static isPointInPolygon(t,n){let r=!1,o=n.lon,s=n.lat,c=t.length;for(let i=0,l=c-1;i<c;l=i++){let u=t[i].lon,a=t[i].lat,f=t[l].lon,d=t[l].lat;a>s!=d>s&&o<(f-u)*(s-a)/(d-a)+u&&(r=!r)}return r}static haversineDistance(t,n){let r=Math.PI/180,o=t.lat*r,s=n.lat*r,c=(n.lat-t.lat)*r,i=(n.lon-t.lon)*r,l=Math.sin(c/2)*Math.sin(c/2)+Math.cos(o)*Math.cos(s)*Math.sin(i/2)*Math.sin(i/2);return 6371e3*(2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l)))}static vincentyDistance(t,n){let o=.0033528106647474805,s=(1-o)*6378137,c=Math.PI/180,i=t.lat*c,l=n.lat*c,u=(n.lon-t.lon)*c,a=Math.atan((1-o)*Math.tan(i)),f=Math.atan((1-o)*Math.tan(l)),d=Math.sin(a),p=Math.cos(a),h=Math.sin(f),y=Math.cos(f),g=u,m,S=1e3,b,T,x,N,O,A;do{let F=Math.sin(g),H=Math.cos(g);if(b=Math.sqrt(y*F*(y*F)+(p*h-d*y*H)*(p*h-d*y*H)),b===0)return 0;T=d*h+p*y*H,x=Math.atan2(b,T),N=p*y*F/b,O=1-N*N,A=T-2*d*h/O,isNaN(A)&&(A=0);let Ae=o/16*O*(4+o*(4-3*O));m=g,g=u+(1-Ae)*o*N*(x+Ae*b*(A+Ae*T*(-1+2*A*A)))}while(Math.abs(g-m)>1e-12&&--S>0);if(S===0)return NaN;let R=O*(6378137*6378137-s*s)/(s*s),ie=1+R/16384*(4096+R*(-768+R*(320-175*R))),C=R/1024*(256+R*(-128+R*(74-47*R))),De=C*b*(A+C/4*(T*(-1+2*A*A)-C/6*A*(-3+4*b*b)*(-3+4*A*A)));return s*ie*(x-De)}};var ne=class e{constructor(){D(this,"true");D(this,"false");this.true=new Set,this.false=new Set}insert(t,n){n?this.true.add(t):this.false.add(t)}delete(t,n){n?this.true.delete(t):this.false.delete(t)}getSize(){return this.true.size+this.false.size}toJSON(){return{true:Array.from(this.true),false:Array.from(this.false)}}static fromJSON(t){let n=new e;return n.true=new Set(t.true),n.false=new Set(t.false),n}};function pt(e,t,n,r,o,{k:s,b:c,d:i}){return Math.log(1+(n-t+.5)/(t+.5))*(i+e*(s+1))/(e+s*(1-c+c*r/o))}var re=class e{constructor(t){D(this,"size");D(this,"vectors",new Map);this.size=t}add(t,n){n instanceof Float32Array||(n=new Float32Array(n));let r=ht(n,this.size);this.vectors.set(t,[r,n])}remove(t){this.vectors.delete(t)}find(t,n,r){return t instanceof Float32Array||(t=new Float32Array(t)),yn(t,r,this.vectors,this.size,n)}toJSON(){let t=[];for(let[n,[r,o]]of this.vectors)t.push([n,[r,Array.from(o)]]);return{size:this.size,vectors:t}}static fromJSON(t){let n=t,r=new e(n.size);for(let[o,[s,c]]of n.vectors)r.vectors.set(o,[s,new Float32Array(c)]);return r}};function ht(e,t){let n=0;for(let r=0;r<t;r++)n+=e[r]*e[r];return Math.sqrt(n)}function yn(e,t,n,r,o){let s=ht(e,r),c=[],i=t||n.keys();for(let l of i){let u=n.get(l);if(!u)continue;let a=u[0],f=u[1],d=0;for(let h=0;h<r;h++)d+=e[h]*f[h];let p=d/(s*a);p>=o&&c.push([l,p])}return c}function Sn(e,t,n,r,o){let s=w(e.sharedInternalDocumentStore,n);e.avgFieldLength[t]=((e.avgFieldLength[t]??0)*(o-1)+r.length)/o,e.fieldLengths[t][s]=r.length,e.frequencies[t][s]={}}function In(e,t,n,r,o){let s=0;for(let l of r)l===o&&s++;let c=w(e.sharedInternalDocumentStore,n),i=s/r.length;e.frequencies[t][c][o]=i,o in e.tokenOccurrences[t]||(e.tokenOccurrences[t][o]=0),e.tokenOccurrences[t][o]=(e.tokenOccurrences[t][o]??0)+1}function bn(e,t,n,r){let o=w(e.sharedInternalDocumentStore,n);r>1?e.avgFieldLength[t]=(e.avgFieldLength[t]*r-e.fieldLengths[t][o])/(r-1):e.avgFieldLength[t]=void 0,e.fieldLengths[t][o]=void 0,e.frequencies[t][o]=void 0}function Tn(e,t,n){e.tokenOccurrences[t][n]--}function St(e,t,n,r,o=""){r||(r={sharedInternalDocumentStore:t,indexes:{},vectorIndexes:{},searchableProperties:[],searchablePropertiesWithTypes:{},frequencies:{},tokenOccurrences:{},avgFieldLength:{},fieldLengths:{}});for(let[s,c]of Object.entries(n)){let i=`${o}${o?".":""}${s}`;if(typeof c=="object"&&!Array.isArray(c)){St(e,t,c,r,i);continue}if(M(c))r.searchableProperties.push(i),r.searchablePropertiesWithTypes[i]=c,r.vectorIndexes[i]={type:"Vector",node:new re(Pe(c)),isArray:!1};else{let l=/\[/.test(c);switch(c){case"boolean":case"boolean[]":r.indexes[i]={type:"Bool",node:new ne,isArray:l};break;case"number":case"number[]":r.indexes[i]={type:"AVL",node:new Q(0,[]),isArray:l};break;case"string":case"string[]":r.indexes[i]={type:"Radix",node:new te,isArray:l},r.avgFieldLength[i]=0,r.frequencies[i]={},r.tokenOccurrences[i]={},r.fieldLengths[i]={};break;case"enum":case"enum[]":r.indexes[i]={type:"Flat",node:new ee,isArray:l};break;case"geopoint":r.indexes[i]={type:"BKD",node:new U,isArray:l};break;default:throw I("INVALID_SCHEMA_TYPE",Array.isArray(c)?"array":c,i)}r.searchableProperties.push(i),r.searchablePropertiesWithTypes[i]=c}}return r}function xn(e,t,n,r,o,s,c,i){return l=>{let{type:u,node:a}=t.indexes[n];switch(u){case"Bool":{a[l?"true":"false"].add(r);break}case"AVL":{let f=i?.avlRebalanceThreshold??1;a.insert(l,r,f);break}case"Radix":{let f=s.tokenize(l,o,n,!1);e.insertDocumentScoreParameters(t,n,r,f,c);for(let d of f)e.insertTokenScoreParameters(t,n,r,f,d),a.insert(d,r);break}case"Flat":{a.insert(l,r);break}case"BKD":{a.insert(l,[r]);break}}}}function Dn(e,t,n,r,o,s,c,i,l,u,a){if(M(c))return An(t,n,s,r,o);let f=xn(e,t,n,o,i,l,u,a);if(!W(c))return f(s);let d=s,p=d.length;for(let h=0;h<p;h++)f(d[h])}function An(e,t,n,r,o){e.vectorIndexes[t].node.add(o,n)}function gt(e,t,n,r,o,s,c,i,l,u){if(M(c))return t.vectorIndexes[n].node.remove(o),!0;let{type:a,node:f}=t.indexes[n];switch(a){case"AVL":return f.removeDocument(s,o),!0;case"Bool":return f[s?"true":"false"].delete(o),!0;case"Radix":{let d=l.tokenize(s,i,n);e.removeDocumentScoreParameters(t,n,r,u);for(let p of d)e.removeTokenScoreParameters(t,n,p),f.removeDocumentByWord(p,o);return!0}case"Flat":return f.removeDocument(o,s),!0;case"BKD":return f.removeDocByID(s,o),!1}}function Nn(e,t,n,r,o,s,c,i,l,u){if(!W(c))return gt(e,t,n,r,o,s,c,i,l,u);let a=Re(c),f=s,d=f.length;for(let p=0;p<d;p++)gt(e,t,n,r,o,f[p],a,i,l,u);return!0}function It(e,t,n,r,o,s,c,i,l,u){let a=Array.from(r),f=e.avgFieldLength[t],d=e.fieldLengths[t],p=e.tokenOccurrences[t],h=e.frequencies[t],y=typeof p[n]=="number"?p[n]??0:0,g=a.length;for(let m=0;m<g;m++){let S=a[m];if(l&&!l.has(S))continue;u.has(S)||u.set(S,new Map);let b=u.get(S);b.set(t,(b.get(t)||0)+1);let T=h?.[S]?.[n]??0,x=pt(T,y,o,d[S],f,s);c.has(S)?c.set(S,c.get(S)+x*i):c.set(S,x*i)}}function wn(e,t,n,r,o,s,c,i,l,u,a,f=0){let d=n.tokenize(t,r),p=d.length||1,h=new Map,y=new Map,g=new Map;for(let b of o){if(!(b in e.indexes))continue;let T=e.indexes[b],{type:x}=T;if(x!=="Radix")throw I("WRONG_SEARCH_PROPERTY_TYPE",b);let N=i[b]??1;if(N<=0)throw I("INVALID_BOOST_VALUE",N);d.length===0&&!t&&d.push("");let O=d.length;for(let A=0;A<O;A++){let R=d[A],ie=T.node.find({term:R,exact:s,tolerance:c}),C=Object.keys(ie);C.length>0&&y.set(R,!0);let De=C.length;for(let ce=0;ce<De;ce++){let F=C[ce],H=ie[F];It(e,b,F,H,u,l,g,N,a,h)}}}let m=Array.from(g.entries()).map(([b,T])=>[b,T]).sort((b,T)=>T[1]-b[1]);if(m.length===0)return[];if(f===1)return m;if(f===0){if(p===1)return m;for(let T of d)if(!y.get(T))return[];return m.filter(([T])=>{let x=h.get(T);return x?Array.from(x.values()).some(N=>N===p):!1})}let S=m.filter(([b])=>{let T=h.get(b);return T?Array.from(T.values()).some(x=>x===p):!1});if(S.length>0){let b=m.filter(([x])=>!S.some(([N])=>N===x)),T=Math.ceil(b.length*f);return[...S,...b.slice(0,T)]}return m}function ye(e,t,n,r){if("and"in n&&n.and&&Array.isArray(n.and)){let c=n.and;if(c.length===0)return new Set;let i=c.map(l=>ye(e,t,l,r));return he(...i)}if("or"in n&&n.or&&Array.isArray(n.or)){let c=n.or;return c.length===0?new Set:c.map(l=>ye(e,t,l,r)).reduce((l,u)=>z(l,u),new Set)}if("not"in n&&n.not){let c=n.not,i=new Set,l=e.sharedInternalDocumentStore;for(let a=1;a<=l.internalIdToId.length;a++)i.add(a);let u=ye(e,t,c,r);return we(i,u)}let o=Object.keys(n),s=o.reduce((c,i)=>({[i]:new Set,...c}),{});for(let c of o){let i=n[c];if(typeof e.indexes[c]>"u")throw I("UNKNOWN_FILTER_PROPERTY",c);let{node:l,type:u,isArray:a}=e.indexes[c];if(u==="Bool"){let d=l,p=i?d.true:d.false;s[c]=z(s[c],p);continue}if(u==="BKD"){let d;if("radius"in i)d="radius";else if("polygon"in i)d="polygon";else throw new Error(`Invalid operation ${i}`);if(d==="radius"){let{value:p,coordinates:h,unit:y="m",inside:g=!0,highPrecision:m=!1}=i[d],S=de(p,y),b=l.searchByRadius(h,S,g,void 0,m);s[c]=mt(s[c],b)}else{let{coordinates:p,inside:h=!0,highPrecision:y=!1}=i[d],g=l.searchByPolygon(p,h,void 0,y);s[c]=mt(s[c],g)}continue}if(u==="Radix"&&(typeof i=="string"||Array.isArray(i))){for(let d of[i].flat()){let p=t.tokenize(d,r,c);for(let h of p){let y=l.find({term:h,exact:!0});s[c]=Mn(s[c],y)}}continue}let f=Object.keys(i);if(f.length>1)throw I("INVALID_FILTER_OPERATION",f.length);if(u==="Flat"){let d=new Set(a?l.filterArr(i):l.filter(i));s[c]=z(s[c],d);continue}if(u==="AVL"){let d=f[0],p=i[d],h;switch(d){case"gt":{h=l.greaterThan(p,!1);break}case"gte":{h=l.greaterThan(p,!0);break}case"lt":{h=l.lessThan(p,!1);break}case"lte":{h=l.lessThan(p,!0);break}case"eq":{h=l.find(p)??new Set;break}case"between":{let[y,g]=p;h=l.rangeSearch(y,g);break}default:throw I("INVALID_FILTER_OPERATION",d)}s[c]=z(s[c],h)}}return he(...Object.values(s))}function On(e){return e.searchableProperties}function En(e){return e.searchablePropertiesWithTypes}function Rn(e,t){let{indexes:n,vectorIndexes:r,searchableProperties:o,searchablePropertiesWithTypes:s,frequencies:c,tokenOccurrences:i,avgFieldLength:l,fieldLengths:u}=t,a={},f={};for(let d of Object.keys(n)){let{node:p,type:h,isArray:y}=n[d];switch(h){case"Radix":a[d]={type:"Radix",node:te.fromJSON(p),isArray:y};break;case"Flat":a[d]={type:"Flat",node:ee.fromJSON(p),isArray:y};break;case"AVL":a[d]={type:"AVL",node:Q.fromJSON(p),isArray:y};break;case"BKD":a[d]={type:"BKD",node:U.fromJSON(p),isArray:y};break;case"Bool":a[d]={type:"Bool",node:ne.fromJSON(p),isArray:y};break;default:a[d]=n[d]}}for(let d of Object.keys(r))f[d]={type:"Vector",isArray:!1,node:re.fromJSON(r[d])};return{sharedInternalDocumentStore:e,indexes:a,vectorIndexes:f,searchableProperties:o,searchablePropertiesWithTypes:s,frequencies:c,tokenOccurrences:i,avgFieldLength:l,fieldLengths:u}}function Pn(e){let{indexes:t,vectorIndexes:n,searchableProperties:r,searchablePropertiesWithTypes:o,frequencies:s,tokenOccurrences:c,avgFieldLength:i,fieldLengths:l}=e,u={};for(let f of Object.keys(n))u[f]=n[f].node.toJSON();let a={};for(let f of Object.keys(t)){let{type:d,node:p,isArray:h}=t[f];d==="Flat"||d==="Radix"||d==="AVL"||d==="BKD"||d==="Bool"?a[f]={type:d,node:p.toJSON(),isArray:h}:(a[f]=t[f],a[f].node=a[f].node.toJSON())}return{indexes:a,vectorIndexes:u,searchableProperties:r,searchablePropertiesWithTypes:o,frequencies:s,tokenOccurrences:c,avgFieldLength:i,fieldLengths:l}}function bt(){return{create:St,insert:Dn,remove:Nn,insertDocumentScoreParameters:Sn,insertTokenScoreParameters:In,removeDocumentScoreParameters:bn,removeTokenScoreParameters:Tn,calculateResultScores:It,search:wn,searchByWhereClause:ye,getSearchableProperties:On,getSearchablePropertiesWithTypes:En,load:Rn,save:Pn}}function mt(e,t){e||(e=new Set);let n=t.length;for(let r=0;r<n;r++){let o=t[r].docIDs,s=o.length;for(let c=0;c<s;c++)e.add(o[c])}return e}function yt(e,t,n=!1){let r=n?U.vincentyDistance:U.haversineDistance,o=[],s=[];for(let{point:l}of e)s.push(r(t,l));let c=Math.max(...s),i=0;for(let{docIDs:l}of e){let u=s[i],a=c-u+1;for(let f of l)o.push([f,a]);i++}return o.sort((l,u)=>u[1]-l[1]),o}function _n(e,t){let n=Object.keys(e);if(n.length!==1)return{isGeoOnly:!1};let r=n[0],o=e[r];if(typeof t.indexes[r]>"u")return{isGeoOnly:!1};let{type:s}=t.indexes[r];return s==="BKD"&&o&&("radius"in o||"polygon"in o)?{isGeoOnly:!0,geoProperty:r,geoOperation:o}:{isGeoOnly:!1}}function Tt(e,t){let n=e,r=_n(t,n);if(!r.isGeoOnly||!r.geoProperty||!r.geoOperation)return null;let{node:o}=n.indexes[r.geoProperty],s=r.geoOperation,c=o,i;if("radius"in s){let{value:l,coordinates:u,unit:a="m",inside:f=!0,highPrecision:d=!1}=s.radius,p=u,h=de(l,a);return i=c.searchByRadius(p,h,f,"asc",d),yt(i,p,d)}else if("polygon"in s){let{coordinates:l,inside:u=!0,highPrecision:a=!1}=s.polygon;i=c.searchByPolygon(l,u,"asc",a);let f=U.calculatePolygonCentroid(l);return yt(i,f,a)}return null}function Mn(e,t){e||(e=new Set);let n=Object.keys(t),r=n.length;for(let o=0;o<r;o++){let s=t[n[o]],c=s.length;for(let i=0;i<c;i++)e.add(s[i])}return e}function xt(e,t,n,r,o){let s={language:e.tokenizer.language,sharedInternalDocumentStore:t,enabled:!0,isSorted:!0,sortableProperties:[],sortablePropertiesWithTypes:{},sorts:{}};for(let[c,i]of Object.entries(n)){let l=`${o}${o?".":""}${c}`;if(!r.includes(l)){if(typeof i=="object"&&!Array.isArray(i)){let u=xt(e,t,i,r,l);X(s.sortableProperties,u.sortableProperties),s.sorts={...s.sorts,...u.sorts},s.sortablePropertiesWithTypes={...s.sortablePropertiesWithTypes,...u.sortablePropertiesWithTypes};continue}if(!M(i))switch(i){case"boolean":case"number":case"string":s.sortableProperties.push(l),s.sortablePropertiesWithTypes[l]=i,s.sorts[l]={docs:new Map,orderedDocsToRemove:new Map,orderedDocs:[],type:i};break;case"geopoint":case"enum":continue;case"enum[]":case"boolean[]":case"number[]":case"string[]":continue;default:throw I("INVALID_SORT_SCHEMA_TYPE",Array.isArray(i)?"array":i,l)}}}return s}function Ln(e,t,n,r){return r?.enabled!==!1?xt(e,t,n,(r||{}).unsortableProperties||[],""):{disabled:!0}}function Un(e,t,n,r){if(!e.enabled)return;e.isSorted=!1;let o=w(e.sharedInternalDocumentStore,n),s=e.sorts[t];s.orderedDocsToRemove.has(o)&&ve(e,t),s.docs.set(o,s.orderedDocs.length),s.orderedDocs.push([o,r])}function Dt(e){if(e.isSorted||!e.enabled)return;let t=Object.keys(e.sorts);for(let n of t)Fn(e,n);e.isSorted=!0}function Cn(e,t,n){return t[1].localeCompare(n[1],qe(e))}function kn(e,t){return e[1]-t[1]}function Bn(e,t){return t[1]?-1:1}function Fn(e,t){let n=e.sorts[t],r;switch(n.type){case"string":r=Cn.bind(null,e.language);break;case"number":r=kn.bind(null);break;case"boolean":r=Bn.bind(null);break}n.orderedDocs.sort(r);let o=n.orderedDocs.length;for(let s=0;s<o;s++){let c=n.orderedDocs[s][0];n.docs.set(c,s)}}function Vn(e){let t=Object.keys(e.sorts);for(let n of t)ve(e,n)}function ve(e,t){let n=e.sorts[t];n.orderedDocsToRemove.size&&(n.orderedDocs=n.orderedDocs.filter(r=>!n.orderedDocsToRemove.has(r[0])),n.orderedDocsToRemove.clear())}function zn(e,t,n){if(!e.enabled)return;let r=e.sorts[t],o=w(e.sharedInternalDocumentStore,n);r.docs.get(o)&&(r.docs.delete(o),r.orderedDocsToRemove.set(o,!0))}function Wn(e,t,n){if(!e.enabled)throw I("SORT_DISABLED");let r=n.property,o=n.order==="DESC",s=e.sorts[r];if(!s)throw I("UNABLE_TO_SORT_ON_UNKNOWN_FIELD",r,e.sortableProperties.join(", "));return ve(e,r),Dt(e),t.sort((c,i)=>{let l=s.docs.get(w(e.sharedInternalDocumentStore,c[0])),u=s.docs.get(w(e.sharedInternalDocumentStore,i[0])),a=typeof l<"u",f=typeof u<"u";return!a&&!f?0:a?f?o?u-l:l-u:-1:1}),t}function Gn(e){return e.enabled?e.sortableProperties:[]}function $n(e){return e.enabled?e.sortablePropertiesWithTypes:{}}function Yn(e,t){let n=t;if(!n.enabled)return{enabled:!1};let r=Object.keys(n.sorts).reduce((o,s)=>{let{docs:c,orderedDocs:i,type:l}=n.sorts[s];return o[s]={docs:new Map(Object.entries(c).map(([u,a])=>[+u,a])),orderedDocsToRemove:new Map,orderedDocs:i,type:l},o},{});return{sharedInternalDocumentStore:e,language:n.language,sortableProperties:n.sortableProperties,sortablePropertiesWithTypes:n.sortablePropertiesWithTypes,sorts:r,enabled:!0,isSorted:n.isSorted}}function jn(e){if(!e.enabled)return{enabled:!1};Vn(e),Dt(e);let t=Object.keys(e.sorts).reduce((n,r)=>{let{docs:o,orderedDocs:s,type:c}=e.sorts[r];return n[r]={docs:Object.fromEntries(o.entries()),orderedDocs:s,type:c},n},{});return{language:e.language,sortableProperties:e.sortableProperties,sortablePropertiesWithTypes:e.sortablePropertiesWithTypes,sorts:t,enabled:e.enabled,isSorted:e.isSorted}}function At(){return{create:Ln,insert:Un,remove:zn,save:jn,load:Yn,sortBy:Wn,getSortableProperties:Gn,getSortablePropertiesWithTypes:$n}}var Jn=[65,65,65,65,65,65,65,67,69,69,69,69,73,73,73,73,69,78,79,79,79,79,79,null,79,85,85,85,85,89,80,115,97,97,97,97,97,97,97,99,101,101,101,101,105,105,105,105,101,110,111,111,111,111,111,null,111,117,117,117,117,121,112,121,65,97,65,97,65,97,67,99,67,99,67,99,67,99,68,100,68,100,69,101,69,101,69,101,69,101,69,101,71,103,71,103,71,103,71,103,72,104,72,104,73,105,73,105,73,105,73,105,73,105,73,105,74,106,75,107,107,76,108,76,108,76,108,76,108,76,108,78,110,78,110,78,110,110,78,110,79,111,79,111,79,111,79,111,82,114,82,114,82,114,83,115,83,115,83,115,83,115,84,116,84,116,84,116,85,117,85,117,85,117,85,117,85,117,85,117,87,119,89,121,89,90,122,90,122,90,122,115];function Hn(e){return e<192||e>383?e:Jn[e-192]||e}function Nt(e){let t=[];for(let n=0;n<e.length;n++)t[n]=Hn(e.charCodeAt(n));return String.fromCharCode(...t)}var qn={ational:"ate",tional:"tion",enci:"ence",anci:"ance",izer:"ize",bli:"ble",alli:"al",entli:"ent",eli:"e",ousli:"ous",ization:"ize",ation:"ate",ator:"ate",alism:"al",iveness:"ive",fulness:"ful",ousness:"ous",aliti:"al",iviti:"ive",biliti:"ble",logi:"log"},Xn={icate:"ic",ative:"",alize:"al",iciti:"ic",ical:"ic",ful:"",ness:""},Zn="[^aeiou]",Ie="[aeiouy]",_=Zn+"[^aeiouy]*",oe=Ie+"[aeiou]*",Le="^("+_+")?"+oe+_,Qn="^("+_+")?"+oe+_+"("+oe+")?$",Se="^("+_+")?"+oe+_+oe+_,wt="^("+_+")?"+Ie;function Ot(e){let t,n,r,o,s,c;if(e.length<3)return e;let i=e.substring(0,1);if(i=="y"&&(e=i.toUpperCase()+e.substring(1)),r=/^(.+?)(ss|i)es$/,o=/^(.+?)([^s])s$/,r.test(e)?e=e.replace(r,"$1$2"):o.test(e)&&(e=e.replace(o,"$1$2")),r=/^(.+?)eed$/,o=/^(.+?)(ed|ing)$/,r.test(e)){let l=r.exec(e);r=new RegExp(Le),r.test(l[1])&&(r=/.$/,e=e.replace(r,""))}else o.test(e)&&(t=o.exec(e)[1],o=new RegExp(wt),o.test(t)&&(e=t,o=/(at|bl|iz)$/,s=new RegExp("([^aeiouylsz])\\1$"),c=new RegExp("^"+_+Ie+"[^aeiouwxy]$"),o.test(e)?e=e+"e":s.test(e)?(r=/.$/,e=e.replace(r,"")):c.test(e)&&(e=e+"e")));if(r=/^(.+?)y$/,r.test(e)&&(t=r.exec(e)?.[1],r=new RegExp(wt),t&&r.test(t)&&(e=t+"i")),r=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,r.test(e)){let l=r.exec(e);t=l?.[1],n=l?.[2],r=new RegExp(Le),t&&r.test(t)&&(e=t+qn[n])}if(r=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,r.test(e)){let l=r.exec(e);t=l?.[1],n=l?.[2],r=new RegExp(Le),t&&r.test(t)&&(e=t+Xn[n])}if(r=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,o=/^(.+?)(s|t)(ion)$/,r.test(e))t=r.exec(e)?.[1],r=new RegExp(Se),t&&r.test(t)&&(e=t);else if(o.test(e)){let l=o.exec(e);t=l?.[1]??""+l?.[2]??"",o=new RegExp(Se),o.test(t)&&(e=t)}return r=/^(.+?)e$/,r.test(e)&&(t=r.exec(e)?.[1],r=new RegExp(Se),o=new RegExp(Qn),s=new RegExp("^"+_+Ie+"[^aeiouwxy]$"),t&&(r.test(t)||o.test(t)&&!s.test(t))&&(e=t)),r=/ll$/,o=new RegExp(Se),r.test(e)&&o.test(e)&&(r=/.$/,e=e.replace(r,"")),i=="y"&&(e=i.toLowerCase()+e.substring(1)),e}function Ue(e,t,n=!0){let r=`${this.language}:${e}:${t}`;return n&&this.normalizationCache.has(r)?this.normalizationCache.get(r):this.stopWords?.includes(t)?(n&&this.normalizationCache.set(r,""),""):(this.stemmer&&!this.stemmerSkipProperties.has(e)&&(t=this.stemmer(t)),t=Nt(t),n&&this.normalizationCache.set(r,t),t)}function er(e){for(;e[e.length-1]==="";)e.pop();for(;e[0]==="";)e.shift();return e}function Et(e,t,n,r=!0){if(t&&t!==this.language)throw I("LANGUAGE_NOT_SUPPORTED",t);if(typeof e!="string")return[e];let o=this.normalizeToken.bind(this,n??""),s;if(n&&this.tokenizeSkipProperties.has(n))s=[o(e,r)];else{let i=He[this.language];s=e.toLowerCase().split(i).map(l=>o(l,r)).filter(Boolean)}let c=er(s);return this.allowDuplicates?c:Array.from(new Set(c))}function Ce(e={}){if(!e.language)e.language="english";else if(!q.includes(e.language))throw I("LANGUAGE_NOT_SUPPORTED",e.language);let t;if(e.stemming||e.stemmer&&!("stemming"in e))if(e.stemmer){if(typeof e.stemmer!="function")throw I("INVALID_STEMMER_FUNCTION_TYPE");t=e.stemmer}else if(e.language==="english")t=Ot;else throw I("MISSING_STEMMER",e.language);let n;if(e.stopWords!==!1){if(n=[],Array.isArray(e.stopWords))n=e.stopWords;else if(typeof e.stopWords=="function")n=e.stopWords(n);else if(e.stopWords)throw I("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");if(!Array.isArray(n))throw I("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");for(let o of n)if(typeof o!="string")throw I("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY")}let r={tokenize:Et,language:e.language,stemmer:t,stemmerSkipProperties:new Set(e.stemmerSkipProperties?[e.stemmerSkipProperties].flat():[]),tokenizeSkipProperties:new Set(e.tokenizeSkipProperties?[e.tokenizeSkipProperties].flat():[]),stopWords:n,allowDuplicates:!!e.allowDuplicates,normalizeToken:Ue,normalizationCache:new Map};return r.tokenize=Et.bind(r),r.normalizeToken=Ue,r}function nr(e){return{sharedInternalDocumentStore:e,rules:new Map}}function rr(e,t){if(e.rules.has(t.id))throw new Error(`PINNING_RULE_ALREADY_EXISTS: A pinning rule with id "${t.id}" already exists. Use updateRule to modify it.`);e.rules.set(t.id,t)}function or(e,t){if(!e.rules.has(t.id))throw new Error(`PINNING_RULE_NOT_FOUND: Cannot update pinning rule with id "${t.id}" because it does not exist. Use addRule to create it.`);e.rules.set(t.id,t)}function sr(e,t){return e.rules.delete(t)}function ir(e,t){return e.rules.get(t)}function cr(e){return Array.from(e.rules.values())}function lr(e,t){let n=e.toLowerCase().trim(),r=t.pattern.toLowerCase().trim();switch(t.anchoring){case"is":return n===r;case"starts_with":return n.startsWith(r);case"contains":return n.includes(r);default:return!1}}function ur(e,t){return e?t.conditions.every(n=>lr(e,n)):!1}function ke(e,t){if(!t)return[];let n=[];for(let r of e.rules.values())ur(t,r)&&n.push(r);return n}function fr(e,t){let n=t;return{sharedInternalDocumentStore:e,rules:new Map(n?.rules??[])}}function ar(e){return{rules:Array.from(e.rules.entries())}}function Rt(){return{create:nr,addRule:rr,updateRule:or,removeRule:sr,getRule:ir,getAllRules:cr,getMatchingRules:ke,load:fr,save:ar}}function dr(e){let t={formatElapsedTime:ot,getDocumentIndexId:st,getDocumentProperties:ae,validateSchema:Ee};for(let n of _e){let r=n;if(e[r]){if(typeof e[r]!="function")throw I("COMPONENT_MUST_BE_FUNCTION",r)}else e[r]=t[r]}for(let n of Object.keys(e))if(!at.includes(n)&&!_e.includes(n))throw I("UNSUPPORTED_COMPONENT",n)}function Be({schema:e,sort:t,language:n,components:r,id:o,plugins:s}){r||(r={});for(let S of s??[]){if(!("getComponents"in S)||typeof S.getComponents!="function")continue;let b=S.getComponents(e),T=Object.keys(b);for(let x of T)if(r[x])throw I("PLUGIN_COMPONENT_CONFLICT",x,S.name);r={...r,...b}}o||(o=Z());let c=r.tokenizer,i=r.index,l=r.documentsStore,u=r.sorter,a=r.pinning;if(c?c.tokenize?c=c:c=Ce(c):c=Ce({language:n??"english"}),r.tokenizer&&n)throw I("NO_LANGUAGE_WITH_CUSTOM_TOKENIZER");let f=ct();i||(i=bt()),u||(u=At()),l||(l=lt()),a||(a=Rt()),dr(r);let{getDocumentProperties:d,getDocumentIndexId:p,validateSchema:h,formatElapsedTime:y}=r,g={data:{},caches:{},schema:e,tokenizer:c,index:i,sorter:u,documentsStore:l,pinning:a,internalDocumentIDStore:f,getDocumentProperties:d,getDocumentIndexId:p,validateSchema:h,beforeInsert:[],afterInsert:[],beforeRemove:[],afterRemove:[],beforeUpdate:[],afterUpdate:[],beforeUpsert:[],afterUpsert:[],beforeSearch:[],afterSearch:[],beforeInsertMultiple:[],afterInsertMultiple:[],beforeRemoveMultiple:[],afterRemoveMultiple:[],beforeUpdateMultiple:[],afterUpdateMultiple:[],beforeUpsertMultiple:[],afterUpsertMultiple:[],afterCreate:[],formatElapsedTime:y,id:o,plugins:s,version:pr()};g.data={index:g.index.create(g,f,e),docs:g.documentsStore.create(g,f),sorting:g.sorter.create(g,f,e,t),pinning:g.pinning.create(f)};for(let S of ut)g[S]=(g[S]??[]).concat(ft(g,S));let m=g.afterCreate;return m&&dt(m,g),g}function pr(){return"{{VERSION}}"}function Fe(e){return e.documentsStore.count(e.data.docs)}function se(e,t,n,r,o){let s=e.validateSchema(t,e.schema);if(s)throw I("SCHEMA_VALIDATION_FAILURE",s);return E(e.beforeInsert)||E(e.afterInsert)||E(e.index.beforeInsert)||E(e.index.insert)||E(e.index.afterInsert)?yr(e,t,n,r,o):Sr(e,t,n,r,o)}var gr=new Set(["enum","enum[]"]),mr=new Set(["string","number"]);async function yr(e,t,n,r,o){let{index:s,docs:c}=e.data,i=e.getDocumentIndexId(t);if(typeof i!="string")throw I("DOCUMENT_ID_MUST_BE_STRING",typeof i);let l=w(e.internalDocumentIDStore,i);if(r||await L(e.beforeInsert,e,i,t),!e.documentsStore.store(c,i,l,t))throw I("DOCUMENT_ALREADY_EXISTS",i);let u=e.documentsStore.count(c),a=e.index.getSearchableProperties(s),f=e.index.getSearchablePropertiesWithTypes(s),d=e.getDocumentProperties(t,a);for(let[p,h]of Object.entries(d)){if(typeof h>"u")continue;let y=typeof h,g=f[p];Pt(y,g,p,h)}return await Ir(e,i,a,d,u,n,t,o),r||await L(e.afterInsert,e,i,t),i}function Sr(e,t,n,r,o){let{index:s,docs:c}=e.data,i=e.getDocumentIndexId(t);if(typeof i!="string")throw I("DOCUMENT_ID_MUST_BE_STRING",typeof i);let l=w(e.internalDocumentIDStore,i);if(r||L(e.beforeInsert,e,i,t),!e.documentsStore.store(c,i,l,t))throw I("DOCUMENT_ALREADY_EXISTS",i);let u=e.documentsStore.count(c),a=e.index.getSearchableProperties(s),f=e.index.getSearchablePropertiesWithTypes(s),d=e.getDocumentProperties(t,a);for(let[p,h]of Object.entries(d)){if(typeof h>"u")continue;let y=typeof h,g=f[p];Pt(y,g,p,h)}return br(e,i,a,d,u,n,t,o),r||L(e.afterInsert,e,i,t),i}function Pt(e,t,n,r){if(!(it(t)&&typeof r=="object"&&typeof r.lon=="number"&&typeof r.lat=="number")&&!(M(t)&&Array.isArray(r))&&!(W(t)&&Array.isArray(r))&&!(gr.has(t)&&mr.has(e))&&e!==t)throw I("INVALID_DOCUMENT_PROPERTY",n,t,e)}async function Ir(e,t,n,r,o,s,c,i){for(let a of n){let f=r[a];if(typeof f>"u")continue;let d=e.index.getSearchablePropertiesWithTypes(e.data.index)[a];await e.index.beforeInsert?.(e.data.index,a,t,f,d,s,e.tokenizer,o);let p=e.internalDocumentIDStore.idToInternalId.get(t);await e.index.insert(e.index,e.data.index,a,t,p,f,d,s,e.tokenizer,o,i),await e.index.afterInsert?.(e.data.index,a,t,f,d,s,e.tokenizer,o)}let l=e.sorter.getSortableProperties(e.data.sorting),u=e.getDocumentProperties(c,l);for(let a of l){let f=u[a];if(typeof f>"u")continue;let d=e.sorter.getSortablePropertiesWithTypes(e.data.sorting)[a];e.sorter.insert(e.data.sorting,a,t,f,d,s)}}function br(e,t,n,r,o,s,c,i){for(let a of n){let f=r[a];if(typeof f>"u")continue;let d=e.index.getSearchablePropertiesWithTypes(e.data.index)[a],p=w(e.internalDocumentIDStore,t);e.index.beforeInsert?.(e.data.index,a,t,f,d,s,e.tokenizer,o),e.index.insert(e.index,e.data.index,a,t,p,f,d,s,e.tokenizer,o,i),e.index.afterInsert?.(e.data.index,a,t,f,d,s,e.tokenizer,o)}let l=e.sorter.getSortableProperties(e.data.sorting),u=e.getDocumentProperties(c,l);for(let a of l){let f=u[a];if(typeof f>"u")continue;let d=e.sorter.getSortablePropertiesWithTypes(e.data.sorting)[a];e.sorter.insert(e.data.sorting,a,t,f,d,s)}}function Ve(e,t,n,r,o,s){return E(e.afterInsertMultiple)||E(e.beforeInsertMultiple)||E(e.index.beforeInsert)||E(e.index.insert)||E(e.index.afterInsert)?Tr(e,t,n,r,o,s):xr(e,t,n,r,o,s)}async function Tr(e,t,n=1e3,r,o,s=0){let c=[],i=async u=>{let a=Math.min(u+n,t.length),f=t.slice(u,a);for(let d of f){let p={avlRebalanceThreshold:f.length},h=await se(e,d,r,o,p);c.push(h)}return a};return await(async()=>{let u=0;for(;u<t.length;){let a=Date.now();if(u=await i(u),s>0){let f=Date.now()-a,d=s-f;d>0&&Oe(d)}}})(),o||await G(e.afterInsertMultiple,e,t),c}function xr(e,t,n=1e3,r,o,s=0){let c=[],i=0;function l(){let a=t.slice(i*n,(i+1)*n);if(a.length===0)return!1;for(let f of a){let d={avlRebalanceThreshold:a.length},p=se(e,f,r,o,d);c.push(p)}return i++,!0}function u(){let a=Date.now();for(;l();)if(s>0){let d=Date.now()-a;if(d>=s){let p=s-d%s;p>0&&Oe(p)}}}return u(),o||G(e.afterInsertMultiple,e,t),c}var be="fulltext",ze="hybrid",We="vector";function Dr(e,t){return e[1]-t[1]}function Ar(e,t){return t[1]-e[1]}function Nr(e="desc"){return e.toLowerCase()==="asc"?Dr:Ar}function j(e,t,n){let r={},o=t.map(([u])=>u),s=e.documentsStore.getMultiple(e.data.docs,o),c=Object.keys(n),i=e.index.getSearchablePropertiesWithTypes(e.data.index);for(let u of c){let a;if(i[u]==="number"){let{ranges:f}=n[u],d=f.length,p=Array.from({length:d});for(let h=0;h<d;h++){let y=f[h];p[h]=[`${y.from}-${y.to}`,0]}a=Object.fromEntries(p)}r[u]={count:0,values:a??{}}}let l=s.length;for(let u=0;u<l;u++){let a=s[u];for(let f of c){let d=f.includes(".")?V(a,f):a[f],p=i[f],h=r[f].values;switch(p){case"number":{let y=n[f].ranges;_t(y,h)(d);break}case"number[]":{let y=new Set,g=n[f].ranges,m=_t(g,h,y);for(let S of d)m(S);break}case"boolean":case"enum":case"string":{Mt(h,p)(d);break}case"boolean[]":case"enum[]":case"string[]":{let m=Mt(h,p==="boolean[]"?"boolean":"string",new Set);for(let S of d)m(S);break}default:throw I("FACET_NOT_SUPPORTED",p)}}}for(let u of c){let a=r[u];if(a.count=Object.keys(a.values).length,i[u]==="string"){let f=n[u],d=Nr(f.sort);a.values=Object.fromEntries(Object.entries(a.values).sort(d).slice(f.offset??0,f.limit??10))}}return r}function _t(e,t,n){return r=>{for(let o of e){let s=`${o.from}-${o.to}`;n?.has(s)||r>=o.from&&r<=o.to&&(t[s]===void 0?t[s]=1:(t[s]++,n?.add(s)))}}}function Mt(e,t,n){let r=t==="boolean"?"false":"";return o=>{let s=o?.toString()??r;n?.has(s)||(e[s]=(e[s]??0)+1,n?.add(s))}}var wr={reducer:(e,t,n,r)=>(t[r]=n,t),getInitialValue:e=>Array.from({length:e})},vt=["string","number","boolean"];function K(e,t,n){let r=n.properties,o=r.length,s=e.index.getSearchablePropertiesWithTypes(e.data.index);for(let m=0;m<o;m++){let S=r[m];if(typeof s[S]>"u")throw I("UNKNOWN_GROUP_BY_PROPERTY",S);if(!vt.includes(s[S]))throw I("INVALID_GROUP_BY_PROPERTY",S,vt.join(", "),s[S])}let c=t.map(([m])=>v(e.internalDocumentIDStore,m)),i=e.documentsStore.getMultiple(e.data.docs,c),l=i.length,u=n.maxResult||Number.MAX_SAFE_INTEGER,a=[],f={};for(let m=0;m<o;m++){let S=r[m],b={property:S,perValue:{}},T=new Set;for(let x=0;x<l;x++){let N=i[x],O=V(N,S);if(typeof O>"u")continue;let A=typeof O!="boolean"?O:""+O,R=b.perValue[A]??{indexes:[],count:0};R.count>=u||(R.indexes.push(x),R.count++,b.perValue[A]=R,T.add(O))}a.push(Array.from(T)),f[S]=b}let d=Lt(a),p=d.length,h=[];for(let m=0;m<p;m++){let S=d[m],b=S.length,T={values:[],indexes:[]},x=[];for(let N=0;N<b;N++){let O=S[N],A=r[N];x.push(f[A].perValue[typeof O!="boolean"?O:""+O].indexes),T.values.push(O)}T.indexes=rt(x).sort((N,O)=>N-O),T.indexes.length!==0&&h.push(T)}let y=h.length,g=Array.from({length:y});for(let m=0;m<y;m++){let S=h[m],b=n.reduce||wr,T=S.indexes.map(A=>({id:c[A],score:t[A][1],document:i[A]})),x=b.reducer.bind(null,S.values),N=b.getInitialValue(S.indexes.length),O=T.reduce(x,N);g[m]={values:S.values,result:O}}return g}function Lt(e,t=0){if(t+1===e.length)return e[t].map(s=>[s]);let n=e[t],r=Lt(e,t+1),o=[];for(let s of n)for(let c of r){let i=[s];X(i,c),o.push(i)}return o}function J(e,t,n,r){let o=ke(t,r);if(o.length===0)return n;let s=o.flatMap(g=>g.consequence.promote);s.sort((g,m)=>g.position-m.position);let c=new Set,i=new Map,l=new Set;for(let g of s){let m=w(e.internalDocumentIDStore,g.doc_id);if(m!==void 0){if(i.has(m)){let S=i.get(m);g.position<S&&i.set(m,g.position);continue}l.has(g.position)||(c.add(m),i.set(m,g.position),l.add(g.position))}}if(i.size===0)return n;let u=n.filter(([g])=>!c.has(g)),a=1e6,f=[];for(let[g,m]of i.entries())n.find(([b])=>b===g)?f.push([g,a-m]):e.documentsStore.get(e.data.docs,g)&&f.push([g,0]);f.sort((g,m)=>{let S=i.get(g[0])??1/0,b=i.get(m[0])??1/0;return S-b});let d=[],p=new Map;for(let g of f){let m=i.get(g[0]);p.set(m,g)}let h=0,y=0;for(;y<u.length+f.length;)if(p.has(y))d.push(p.get(y)),y++;else if(h<u.length)d.push(u[h]),h++,y++;else break;for(let[g,m]of p.entries())g>=d.length&&d.push(m);return d}function $e(e,t,n){let{term:r,properties:o}=t,s=e.data.index,c=e.caches.propertiesToSearch;if(!c){let f=e.index.getSearchablePropertiesWithTypes(s);c=e.index.getSearchableProperties(s),c=c.filter(d=>f[d].startsWith("string")),e.caches.propertiesToSearch=c}if(o&&o!=="*"){for(let f of o)if(!c.includes(f))throw I("UNKNOWN_INDEX",f,c.join(", "));c=c.filter(f=>o.includes(f))}let i=Object.keys(t.where??{}).length>0,l;i&&(l=e.index.searchByWhereClause(s,e.tokenizer,t.where,n));let u,a=t.threshold!==void 0&&t.threshold!==null?t.threshold:1;if(r||o){let f=Fe(e);if(u=e.index.search(s,r||"",e.tokenizer,n,c,t.exact||!1,t.tolerance||0,t.boost||{},Rr(t.relevance),f,l,a),t.exact&&r){let d=r.trim().split(/\s+/);u=u.filter(([p])=>{let h=e.documentsStore.get(e.data.docs,p);if(!h)return!1;for(let y of c){let g=Er(h,y);if(typeof g=="string"&&d.every(S=>new RegExp(`\\b${Or(S)}\\b`).test(g)))return!0}return!1})}}else if(i){let f=Tt(s,t.where);f?u=f:u=(l?Array.from(l):[]).map(p=>[+p,0])}else u=Object.keys(e.documentsStore.getAll(e.data.docs)).map(d=>[+d,0]);return u}function Or(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Er(e,t){let n=t.split("."),r=e;for(let o of n)if(r&&typeof r=="object"&&o in r)r=r[o];else return;return r}function Ut(e,t,n){let r=P();function o(){let i=Object.keys(e.data.index.vectorIndexes),l=t.facets&&Object.keys(t.facets).length>0,{limit:u=10,offset:a=0,distinctOn:f,includeVectors:d=!1}=t,p=t.preflight===!0,h=$e(e,t,n);if(t.sortBy)if(typeof t.sortBy=="function"){let m=h.map(([T])=>T),b=e.documentsStore.getMultiple(e.data.docs,m).map((T,x)=>[h[x][0],h[x][1],T]);b.sort(t.sortBy),h=b.map(([T,x])=>[T,x])}else h=e.sorter.sortBy(e.data.sorting,h,t.sortBy).map(([m,S])=>[w(e.internalDocumentIDStore,m),S]);else h=h.sort(fe);h=J(e,e.data.pinning,h,t.term);let y;p||(y=f?Ct(e,h,a,u,f):Te(e,h,a,u));let g={elapsed:{formatted:"",raw:0},hits:[],count:h.length};if(typeof y<"u"&&(g.hits=y.filter(Boolean),d||pe(g,i)),l){let m=j(e,h,t.facets);g.facets=m}return t.groupBy&&(g.groups=K(e,h,t.groupBy)),g.elapsed=e.formatElapsedTime(P()-r),g}async function s(){e.beforeSearch&&await Y(e.beforeSearch,e,t,n);let i=o();return e.afterSearch&&await $(e.afterSearch,e,t,n,i),i}return e.beforeSearch?.length||e.afterSearch?.length?s():o()}var Ge={k:1.2,b:.75,d:.5};function Rr(e){let t=e??{};return t.k=t.k??Ge.k,t.b=t.b??Ge.b,t.d=t.d??Ge.d,t}function Ye(e,t,n){let r=t.vector;if(r&&(!("value"in r)||!("property"in r)))throw I("INVALID_VECTOR_INPUT",Object.keys(r).join(", "));let o=e.data.index.vectorIndexes[r.property];if(!o)throw I("UNKNOWN_VECTOR_PROPERTY",r.property);let s=o.node.size;if(r?.value.length!==s)throw r?.property===void 0||r?.value.length===void 0?I("INVALID_INPUT_VECTOR","undefined",s,"undefined"):I("INVALID_INPUT_VECTOR",r.property,s,r.value.length);let c=e.data.index,i;return Object.keys(t.where??{}).length>0&&(i=e.index.searchByWhereClause(c,e.tokenizer,t.where,n)),o.node.find(r.value,t.similarity??.8,i)}function je(e,t,n="english"){let r=P();function o(){let i=Ye(e,t,n).sort(fe);i=J(e,e.data.pinning,i,void 0);let l=[];t.facets&&Object.keys(t.facets).length>0&&(l=j(e,i,t.facets));let a=t.vector.property,f=t.includeVectors??!1,d=t.limit??10,p=t.offset??0,h=Array.from({length:d});for(let S=0;S<d;S++){let b=i[S+p];if(!b)break;let T=e.data.docs.docs[b[0]];if(T){f||(T[a]=null);let x={id:v(e.internalDocumentIDStore,b[0]),score:b[1],document:T};h[S]=x}}let y=[];t.groupBy&&(y=K(e,i,t.groupBy));let m=P()-r;return{count:i.length,hits:h.filter(Boolean),elapsed:{raw:Number(m),formatted:k(m)},...l?{facets:l}:{},...y?{groups:y}:{}}}async function s(){e.beforeSearch&&await Y(e.beforeSearch,e,t,n);let i=o();return e.afterSearch&&await $(e.afterSearch,e,t,n,i),i}return e.beforeSearch?.length||e.afterSearch?.length?s():o()}function _r(e,t,n){let r=Mr($e(e,t,n)),o=Ye(e,t,n),s=t.hybridWeights;return Lr(r,o,t.term??"",s)}function Bt(e,t,n){let r=P();function o(){let i=_r(e,t,n);i=J(e,e.data.pinning,i,t.term);let l;t.facets&&Object.keys(t.facets).length>0&&(l=j(e,i,t.facets));let a;t.groupBy&&(a=K(e,i,t.groupBy));let f=t.offset??0,d=t.limit??10,p=Te(e,i,f,d).filter(Boolean),h=P(),y={count:i.length,elapsed:{raw:Number(h-r),formatted:k(h-r)},hits:p,...l?{facets:l}:{},...a?{groups:a}:{}};if(!(t.includeVectors??!1)){let m=Object.keys(e.data.index.vectorIndexes);pe(y,m)}return y}async function s(){e.beforeSearch&&await Y(e.beforeSearch,e,t,n);let i=o();return e.afterSearch&&await $(e.afterSearch,e,t,n,i),i}return e.beforeSearch?.length||e.afterSearch?.length?s():o()}function Ke(e){return e[1]}function Mr(e){let t=Math.max.apply(Math,e.map(Ke));return e.map(([n,r])=>[n,r/t])}function kt(e,t){return e/t}function vr(e,t){return(n,r)=>n*e+r*t}function Lr(e,t,n,r){let o=Math.max.apply(Math,e.map(Ke)),s=Math.max.apply(Math,t.map(Ke)),c=r&&r.text&&r.vector,{text:i,vector:l}=c?r:Ur(n),u=new Map,a=e.length,f=vr(i,l);for(let p=0;p<a;p++){let[h,y]=e[p],g=kt(y,o),m=f(g,0);u.set(h,m)}let d=t.length;for(let p=0;p<d;p++){let[h,y]=t[p],g=kt(y,s),m=u.get(h)??0;u.set(h,m+f(0,g))}return[...u].sort((p,h)=>h[1]-p[1])}function Ur(e){return{text:.5,vector:.5}}function xe(e,t,n){let r=t.mode??be;if(r===be)return Ut(e,t,n);if(r===We)return je(e,t);if(r===ze)return Bt(e,t);throw I("INVALID_SEARCH_MODE",r)}function Ct(e,t,n,r,o){let s=e.data.docs,c=new Map,i=[],l=new Set,u=t.length,a=0;for(let f=0;f<u;f++){let d=t[f];if(typeof d>"u")continue;let[p,h]=d;if(l.has(p))continue;let y=e.documentsStore.get(s,p),g=V(y,o);if(!(typeof g>"u"||c.has(g))&&(c.set(g,!0),a++,!(a<=n)&&(i.push({id:v(e.internalDocumentIDStore,p),score:h,document:y}),l.add(p),a>=n+r)))break}return i}function Te(e,t,n,r){let o=e.data.docs,s=Array.from({length:r}),c=new Set;for(let i=n;i<r+n;i++){let l=t[i];if(typeof l>"u")break;let[u,a]=l;if(!c.has(u)){let f=e.documentsStore.get(o,u);s[i]={id:v(e.internalDocumentIDStore,u),score:a,document:f},c.add(u)}}return s}return Yt(Wr);})();