@midsummer-ai/sdk 0.1.0-next.901 → 0.1.0-staging.3100

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 (40) hide show
  1. package/auth-1W-SzpD3.mjs +441 -0
  2. package/build-DQo-JrlN.d.mts +120 -0
  3. package/bytes-C2pcyl9u.mjs +280 -0
  4. package/{connection-CDk7H1FL.mjs → connection-Cu2GSOaR.mjs} +171 -31
  5. package/database/build.d.mts +2 -2
  6. package/database/build.mjs +1404 -117
  7. package/database/client.d.mts +85 -9
  8. package/database/client.mjs +550 -32
  9. package/database/contract.d.mts +92 -2
  10. package/database/contract.mjs +2179 -3
  11. package/database/errors.d.mts +1 -22
  12. package/database/react.d.mts +133 -0
  13. package/database/react.mjs +488 -0
  14. package/database/server.d.mts +2 -3
  15. package/database/server.mjs +3 -320
  16. package/database/stand-in.d.mts +95 -9
  17. package/database/stand-in.mjs +1436 -116
  18. package/errors-x2vXKi0u.d.mts +25 -0
  19. package/index-DNNXNny7.d.mts +410 -0
  20. package/key-BrRdFY-n.mjs +11 -0
  21. package/package.json +114 -1
  22. package/schema-CTHQMRsW.mjs +217 -0
  23. package/server-B5HK2Ou9.d.mts +574 -0
  24. package/server-EDRbF2u-.mjs +1893 -0
  25. package/{store-BzI9at5x.mjs → store-lIZ5GxVv.mjs} +1 -1
  26. package/{tabs-D-P8_ci_.mjs → tabs-zCh8kceo.mjs} +1 -1
  27. package/vector/contract.d.mts +1 -1
  28. package/vector/contract.mjs +773 -1
  29. package/vector/index.d.mts +2 -2
  30. package/vector/index.mjs +71 -3
  31. package/vector/stand-in.d.mts +1 -1
  32. package/vector/stand-in.mjs +326 -23
  33. package/vector/wire.d.mts +11 -2
  34. package/vector/wire.mjs +179 -14
  35. package/build-SQ44jwSa.d.mts +0 -41
  36. package/index-DdoK0y7D.d.mts +0 -192
  37. package/schema-BF-Y1EVu.mjs +0 -142
  38. package/schema-DS8x1Dn8.mjs +0 -115
  39. package/schema-f7E9uzUn.d.mts +0 -74
  40. package/server-C7O7CICU.d.mts +0 -182
@@ -1,2 +1,2 @@
1
- import { C as MAX_TOP_K, D as vectorErrorCodes, E as VectorErrorCode, S as MAX_TEXT, T as VectorError, _ as embedded, a as Match, b as MAX_DIMENSION, c as Namespace, d as TextVector, f as ValuesEngine, g as VectorEngine, h as VectorDb, i as Filter, l as NamespaceInfo, m as VectorControl, n as Consistency, o as MetadataValue, p as Vector, r as EngineQuery, s as Metric, t as Condition, u as QueryOptions, v as vectorDb, w as MAX_VALUE, x as MAX_METADATA_BYTES, y as MAX_BATCH } from "../index-DdoK0y7D.mjs";
2
- export { Condition, Consistency, EngineQuery, Filter, MAX_BATCH, MAX_DIMENSION, MAX_METADATA_BYTES, MAX_TEXT, MAX_TOP_K, MAX_VALUE, Match, MetadataValue, Metric, Namespace, NamespaceInfo, QueryOptions, TextVector, ValuesEngine, Vector, VectorControl, VectorDb, VectorEngine, VectorError, type VectorErrorCode, embedded, vectorDb, vectorErrorCodes };
1
+ import { A as VectorControl, B as MAX_TEXT, C as QueryOptions, D as ValuesEngine, E as TextVector, F as MAX_BATCH, G as vectorErrorCodes, H as MAX_VALUE, I as MAX_DIMENSION, L as MAX_FULL_TEXT, M as VectorEngine, N as embedded, O as ValuesMultiQuery, P as vectorDb, R as MAX_METADATA_BYTES, S as NamespaceInfo, T as TextSearchOptions, U as VectorError, V as MAX_TOP_K, W as VectorErrorCode, _ as Metric, a as Consistency, b as MultiQueryResult, c as EngineMultiQuery, d as EngineTextSearch, f as Filter, g as MetadataValue, h as Match, i as Condition, j as VectorDb, k as Vector, l as EnginePart, m as Listed, n as AggregateGroup, o as EngineAggregate, p as ListOptions, r as AggregateOptions, s as EngineList, t as Aggregate, u as EngineQuery, v as MultiQueryOptions, w as Scalar, x as Namespace, y as MultiQueryPart, z as MAX_QUERIES } from "../index-DNNXNny7.mjs";
2
+ export { Aggregate, AggregateGroup, AggregateOptions, Condition, Consistency, EngineAggregate, EngineList, EngineMultiQuery, EnginePart, EngineQuery, EngineTextSearch, Filter, ListOptions, Listed, MAX_BATCH, MAX_DIMENSION, MAX_FULL_TEXT, MAX_METADATA_BYTES, MAX_QUERIES, MAX_TEXT, MAX_TOP_K, MAX_VALUE, Match, MetadataValue, Metric, MultiQueryOptions, MultiQueryPart, MultiQueryResult, Namespace, NamespaceInfo, QueryOptions, Scalar, TextSearchOptions, TextVector, ValuesEngine, ValuesMultiQuery, Vector, VectorControl, VectorDb, VectorEngine, VectorError, type VectorErrorCode, embedded, vectorDb, vectorErrorCodes };
package/vector/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as MAX_TEXT, c as NamespaceName, d as Vectors, f as checked, i as MAX_METADATA_BYTES, l as Query, m as vectorErrorCodes, n as MAX_BATCH, o as MAX_TOP_K, p as VectorError, r as MAX_DIMENSION, s as MAX_VALUE, t as Ids } from "../schema-DS8x1Dn8.mjs";
1
+ import { a as MAX_DIMENSION, b as VectorError, c as MAX_QUERIES, d as MAX_VALUE, f as MultiQuery, g as TextSearch, i as MAX_BATCH, l as MAX_TEXT, m as Query, n as Ids, o as MAX_FULL_TEXT, p as NamespaceName, r as List, s as MAX_METADATA_BYTES, t as Aggregation, u as MAX_TOP_K, v as Vectors, x as vectorErrorCodes, y as checked } from "../schema-CTHQMRsW.mjs";
2
2
  //#region src/vector/index.ts
3
3
  /**
4
4
  * Vector DB: a Team's Vectors in Vector namespaces, searched by closeness and filtered by their
@@ -20,6 +20,12 @@ import { a as MAX_TEXT, c as NamespaceName, d as Vectors, f as checked, i as MAX
20
20
  * const [intro] = await docs.fetch(["intro"])
21
21
  * await docs.delete(["intro"])
22
22
  *
23
+ * // By metadata alone, by words, several at once, and counted.
24
+ * const newest = await docs.list({ orderBy: [["year", "desc"]], topK: 5 })
25
+ * const words = await docs.textSearch("reset password", { field: "title", topK: 5 }) // `title` made full text
26
+ * const { fused } = await docs.multiQuery([{ vector: [0.1, 0.2, 0.25] }, { textSearch: "reset password", field: "title" }], { fuse: { rrf: {} } })
27
+ * const perLang = await docs.aggregate({ aggregates: { n: ["count"] }, groupBy: ["lang"] })
28
+ *
23
29
  * In tests and `midsummer dev`, `standIn()` from `@midsummer-ai/sdk/vector/stand-in` keeps Vectors in
24
30
  * memory. Each is held to the cases in `@midsummer-ai/sdk/vector/contract`; a behaviour that is not a
25
31
  * case there is not promised.
@@ -61,6 +67,52 @@ function vectorDb(engine) {
61
67
  },
62
68
  async describe() {
63
69
  return engine.describe(name);
70
+ },
71
+ async list(options) {
72
+ return engine.list(name, checked(List, {
73
+ orderBy: options.orderBy,
74
+ topK: options.topK ?? 10,
75
+ includeValues: options.includeValues ?? false,
76
+ includeMetadata: options.includeMetadata ?? false,
77
+ ...options.filter !== void 0 ? { filter: options.filter } : {}
78
+ }));
79
+ },
80
+ async textSearch(words, options) {
81
+ return engine.textSearch(name, checked(TextSearch, {
82
+ words,
83
+ field: options.field,
84
+ topK: options.topK ?? 10,
85
+ includeValues: options.includeValues ?? false,
86
+ includeMetadata: options.includeMetadata ?? false,
87
+ ...options.filter !== void 0 ? { filter: options.filter } : {}
88
+ }));
89
+ },
90
+ async multiQuery(queries, options = {}) {
91
+ const rrf = options.fuse?.rrf;
92
+ return engine.multiQuery(name, checked(MultiQuery, {
93
+ queries: queries.map((part) => ({
94
+ ..."textSearch" in part ? {
95
+ textSearch: part.textSearch,
96
+ field: part.field
97
+ } : typeof part.vector === "string" ? { text: part.vector } : { vector: part.vector },
98
+ topK: part.topK ?? 10,
99
+ ...part.filter !== void 0 ? { filter: part.filter } : {}
100
+ })),
101
+ ...rrf ? { fuse: {
102
+ k: rrf.k ?? 60,
103
+ weights: rrf.weights ?? queries.map(() => 1)
104
+ } } : {},
105
+ topK: options.topK ?? 10,
106
+ includeMetadata: options.includeMetadata ?? false
107
+ }));
108
+ },
109
+ async aggregate(options) {
110
+ return engine.aggregate(name, checked(Aggregation, {
111
+ aggregates: options.aggregates,
112
+ groupBy: options.groupBy ?? [],
113
+ limit: options.limit ?? 1e3,
114
+ ...options.filter !== void 0 ? { filter: options.filter } : {}
115
+ }));
64
116
  }
65
117
  };
66
118
  } };
@@ -101,8 +153,24 @@ function embedded(engine, embed) {
101
153
  });
102
154
  },
103
155
  fetch: (namespace, ids) => engine.fetch(namespace, ids),
104
- delete: (namespace, ids) => engine.delete(namespace, ids)
156
+ delete: (namespace, ids) => engine.delete(namespace, ids),
157
+ list: (namespace, list) => engine.list(namespace, list),
158
+ textSearch: (namespace, search) => engine.textSearch(namespace, search),
159
+ async multiQuery(namespace, multi) {
160
+ const texts = multi.queries.flatMap((part) => "text" in part ? [part.text] : []);
161
+ const embeddings = texts.length ? await values(namespace, texts) : [];
162
+ let next = 0;
163
+ return engine.multiQuery(namespace, {
164
+ ...multi,
165
+ queries: multi.queries.map((part) => "text" in part ? {
166
+ vector: embeddings[next++],
167
+ topK: part.topK,
168
+ ...part.filter !== void 0 ? { filter: part.filter } : {}
169
+ } : part)
170
+ });
171
+ },
172
+ aggregate: (namespace, aggregate) => engine.aggregate(namespace, aggregate)
105
173
  };
106
174
  }
107
175
  //#endregion
108
- export { MAX_BATCH, MAX_DIMENSION, MAX_METADATA_BYTES, MAX_TEXT, MAX_TOP_K, MAX_VALUE, VectorError, embedded, vectorDb, vectorErrorCodes };
176
+ export { MAX_BATCH, MAX_DIMENSION, MAX_FULL_TEXT, MAX_METADATA_BYTES, MAX_QUERIES, MAX_TEXT, MAX_TOP_K, MAX_VALUE, VectorError, embedded, vectorDb, vectorErrorCodes };
@@ -1,4 +1,4 @@
1
- import { g as VectorEngine, m as VectorControl } from "../index-DdoK0y7D.mjs";
1
+ import { A as VectorControl, M as VectorEngine } from "../index-DNNXNny7.mjs";
2
2
  //#region src/vector/stand-in.d.ts
3
3
  /**
4
4
  * A text's Stand-in embedding of `dimension` numbers: each word (letters and digits, in lower case)
@@ -1,4 +1,4 @@
1
- import { p as VectorError } from "../schema-DS8x1Dn8.mjs";
1
+ import { b as VectorError } from "../schema-CTHQMRsW.mjs";
2
2
  import { embedded } from "./index.mjs";
3
3
  //#region src/vector/stand-in.ts
4
4
  /**
@@ -42,6 +42,7 @@ function standIn() {
42
42
  return namespace.embed === void 0 ? void 0 : texts.map((text) => localEmbedding(text, namespace.dimension));
43
43
  }),
44
44
  create: engine.create,
45
+ update: engine.update,
45
46
  drop: engine.drop
46
47
  };
47
48
  }
@@ -57,11 +58,20 @@ function valuesOnly() {
57
58
  held,
58
59
  async create(name, settings) {
59
60
  const current = namespaces.get(name);
61
+ const { fullText, vectorType, ...rest } = settings;
60
62
  if (!current) return void namespaces.set(name, {
61
- ...settings,
62
- vectors: /* @__PURE__ */ new Map()
63
+ ...rest,
64
+ vectors: /* @__PURE__ */ new Map(),
65
+ fullText: new Set(fullText ?? []),
66
+ vectorType: vectorType ?? "f32"
63
67
  });
64
- if (current.dimension !== settings.dimension || current.metric !== settings.metric || current.embed !== settings.embed) throw new VectorError("conflict", `The Vector namespace ${name} exists with dimension ${current.dimension} and metric ${current.metric}${current.embed ? `, embedded by ${current.embed}` : ""}.`);
68
+ if (current.dimension !== settings.dimension || current.metric !== settings.metric || current.embed !== settings.embed || current.vectorType !== (vectorType ?? "f32") || !sameFields(current.fullText, fullText ?? [])) throw new VectorError("conflict", `The Vector namespace ${name} exists with dimension ${current.dimension}, metric ${current.metric}, ${current.vectorType} values${current.embed ? `, embedded by ${current.embed}` : ""} and full-text fields ${JSON.stringify([...current.fullText].sort())}.`);
69
+ },
70
+ async update(name, change) {
71
+ const namespace = held(name);
72
+ const fullText = /* @__PURE__ */ new Set([...namespace.fullText, ...change.addFullText]);
73
+ if (fullText.size > FULL_TEXT_MAX) throw new VectorError("invalid", `A Vector namespace keeps ${FULL_TEXT_MAX} full-text fields at most; ${name} would keep ${fullText.size}.`);
74
+ for (const field of change.addFullText) namespace.fullText.add(field);
65
75
  },
66
76
  async drop(name) {
67
77
  namespaces.delete(name);
@@ -79,28 +89,79 @@ function valuesOnly() {
79
89
  for (const vector of vectors) fits(namespace, vector.values, `Vector ${vector.id}`);
80
90
  for (const vector of vectors) namespace.vectors.set(vector.id, {
81
91
  ...copy(vector),
82
- values: vector.values.map((value) => Math.fround(value))
92
+ values: namespace.vectorType === "f16" && fitsHalf(vector.values) ? vector.values.map(half) : vector.values.map((value) => Math.fround(value))
83
93
  });
84
94
  return { upserted: vectors.length };
85
95
  },
86
96
  async query(name, query) {
87
97
  const namespace = held(name);
88
98
  fits(namespace, query.vector, "The query's vector");
89
- const scored = [];
99
+ return nearest(namespace, query.vector, query.filter, query.topK, query.includeValues, query.includeMetadata);
100
+ },
101
+ async list(name, list) {
102
+ const met = [...held(name).vectors.values()].filter((vector) => !list.filter || matches(list.filter, vector.id, vector.metadata ?? {}));
103
+ const key = (vector) => list.orderBy.map(([field]) => field === "id" ? vector.id : (vector.metadata ?? {})[field]);
104
+ met.sort((a, b) => ordered(list.orderBy.map(([, way]) => way === "desc"), key(a), key(b)) || byId(a.id, b.id));
105
+ return met.slice(0, list.topK).map((vector) => included(vector, list.includeValues, list.includeMetadata));
106
+ },
107
+ async textSearch(name, search) {
108
+ return textSearched(held(name), search.words, search.field, search.filter, search.topK, search.includeValues, search.includeMetadata);
109
+ },
110
+ async multiQuery(name, multi) {
111
+ const namespace = held(name);
112
+ const results = multi.queries.map((part) => {
113
+ if ("textSearch" in part) return textSearched(namespace, part.textSearch, part.field, part.filter, part.topK, false, multi.includeMetadata);
114
+ fits(namespace, part.vector, "A search's vector");
115
+ return nearest(namespace, part.vector, part.filter, part.topK, false, multi.includeMetadata);
116
+ });
117
+ if (!multi.fuse) return { results };
118
+ const { k, weights } = multi.fuse;
119
+ const fused = /* @__PURE__ */ new Map();
120
+ results.forEach((matches, search) => matches.forEach((match, rank) => {
121
+ const at = fused.get(match.id) ?? {
122
+ score: 0,
123
+ ...match.metadata ? { metadata: structuredClone(match.metadata) } : {}
124
+ };
125
+ fused.set(match.id, {
126
+ ...at,
127
+ score: at.score + weights[search] / (k + rank + 1)
128
+ });
129
+ }));
130
+ return {
131
+ results,
132
+ fused: [...fused].sort(([a, x], [b, y]) => y.score - x.score || byId(a, b)).slice(0, multi.topK).map(([id, { score, metadata }]) => ({
133
+ id,
134
+ score,
135
+ ...metadata ? { metadata } : {}
136
+ }))
137
+ };
138
+ },
139
+ async aggregate(name, aggregate) {
140
+ const namespace = held(name);
141
+ const groups = /* @__PURE__ */ new Map();
142
+ const names = Object.keys(aggregate.aggregates);
90
143
  for (const vector of namespace.vectors.values()) {
91
- if (query.filter && !matches(query.filter, vector.metadata ?? {})) continue;
92
- scored.push({
93
- vector,
94
- score: score(namespace.metric, query.vector, vector.values)
144
+ const metadata = vector.metadata ?? {};
145
+ if (aggregate.filter && !matches(aggregate.filter, vector.id, metadata)) continue;
146
+ const key = aggregate.groupBy.map((field) => Object.hasOwn(metadata, field) ? structuredClone(metadata[field]) : null);
147
+ const at = groups.get(JSON.stringify(key)) ?? {
148
+ key,
149
+ values: names.map(() => 0)
150
+ };
151
+ names.forEach((n, index) => {
152
+ const [kind, field] = aggregate.aggregates[n];
153
+ const value = field === void 0 ? void 0 : metadata[field];
154
+ at.values[index] += kind === "count" ? 1 : typeof value === "number" ? value : 0;
95
155
  });
156
+ groups.set(JSON.stringify(key), at);
96
157
  }
97
- const closer = namespace.metric === "euclidean" ? (a, b) => a - b : (a, b) => b - a;
98
- scored.sort((a, b) => closer(a.score, b.score) || (a.vector.id < b.vector.id ? -1 : a.vector.id > b.vector.id ? 1 : 0));
99
- return scored.slice(0, query.topK).map(({ vector, score }) => ({
100
- id: vector.id,
101
- score,
102
- ...query.includeValues ? { values: [...vector.values] } : {},
103
- ...query.includeMetadata ? { metadata: { ...vector.metadata } } : {}
158
+ if (!aggregate.groupBy.length && !groups.size) groups.set("[]", {
159
+ key: [],
160
+ values: names.map(() => 0)
161
+ });
162
+ return [...groups.values()].sort((a, b) => ordered(aggregate.groupBy.map(() => false), a.key.map((v) => v ?? void 0), b.key.map((v) => v ?? void 0)) || byId(JSON.stringify(a.key), JSON.stringify(b.key))).slice(0, aggregate.limit).map(({ key, values }) => ({
163
+ key: Object.fromEntries(aggregate.groupBy.map((field, index) => [field, key[index]])),
164
+ aggregates: Object.fromEntries(names.map((n, index) => [n, values[index]]))
104
165
  }));
105
166
  },
106
167
  async fetch(name, ids) {
@@ -116,11 +177,250 @@ function valuesOnly() {
116
177
  }
117
178
  };
118
179
  }
180
+ /** The full-text fields a namespace keeps at most, as the engine keeps them. */
181
+ const FULL_TEXT_MAX = 16;
182
+ /** Whether a namespace's full-text fields are `fields`, each once, in any order. */
183
+ function sameFields(kept, fields) {
184
+ const asked = new Set(fields);
185
+ return asked.size === kept.size && [...asked].every((field) => kept.has(field));
186
+ }
187
+ /** Whether 16-bit floats keep a vector: every value at most 65,504 in size, the largest at least 2^-10. */
188
+ function fitsHalf(values) {
189
+ const largest = Math.max(...values.map(Math.abs));
190
+ return values.every((value) => Math.abs(value) <= 65504) && largest >= 1 / 1024;
191
+ }
192
+ /**
193
+ * `value` as a 16-bit float holds it: its 32-bit float rounded to 10 bits of mantissa, to nearest, ties to even. Below
194
+ * 2^-14 the step is the subnormals' 2^-24, so 3 x 2^-26 rounds up to 2^-24 and only what is under half of it to zero.
195
+ */
196
+ function half(value) {
197
+ const bits = new Uint32Array(new Float32Array([value]).buffer)[0];
198
+ const sign = bits >>> 31 ? -1 : 1;
199
+ const exp = (bits >>> 23 & 255) - 127;
200
+ const step = 2 ** Math.max(exp - 10, -24);
201
+ const scaled = Math.abs(Math.fround(value)) / step;
202
+ const floor = Math.floor(scaled);
203
+ return sign * (scaled - floor > .5 || scaled - floor === .5 && floor % 2 === 1 ? floor + 1 : floor) * step;
204
+ }
205
+ function byId(a, b) {
206
+ return a < b ? -1 : a > b ? 1 : 0;
207
+ }
208
+ /** A Vector as an answer carries it: its own copies, so what a caller does to an answer never reaches what is held. */
209
+ function included(vector, values, metadata) {
210
+ return {
211
+ id: vector.id,
212
+ ...values ? { values: [...vector.values] } : {},
213
+ ...metadata ? { metadata: structuredClone(vector.metadata ?? {}) } : {}
214
+ };
215
+ }
216
+ /** The `topK` Vectors closest to `query` that match `filter`, closest first, ties by id. */
217
+ function nearest(namespace, query, filter, topK, values, metadata) {
218
+ const scored = [];
219
+ for (const vector of namespace.vectors.values()) {
220
+ if (filter && !matches(filter, vector.id, vector.metadata ?? {})) continue;
221
+ scored.push({
222
+ vector,
223
+ score: score(namespace.metric, query, vector.values)
224
+ });
225
+ }
226
+ const closer = namespace.metric === "euclidean" ? (a, b) => a - b : (a, b) => b - a;
227
+ scored.sort((a, b) => closer(a.score, b.score) || byId(a.vector.id, b.vector.id));
228
+ return scored.slice(0, topK).map(({ vector, score }) => ({
229
+ score,
230
+ ...included(vector, values, metadata)
231
+ }));
232
+ }
233
+ /**
234
+ * Two Vectors' keys in an order (`desc` for each): numbers with numbers, strings with strings (code-unit
235
+ * order), booleans with booleans; values of different kinds tie; a missing value comes after every value.
236
+ */
237
+ function ordered(desc, a, b) {
238
+ for (let index = 0; index < desc.length; index++) {
239
+ const [x, y] = [a[index], b[index]];
240
+ if (x === void 0 || y === void 0) {
241
+ if (x === void 0 && y === void 0) continue;
242
+ return x === void 0 ? 1 : -1;
243
+ }
244
+ const c = compare(x, y);
245
+ if (c) return desc[index] ? -c : c;
246
+ }
247
+ return 0;
248
+ }
249
+ /** Two values' order as the engine's filters compare them (`$gt` and the rest): 0 where they do not compare. */
250
+ function compare(x, y) {
251
+ const both = (type) => typeof x === type && typeof y === type;
252
+ if (both("number") || both("string")) return x < y ? -1 : x > y ? 1 : 0;
253
+ if (both("boolean")) return Number(x) - Number(y);
254
+ return 0;
255
+ }
256
+ /** Whether `x` and `y` compare (`compare` gave an order, equal included). */
257
+ function comparable(x, y) {
258
+ return typeof x === "number" && typeof y === "number" || typeof x === "string" && typeof y === "string" || typeof x === "boolean" && typeof y === "boolean";
259
+ }
260
+ /** A text's words as filters see them: runs of letters and digits, in lower case. */
261
+ function tokens(text) {
262
+ return text.split(/[^\p{Alphabetic}\p{N}]+/u).filter(Boolean).map((word) => word.toLowerCase());
263
+ }
264
+ /** A field's text: its string, or its array's strings joined by spaces; numbers and the rest have none. */
265
+ function textOf(value) {
266
+ if (typeof value === "string") return value;
267
+ if (Array.isArray(value)) return value.filter((item) => typeof item === "string").join(" ");
268
+ return "";
269
+ }
270
+ /**
271
+ * A glob: `*` any run of characters, `?` any one, `[abc]` / `[a-z]` one of a set (`[!…]` or `[^…]`
272
+ * one not in it); a `[` with no `]` after it is itself.
273
+ */
274
+ function glob(pattern, value) {
275
+ const p = [...pattern];
276
+ const v = [...value];
277
+ const memo = /* @__PURE__ */ new Map();
278
+ const at = (i, j) => {
279
+ const key = `${i},${j}`;
280
+ const known = memo.get(key);
281
+ if (known !== void 0) return known;
282
+ let result;
283
+ if (i === p.length) result = j === v.length;
284
+ else if (p[i] === "*") result = at(i + 1, j) || j < v.length && at(i, j + 1);
285
+ else if (j === v.length) result = false;
286
+ else if (p[i] === "?") result = at(i + 1, j + 1);
287
+ else if (p[i] === "[") {
288
+ let k = i + 1;
289
+ const negated = p[k] === "!" || p[k] === "^";
290
+ if (negated) k++;
291
+ const first = k;
292
+ let hit = false;
293
+ while (k < p.length && (p[k] !== "]" || k === first)) if (p[k + 1] === "-" && k + 2 < p.length && p[k + 2] !== "]") {
294
+ hit ||= p[k] <= v[j] && v[j] <= p[k + 2];
295
+ k += 3;
296
+ } else {
297
+ hit ||= p[k] === v[j];
298
+ k++;
299
+ }
300
+ result = k < p.length ? hit !== negated && at(k + 1, j + 1) : v[j] === "[" && at(i + 1, j + 1);
301
+ } else result = p[i] === v[j] && at(i + 1, j + 1);
302
+ memo.set(key, result);
303
+ return result;
304
+ };
305
+ return at(0, 0);
306
+ }
307
+ function equalValue(a, b) {
308
+ return JSON.stringify(a) === JSON.stringify(b);
309
+ }
310
+ /** One operator against a field's value (undefined: the Vector has no such field), as the engine meets it. */
311
+ function holdsOp(op, expected, value) {
312
+ if (value === void 0) {
313
+ const nullIn = Array.isArray(expected) && expected.includes(null);
314
+ switch (op) {
315
+ case "$eq": return expected === null;
316
+ case "$ne": return expected !== null;
317
+ case "$in": return nullIn;
318
+ case "$nin": return !nullIn;
319
+ case "$notContains":
320
+ case "$notContainsAny":
321
+ case "$notGlob":
322
+ case "$notIGlob": return true;
323
+ default: return false;
324
+ }
325
+ }
326
+ const any = (test) => Array.isArray(value) && value.some((item) => comparable(item, expected) && test(compare(item, expected)));
327
+ const order = (test) => comparable(value, expected) && test(compare(value, expected));
328
+ switch (op) {
329
+ case "$eq": return equalValue(value, expected);
330
+ case "$ne": return !equalValue(value, expected);
331
+ case "$in": return expected.some((item) => equalValue(value, item));
332
+ case "$nin": return !expected.some((item) => equalValue(value, item));
333
+ case "$gt": return order((o) => o > 0);
334
+ case "$gte": return order((o) => o >= 0);
335
+ case "$lt": return order((o) => o < 0);
336
+ case "$lte": return order((o) => o <= 0);
337
+ case "$contains": return Array.isArray(value) && value.some((item) => equalValue(item, expected)) || typeof value === "string" && typeof expected === "string" && value.includes(expected);
338
+ case "$notContains": return !holdsOp("$contains", expected, value);
339
+ case "$containsAny": return Array.isArray(value) && expected.some((wanted) => value.some((item) => equalValue(item, wanted)));
340
+ case "$notContainsAny": return !holdsOp("$containsAny", expected, value);
341
+ case "$anyGt": return any((o) => o > 0);
342
+ case "$anyGte": return any((o) => o >= 0);
343
+ case "$anyLt": return any((o) => o < 0);
344
+ case "$anyLte": return any((o) => o <= 0);
345
+ case "$glob": return typeof value === "string" && glob(expected, value);
346
+ case "$notGlob": return !holdsOp("$glob", expected, value);
347
+ case "$iglob": return typeof value === "string" && glob(expected.toLowerCase(), value.toLowerCase());
348
+ case "$notIGlob": return !holdsOp("$iglob", expected, value);
349
+ case "$containsAllTokens": {
350
+ const have = tokens(textOf(value));
351
+ return tokens(expected).every((t) => have.includes(t));
352
+ }
353
+ case "$containsAnyToken": {
354
+ const { tokens: words, lastAsPrefix } = typeof expected === "string" ? {
355
+ tokens: expected,
356
+ lastAsPrefix: false
357
+ } : expected;
358
+ const have = tokens(textOf(value));
359
+ const wanted = tokens(words);
360
+ const last = lastAsPrefix ? wanted.pop() : void 0;
361
+ return wanted.some((t) => have.includes(t)) || last !== void 0 && have.some((t) => t.startsWith(last));
362
+ }
363
+ case "$containsTokenSequence": {
364
+ const have = tokens(textOf(value));
365
+ const wanted = tokens(expected);
366
+ return wanted.length === 0 || have.some((_, start) => wanted.every((t, k) => have[start + k] === t));
367
+ }
368
+ default: return false;
369
+ }
370
+ }
371
+ function words(text) {
372
+ const out = /* @__PURE__ */ new Map();
373
+ for (const raw of text.split(/[^\p{Alphabetic}\p{N}]+/u)) {
374
+ if (!raw) continue;
375
+ const word = [...raw].map((c) => c.toLowerCase()).join("");
376
+ if ([...word].length > 40) continue;
377
+ if (out.size >= 2048 && !out.has(word)) continue;
378
+ out.set(word, (out.get(word) ?? 0) + 1);
379
+ }
380
+ return out;
381
+ }
382
+ function textSearched(namespace, query, field, filter, topK, values, metadata) {
383
+ if (!namespace.fullText.has(field)) throw new VectorError("invalid", `A text search reads a field the namespace keeps full text; ${field} is not one.`);
384
+ const rows = [...namespace.vectors.values()].map((vector) => ({
385
+ vector,
386
+ words: words(textOf((vector.metadata ?? {})[field]))
387
+ }));
388
+ const length = (w) => [...w.values()].reduce((sum, n) => sum + n, 0);
389
+ const byCodePoint = (a, b) => {
390
+ const [x, y] = [[...a], [...b]];
391
+ for (let i = 0; i < Math.min(x.length, y.length); i++) {
392
+ const d = x[i].codePointAt(0) - y[i].codePointAt(0);
393
+ if (d) return d;
394
+ }
395
+ return x.length - y.length;
396
+ };
397
+ const terms = [...words(query).keys()].sort(byCodePoint).slice(0, 16);
398
+ const n = Math.max(rows.length, 1);
399
+ const scores = /* @__PURE__ */ new Map();
400
+ for (const term of terms) {
401
+ const having = rows.filter((row) => row.words.has(term));
402
+ if (!having.length) continue;
403
+ const df = having.length;
404
+ const mean = Math.max(having.reduce((sum, row) => sum + length(row.words), 0) / df, 1);
405
+ const idf = Math.log(Math.max(n - df + .5, .5) / (df + .5) + 1);
406
+ for (const row of having) {
407
+ const tf = row.words.get(term);
408
+ scores.set(row.vector, (scores.get(row.vector) ?? 0) + idf * tf * 2.2 / (tf + 1.2 * (.25 + .75 * length(row.words) / mean)));
409
+ }
410
+ }
411
+ return [...scores].map(([vector, score]) => ({
412
+ vector,
413
+ score: Math.fround(score)
414
+ })).filter(({ vector }) => !filter || matches(filter, vector.id, vector.metadata ?? {})).sort((a, b) => b.score - a.score || byId(a.vector.id, b.vector.id)).slice(0, topK).map(({ vector, score }) => ({
415
+ score,
416
+ ...included(vector, values, metadata)
417
+ }));
418
+ }
119
419
  function copy(vector) {
120
420
  return {
121
421
  id: vector.id,
122
422
  values: [...vector.values],
123
- ...vector.metadata ? { metadata: { ...vector.metadata } } : {}
423
+ ...vector.metadata ? { metadata: structuredClone(vector.metadata) } : {}
124
424
  };
125
425
  }
126
426
  /** Refuses `values` that are not the namespace's dimension, or, for cosine, all zero: they have no direction. */
@@ -157,13 +457,16 @@ function score(metric, a, b) {
157
457
  for (let index = 0; index < x.length; index++) cosine += x[index] * y[index];
158
458
  return Math.max(-1, Math.min(1, cosine));
159
459
  }
160
- function matches(filter, metadata) {
161
- return Object.entries(filter).every(([field, condition]) => holds(condition, Object.hasOwn(metadata, field) ? metadata[field] : void 0));
460
+ /** Whether a Vector (its id and metadata) meets `filter`. */
461
+ function matches(filter, id, metadata) {
462
+ if ("$and" in filter && Array.isArray(filter.$and)) return filter.$and.every((f) => matches(f, id, metadata));
463
+ if ("$or" in filter && Array.isArray(filter.$or)) return filter.$or.some((f) => matches(f, id, metadata));
464
+ if ("$not" in filter && typeof filter.$not === "object" && !Array.isArray(filter.$not)) return !matches(filter.$not, id, metadata);
465
+ return Object.entries(filter).every(([field, condition]) => holds(condition, field === "id" ? id : Object.hasOwn(metadata, field) ? metadata[field] : void 0));
162
466
  }
163
467
  function holds(condition, value) {
164
- if (typeof condition !== "object") return value === condition;
165
- const ordered = (bound, test) => value !== void 0 && typeof value === typeof bound && typeof value !== "boolean" && test(value < bound ? -1 : value > bound ? 1 : 0);
166
- return (condition.$eq === void 0 || value === condition.$eq) && (condition.$ne === void 0 || value !== condition.$ne) && (condition.$in === void 0 || value !== void 0 && condition.$in.includes(value)) && (condition.$nin === void 0 || value === void 0 || !condition.$nin.includes(value)) && (condition.$gt === void 0 || ordered(condition.$gt, (order) => order > 0)) && (condition.$gte === void 0 || ordered(condition.$gte, (order) => order >= 0)) && (condition.$lt === void 0 || ordered(condition.$lt, (order) => order < 0)) && (condition.$lte === void 0 || ordered(condition.$lte, (order) => order <= 0));
468
+ if (typeof condition !== "object") return holdsOp("$eq", condition, value);
469
+ return Object.entries(condition).every(([op, expected]) => holdsOp(op, expected, value));
167
470
  }
168
471
  //#endregion
169
472
  export { localEmbedding, standIn };
package/vector/wire.d.mts CHANGED
@@ -1,9 +1,18 @@
1
- import { g as VectorEngine, m as VectorControl } from "../index-DdoK0y7D.mjs";
1
+ import { A as VectorControl, M as VectorEngine } from "../index-DNNXNny7.mjs";
2
2
  //#region src/vector/wire.d.ts
3
3
  /** Carries one request frame to a server and brings back its answer frame. */
4
4
  interface Transport {
5
5
  send(frame: Uint8Array): Promise<Uint8Array>;
6
6
  }
7
+ /** Where a frame's vectors are: paths of keys, `*` each item of an array. */
8
+ type Places = ReadonlyArray<ReadonlyArray<string>>;
9
+ /** The places of a call's vectors (`side` "call") or of its answer's (`side` "answer"), by its op. */
10
+ declare function places(op: string, side: "call" | "answer"): Places;
11
+ /** `value` as a frame: the arrays of numbers at `where` (`places`) moved into sections (`{"$v": n}`), the JSON first. */
12
+ declare function encode(value: unknown, where?: Places): Uint8Array;
13
+ /** A frame's value (`encode`): its sections back in place of their `{"$v": n}` at `where` (`places`; or, for a call
14
+ * read before its op is known, the places of the op its JSON names). Throws where it does not read. */
15
+ declare function decode(frame: Uint8Array, where?: Places | ((json: unknown) => Places)): unknown;
7
16
  /** An engine that sends each call over `transport`. A transport that fails is `unavailable`. */
8
17
  declare function remote(transport: Transport): VectorEngine & VectorControl;
9
18
  /**
@@ -22,4 +31,4 @@ declare function serve(engine: VectorEngine & Partial<VectorControl>): (frame: U
22
31
  */
23
32
  declare function scoped(engine: VectorEngine, namespaceId: (name: string) => Promise<string | undefined>): VectorEngine;
24
33
  //#endregion
25
- export { Transport, remote, scoped, serve };
34
+ export { Places, Transport, decode, encode, places, remote, scoped, serve };