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

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
package/vector/wire.mjs CHANGED
@@ -1,16 +1,22 @@
1
- import { c as NamespaceName, d as Vectors, f as checked, l as Query, m as vectorErrorCodes, p as VectorError, t as Ids, u as Settings } from "../schema-DS8x1Dn8.mjs";
1
+ import { _ as Update, b as VectorError, f as MultiQuery, g as TextSearch, h as Settings, m as Query, n as Ids, p as NamespaceName, r as List, t as Aggregation, v as Vectors, x as vectorErrorCodes, y as checked } from "../schema-CTHQMRsW.mjs";
2
2
  import { z } from "zod";
3
3
  //#region src/vector/wire.ts
4
4
  /**
5
- * Vector DB's wire: one call is one frame, the UTF-8 JSON of `{ op, namespace, … }`, and its answer
6
- * is one frame, `{ ok }` or `{ error, why }` with a `VectorErrorCode`. A transport only carries
7
- * frames; a Site's own handle is one (`{ send }`), handed to it by the platform for its Environment.
5
+ * Vector DB's wire: one call is one frame, `{ op, namespace, … }`, and its answer is one frame, `{ ok }`
6
+ * or `{ error, why }` with a `VectorErrorCode`. A frame is a u32 (little-endian) length, that much
7
+ * UTF-8 JSON, then its vectors: each array at a place its call names for one (`places`: an upsert's
8
+ * Vectors' `values`, a query's `vector`, an answer's matches' `values`; never a filter, metadata or
9
+ * an aggregate's key, whatever its fields are named) is `{"$v": n}` in the JSON and section n after
10
+ * it, a u32 count and that many little-endian 32-bit floats, so a value crosses the wire bit for bit
11
+ * (-0 included), never as a JSON number. A transport
12
+ * only carries frames; a Site's own handle is one (`{ send }`), handed to it by the platform for its
13
+ * Environment.
8
14
  *
9
15
  * const docs = vectorDb(remote(context.vector)).namespace("docs") // a Site
10
16
  * const answer = await serve(scoped(engine, (name) => vector.siteNamespace(repositoryId, environment, name)))(frame) // the platform
11
17
  *
12
18
  * `scoped` is how the platform serves a Site: names mapped to the ids the engine knows them by, and
13
- * making or dropping a namespace refused.
19
+ * making, changing or dropping a namespace refused.
14
20
  */
15
21
  const call = z.discriminatedUnion("op", [
16
22
  z.object({
@@ -37,11 +43,36 @@ const call = z.discriminatedUnion("op", [
37
43
  namespace: z.string(),
38
44
  ids: z.unknown()
39
45
  }),
46
+ z.object({
47
+ op: z.literal("list"),
48
+ namespace: z.string(),
49
+ list: z.unknown()
50
+ }),
51
+ z.object({
52
+ op: z.literal("textSearch"),
53
+ namespace: z.string(),
54
+ search: z.unknown()
55
+ }),
56
+ z.object({
57
+ op: z.literal("multiQuery"),
58
+ namespace: z.string(),
59
+ multi: z.unknown()
60
+ }),
61
+ z.object({
62
+ op: z.literal("aggregate"),
63
+ namespace: z.string(),
64
+ aggregate: z.unknown()
65
+ }),
40
66
  z.object({
41
67
  op: z.literal("create"),
42
68
  namespace: z.string(),
43
69
  settings: z.unknown()
44
70
  }),
71
+ z.object({
72
+ op: z.literal("update"),
73
+ namespace: z.string(),
74
+ change: z.unknown()
75
+ }),
45
76
  z.object({
46
77
  op: z.literal("drop"),
47
78
  namespace: z.string()
@@ -51,19 +82,118 @@ const answer = z.union([z.object({
51
82
  error: z.enum(vectorErrorCodes),
52
83
  why: z.string()
53
84
  }), z.object({ ok: z.unknown() })]);
54
- const encode = (value) => new TextEncoder().encode(JSON.stringify(value));
85
+ /** The places of a call's vectors (`side` "call") or of its answer's (`side` "answer"), by its op. */
86
+ function places(op, side) {
87
+ if (side === "call") {
88
+ if (op === "upsert") return [[
89
+ "vectors",
90
+ "*",
91
+ "values"
92
+ ]];
93
+ if (op === "query") return [["query", "vector"]];
94
+ if (op === "multiQuery") return [[
95
+ "multi",
96
+ "queries",
97
+ "*",
98
+ "vector"
99
+ ]];
100
+ return [];
101
+ }
102
+ if (op === "query" || op === "fetch" || op === "list" || op === "textSearch") return [[
103
+ "ok",
104
+ "*",
105
+ "values"
106
+ ]];
107
+ if (op === "multiQuery") return [[
108
+ "ok",
109
+ "results",
110
+ "*",
111
+ "*",
112
+ "values"
113
+ ], [
114
+ "ok",
115
+ "fused",
116
+ "*",
117
+ "values"
118
+ ]];
119
+ return [];
120
+ }
121
+ /** `value` with each thing at one of `at` (`Places`) given to `f`, the rest as it is. */
122
+ function atPlaces(value, at, f) {
123
+ const walk = (v, paths) => {
124
+ if (paths.some((p) => p.length === 0)) return f(v);
125
+ if (paths.length === 0 || v === null || typeof v !== "object") return v;
126
+ if (Array.isArray(v)) {
127
+ const next = paths.filter((p) => p[0] === "*").map((p) => p.slice(1));
128
+ return next.length === 0 ? v : v.map((item) => walk(item, next));
129
+ }
130
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => {
131
+ const next = paths.filter((p) => p[0] === k).map((p) => p.slice(1));
132
+ return [k, next.length === 0 ? x : walk(x, next)];
133
+ }));
134
+ };
135
+ return walk(value, at);
136
+ }
137
+ /** `value` as a frame: the arrays of numbers at `where` (`places`) moved into sections (`{"$v": n}`), the JSON first. */
138
+ function encode(value, where = []) {
139
+ const sections = [];
140
+ const lifted = atPlaces(value, where, (v) => Array.isArray(v) && v.every((x) => typeof x === "number") ? { $v: sections.push(v) - 1 } : v);
141
+ const json = new TextEncoder().encode(JSON.stringify(lifted));
142
+ const out = new Uint8Array(4 + json.length + sections.reduce((n, v) => n + 4 + 4 * v.length, 0));
143
+ const view = new DataView(out.buffer);
144
+ view.setUint32(0, json.length, true);
145
+ out.set(json, 4);
146
+ let at = 4 + json.length;
147
+ for (const v of sections) {
148
+ view.setUint32(at, v.length, true);
149
+ at += 4;
150
+ for (const x of v) {
151
+ view.setFloat32(at, x, true);
152
+ at += 4;
153
+ }
154
+ }
155
+ return out;
156
+ }
157
+ /** A frame's value (`encode`): its sections back in place of their `{"$v": n}` at `where` (`places`; or, for a call
158
+ * read before its op is known, the places of the op its JSON names). Throws where it does not read. */
159
+ function decode(frame, where = []) {
160
+ const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);
161
+ const length = view.getUint32(0, true);
162
+ if (4 + length > frame.length) throw new Error("a frame shorter than its JSON");
163
+ const json = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(frame.subarray(4, 4 + length)));
164
+ const sections = [];
165
+ for (let at = 4 + length; at < frame.length;) {
166
+ const count = view.getUint32(at, true);
167
+ at += 4;
168
+ if (at + 4 * count > frame.length) throw new Error("a frame shorter than its vectors");
169
+ sections.push(Array.from({ length: count }, (_, k) => view.getFloat32(at + 4 * k, true)));
170
+ at += 4 * count;
171
+ }
172
+ const place = (v) => {
173
+ if (v === null || typeof v !== "object" || Array.isArray(v) || !("$v" in v)) return v;
174
+ const n = v.$v;
175
+ if (typeof n !== "number" || !sections[n]) throw new Error("a vector section that is not there");
176
+ return sections[n];
177
+ };
178
+ return atPlaces(json, typeof where === "function" ? where(json) : where, place);
179
+ }
180
+ /** The places of the call `json` names the op of (`places`). */
181
+ function callPlaces(json) {
182
+ const op = json !== null && typeof json === "object" ? json.op : void 0;
183
+ return typeof op === "string" ? places(op, "call") : [];
184
+ }
55
185
  /** An engine that sends each call over `transport`. A transport that fails is `unavailable`. */
56
186
  function remote(transport) {
57
187
  async function ask(request) {
58
188
  let frame;
59
189
  try {
60
- frame = await transport.send(encode(request));
190
+ frame = await transport.send(encode(request, places(request.op, "call")));
61
191
  } catch {
62
192
  throw new VectorError("unavailable", "Vector DB could not be reached. Try again.");
63
193
  }
64
194
  let parsed;
65
195
  try {
66
- parsed = answer.parse(JSON.parse(new TextDecoder().decode(frame)));
196
+ parsed = answer.parse(decode(frame, places(request.op, "answer")));
67
197
  } catch {
68
198
  throw new VectorError("unavailable", "Vector DB answered something that is not a Vector DB frame");
69
199
  }
@@ -95,11 +225,36 @@ function remote(transport) {
95
225
  namespace,
96
226
  ids
97
227
  }),
228
+ list: (namespace, list) => ask({
229
+ op: "list",
230
+ namespace,
231
+ list
232
+ }),
233
+ textSearch: (namespace, search) => ask({
234
+ op: "textSearch",
235
+ namespace,
236
+ search
237
+ }),
238
+ multiQuery: (namespace, multi) => ask({
239
+ op: "multiQuery",
240
+ namespace,
241
+ multi
242
+ }),
243
+ aggregate: (namespace, aggregate) => ask({
244
+ op: "aggregate",
245
+ namespace,
246
+ aggregate
247
+ }),
98
248
  create: async (namespace, settings) => void await ask({
99
249
  op: "create",
100
250
  namespace,
101
251
  settings
102
252
  }),
253
+ update: async (namespace, change) => void await ask({
254
+ op: "update",
255
+ namespace,
256
+ change
257
+ }),
103
258
  drop: async (namespace) => void await ask({
104
259
  op: "drop",
105
260
  namespace
@@ -117,15 +272,14 @@ function serve(engine) {
117
272
  try {
118
273
  let json;
119
274
  try {
120
- json = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(frame));
275
+ json = decode(frame, callPlaces);
121
276
  } catch {
122
- throw new VectorError("invalid", "the request frame is not JSON");
277
+ throw new VectorError("invalid", "the request frame is not a Vector DB frame");
123
278
  }
124
279
  const parsed = call.safeParse(json);
125
280
  if (!parsed.success) throw new VectorError("invalid", "the request frame is not a Vector DB call");
126
281
  const request = parsed.data;
127
- const namespace = checked(NamespaceName, request.namespace);
128
- return encode({ ok: await answerTo(engine, namespace, request) ?? null });
282
+ return encode({ ok: await answerTo(engine, checked(NamespaceName, request.namespace), request) ?? null }, places(request.op, "answer"));
129
283
  } catch (error) {
130
284
  if (error instanceof VectorError) return encode({
131
285
  error: error.code,
@@ -142,9 +296,16 @@ async function answerTo(engine, namespace, request) {
142
296
  case "query": return engine.query(namespace, checked(Query, request.query));
143
297
  case "fetch": return engine.fetch(namespace, checked(Ids, request.ids));
144
298
  case "delete": return engine.delete(namespace, checked(Ids, request.ids));
299
+ case "list": return engine.list(namespace, checked(List, request.list));
300
+ case "textSearch": return engine.textSearch(namespace, checked(TextSearch, request.search));
301
+ case "multiQuery": return engine.multiQuery(namespace, checked(MultiQuery, request.multi));
302
+ case "aggregate": return engine.aggregate(namespace, checked(Aggregation, request.aggregate));
145
303
  case "create":
146
304
  if (!engine.create) throw new VectorError("forbidden", "Vector namespaces are made through the platform");
147
305
  return engine.create(namespace, checked(Settings, request.settings));
306
+ case "update":
307
+ if (!engine.update) throw new VectorError("forbidden", "Vector namespaces are changed through the platform");
308
+ return engine.update(namespace, checked(Update, request.change));
148
309
  case "drop":
149
310
  if (!engine.drop) throw new VectorError("forbidden", "Vector namespaces are dropped through the platform");
150
311
  return engine.drop(namespace);
@@ -168,8 +329,12 @@ function scoped(engine, namespaceId) {
168
329
  upsert: async (namespace, vectors) => engine.upsert(await id(namespace), vectors),
169
330
  query: async (namespace, query) => engine.query(await id(namespace), query),
170
331
  fetch: async (namespace, ids) => engine.fetch(await id(namespace), ids),
171
- delete: async (namespace, ids) => engine.delete(await id(namespace), ids)
332
+ delete: async (namespace, ids) => engine.delete(await id(namespace), ids),
333
+ list: async (namespace, list) => engine.list(await id(namespace), list),
334
+ textSearch: async (namespace, search) => engine.textSearch(await id(namespace), search),
335
+ multiQuery: async (namespace, multi) => engine.multiQuery(await id(namespace), multi),
336
+ aggregate: async (namespace, aggregate) => engine.aggregate(await id(namespace), aggregate)
172
337
  };
173
338
  }
174
339
  //#endregion
175
- export { remote, scoped, serve };
340
+ export { decode, encode, places, remote, scoped, serve };
@@ -1,41 +0,0 @@
1
- import { r as Shape, t as IndexDeclaration } from "./schema-f7E9uzUn.mjs";
2
- //#region src/database/build.d.ts
3
- /** A file the Database would refuse; the message gives the file, and the line when there is one. */
4
- declare class Refused extends Error {
5
- constructor(message: string);
6
- }
7
- interface BuiltFunction {
8
- readonly name: string;
9
- readonly kind: "query" | "mutation" | "action" | "internalQuery" | "internalMutation" | "internalAction";
10
- /** The built file it is in, and the export that holds it. */
11
- readonly file: string;
12
- readonly export: string;
13
- /** Its `args` fields and `returns` shape as written, for its types: null where they are not literals. */
14
- readonly args: Readonly<Record<string, Shape | null>> | null;
15
- readonly returns: Shape | null;
16
- }
17
- interface Built {
18
- /** The folder's modules as JavaScript, by `<name>.mjs`, each import of the folder naming its built file. */
19
- readonly files: Readonly<Record<string, string>>;
20
- /** Which author file each built one came from. */
21
- readonly from: Readonly<Record<string, string>>;
22
- readonly functions: ReadonlyArray<BuiltFunction>;
23
- /** The schema's tables by field, and their indexes; null without `schema.ts`. */
24
- readonly tables: Readonly<Record<string, Readonly<Record<string, Shape>>>> | null;
25
- readonly indexes: Readonly<Record<string, Readonly<Record<string, IndexDeclaration>>>> | null;
26
- /** The files of `db/_generated/`. */
27
- readonly generated: {
28
- readonly "api.mjs": string;
29
- readonly "api.d.ts": string;
30
- readonly "dataModel.d.ts": string;
31
- readonly "server.d.ts": string;
32
- };
33
- }
34
- /** Whether a file directly in `db/` is a source: types (`.d.ts`) and dotfiles are none. */
35
- declare const isSource: (name: string) => boolean;
36
- /** Builds a `db/` folder's sources: `{ <file>: text }`, its top level. Throws `Refused`. */
37
- declare function buildDatabase(sources: Readonly<Record<string, string>>, strip: (ts: string) => string): Built;
38
- /** A shape as a TypeScript type. */
39
- declare function typeOf(shape: Shape | null | undefined): string;
40
- //#endregion
41
- export { isSource as a, buildDatabase as i, BuiltFunction as n, typeOf as o, Refused as r, Built as t };
@@ -1,192 +0,0 @@
1
- import { z } from "zod";
2
- //#region src/vector/errors.d.ts
3
- /**
4
- * Why a Vector DB call failed. `invalid`: a name, Vector, filter or option is wrong, or a Vector's
5
- * dimension is not its namespace's. `not_found`: the Vector namespace does not exist. `conflict`:
6
- * a namespace by that name exists with another dimension or metric. `forbidden`: the caller may not
7
- * do this. `unavailable`: try again.
8
- */
9
- type VectorErrorCode = "invalid" | "not_found" | "conflict" | "forbidden" | "unavailable";
10
- declare const vectorErrorCodes: ReadonlyArray<VectorErrorCode>;
11
- declare class VectorError extends Error {
12
- readonly code: VectorErrorCode;
13
- constructor(code: VectorErrorCode, why: string);
14
- }
15
- //#endregion
16
- //#region src/vector/schema.d.ts
17
- /** Most numbers a Vector holds. */
18
- declare const MAX_DIMENSION = 4096;
19
- /** Most Vectors one upsert takes, and most ids one fetch or delete names. */
20
- declare const MAX_BATCH = 1000;
21
- /** The most matches one query returns. */
22
- declare const MAX_TOP_K = 100;
23
- /** Most characters a text to embed has. */
24
- declare const MAX_TEXT = 30000;
25
- /** Most bytes a Vector's metadata takes, as JSON. */
26
- declare const MAX_METADATA_BYTES = 10240;
27
- /**
28
- * The largest value a Vector holds. Engines keep values and scores as 32-bit floats, and within it
29
- * every score of 4,096 values is one, finite: a squared distance is at most 4,096 · (2e17)², about
30
- * 1.6e38, under a 32-bit float's 3.4e38. Scores are exact to a 32-bit float's precision for values
31
- * from 1e-17 up.
32
- */
33
- declare const MAX_VALUE = 100000000000000000;
34
- //#endregion
35
- //#region src/vector/index.d.ts
36
- /** How closeness is measured: fixed when a Vector namespace is made. */
37
- type Metric = "cosine" | "euclidean" | "dot";
38
- /** A metadata value: a string, a finite number or a boolean. */
39
- type MetadataValue = string | number | boolean;
40
- /** One Vector: its id in its namespace, its numbers, and the caller's own fields to filter on. */
41
- interface Vector {
42
- /** 1 to 512 characters. */
43
- readonly id: string;
44
- /** Exactly the namespace's dimension of finite numbers. With `cosine`, not all zero. */
45
- readonly values: ReadonlyArray<number>;
46
- /** Up to 10 KiB as JSON; field names do not start with `$`. */
47
- readonly metadata?: Readonly<Record<string, MetadataValue>>;
48
- }
49
- /** A Vector given as text, for a namespace made with an embedding model: its values are the text's embedding. */
50
- interface TextVector {
51
- /** 1 to 512 characters. */
52
- readonly id: string;
53
- /** 1 to 30,000 characters, not all of them spaces. */
54
- readonly text: string;
55
- readonly metadata?: Readonly<Record<string, MetadataValue>>;
56
- }
57
- /**
58
- * What a field's metadata must be. A bare value is `$eq`. `$gt`, `$gte`, `$lt` and `$lte` compare a
59
- * number with a number and a string with a string, in code-unit order; anything else fails them.
60
- * A Vector without the field fails every condition but `$ne` and `$nin`.
61
- */
62
- type Condition = MetadataValue | {
63
- readonly $eq?: MetadataValue;
64
- readonly $ne?: MetadataValue;
65
- readonly $in?: ReadonlyArray<MetadataValue>;
66
- readonly $nin?: ReadonlyArray<MetadataValue>;
67
- readonly $gt?: number | string;
68
- readonly $gte?: number | string;
69
- readonly $lt?: number | string;
70
- readonly $lte?: number | string;
71
- };
72
- /** Each field's condition; a Vector matches when all of them hold. */
73
- type Filter = Readonly<Record<string, Condition>>;
74
- interface QueryOptions {
75
- /** How many matches, closest first: 1 to 100, default 10. */
76
- readonly topK?: number;
77
- readonly filter?: Filter;
78
- /** Answer each match's values too. */
79
- readonly includeValues?: boolean;
80
- /** Answer each match's metadata too. */
81
- readonly includeMetadata?: boolean;
82
- /**
83
- * `strong` (the default): every write made before the query is seen, and it runs in the namespace's
84
- * home region. `eventual`: it runs where it is asked, on what the engine has indexed, which lags
85
- * writes by up to about 15 seconds.
86
- */
87
- readonly consistency?: Consistency;
88
- }
89
- /** Whether a query sees every write made before it, or runs nearest and may lag them. */
90
- type Consistency = "strong" | "eventual";
91
- /**
92
- * One Vector a query found. `score` is the metric's own number: the cosine similarity (1 is the
93
- * same direction), the dot product, or the euclidean distance (0 is the same point). Matches come
94
- * closest first, so highest score first except for `euclidean`, lowest first; equal scores in id order.
95
- */
96
- interface Match {
97
- readonly id: string;
98
- readonly score: number;
99
- readonly values?: ReadonlyArray<number>;
100
- readonly metadata?: Readonly<Record<string, MetadataValue>>;
101
- }
102
- /** A Vector namespace as it is now. */
103
- interface NamespaceInfo {
104
- readonly dimension: number;
105
- readonly metric: Metric;
106
- /** How many Vectors it holds. */
107
- readonly count: number;
108
- }
109
- /** The Vectors of one Vector namespace. */
110
- interface Namespace {
111
- readonly name: string;
112
- /** Stores each Vector under its id, replacing what was there; one given as text is embedded first. The next query anywhere sees it. */
113
- upsert(vectors: ReadonlyArray<Vector | TextVector>): Promise<{
114
- readonly upserted: number;
115
- }>;
116
- /** The `topK` Vectors closest to `vector`, or to a text's embedding, that match `filter`, closest first. */
117
- query(vector: ReadonlyArray<number> | string, options?: QueryOptions): Promise<ReadonlyArray<Match>>;
118
- /** The Vectors with these ids, in the order asked, values and metadata included; ids it does not hold are left out. */
119
- fetch(ids: ReadonlyArray<string>): Promise<ReadonlyArray<Vector>>;
120
- /** Removes the Vectors with these ids. Removing one that is not there is not an error. */
121
- delete(ids: ReadonlyArray<string>): Promise<void>;
122
- describe(): Promise<NamespaceInfo>;
123
- }
124
- interface VectorDb {
125
- /** A Vector namespace by name: 1 to 63 lowercase letters, digits and hyphens, starting with a letter or digit. */
126
- namespace(name: string): Namespace;
127
- }
128
- /** A query as an engine takes it: checked, with its defaults filled in; by a vector, or a text to embed. */
129
- type EngineQuery = ({
130
- readonly vector: ReadonlyArray<number>;
131
- } | {
132
- readonly text: string;
133
- }) & {
134
- readonly topK: number;
135
- readonly filter?: Filter;
136
- readonly includeValues: boolean;
137
- readonly includeMetadata: boolean;
138
- readonly consistency?: Consistency;
139
- };
140
- /**
141
- * Where Vectors live: the Seam under `vectorDb()`. The Stand-in and the real Capability are its
142
- * Adapters. A call arrives checked: names, ids, values, filters and limits valid. The engine checks
143
- * what only it knows: that the namespace exists, and that each Vector has its dimension. An engine
144
- * that keeps only values takes text through `embedded`.
145
- */
146
- interface VectorEngine {
147
- describe(namespace: string): Promise<NamespaceInfo>;
148
- upsert(namespace: string, vectors: ReadonlyArray<Vector | TextVector>): Promise<{
149
- readonly upserted: number;
150
- }>;
151
- query(namespace: string, query: EngineQuery): Promise<ReadonlyArray<Match>>;
152
- fetch(namespace: string, ids: ReadonlyArray<string>): Promise<ReadonlyArray<Vector>>;
153
- delete(namespace: string, ids: ReadonlyArray<string>): Promise<void>;
154
- }
155
- /** An engine that keeps only values, as most do: `VectorEngine` without text, which `embedded` gives it. */
156
- interface ValuesEngine {
157
- describe(namespace: string): Promise<NamespaceInfo>;
158
- upsert(namespace: string, vectors: ReadonlyArray<Vector>): Promise<{
159
- readonly upserted: number;
160
- }>;
161
- query(namespace: string, query: Extract<EngineQuery, {
162
- readonly vector: ReadonlyArray<number>;
163
- }>): Promise<ReadonlyArray<Match>>;
164
- fetch(namespace: string, ids: ReadonlyArray<string>): Promise<ReadonlyArray<Vector>>;
165
- delete(namespace: string, ids: ReadonlyArray<string>): Promise<void>;
166
- }
167
- /**
168
- * Making and dropping Vector namespaces: the platform's, never a Site's. `create` of one that exists
169
- * with the same settings does nothing, and with others is `conflict`; `drop` of one that does not
170
- * exist does nothing.
171
- */
172
- interface VectorControl {
173
- /** `embed` is the embedding model whose vectors the namespace holds; without one, it takes values only. */
174
- create(namespace: string, settings: {
175
- readonly dimension: number;
176
- readonly metric: Metric;
177
- readonly embed?: string;
178
- }): Promise<void>;
179
- drop(namespace: string): Promise<void>;
180
- }
181
- /** Vector DB over `engine`. */
182
- declare function vectorDb(engine: VectorEngine): VectorDb;
183
- /**
184
- * `engine`, which keeps only values, taking text too: the texts of each call are embedded by `embed`,
185
- * given the namespace and the texts in order, before `engine` sees the call. `embed` returns
186
- * `undefined` for a namespace made without an embedding model, which is `invalid`.
187
- *
188
- * const site = embedded(engine, (namespace, texts) => vector.embed(namespace, texts))
189
- */
190
- declare function embedded(engine: ValuesEngine, embed: (namespace: string, texts: ReadonlyArray<string>) => Promise<ReadonlyArray<ReadonlyArray<number>> | undefined>): VectorEngine;
191
- //#endregion
192
- export { MAX_TOP_K as C, vectorErrorCodes as D, VectorErrorCode as E, MAX_TEXT as S, VectorError as T, embedded as _, Match as a, MAX_DIMENSION as b, Namespace as c, TextVector as d, ValuesEngine as f, VectorEngine as g, VectorDb as h, Filter as i, NamespaceInfo as l, VectorControl as m, Consistency as n, MetadataValue as o, Vector as p, EngineQuery as r, Metric as s, Condition as t, QueryOptions as u, vectorDb as v, MAX_VALUE as w, MAX_METADATA_BYTES as x, MAX_BATCH as y };
@@ -1,142 +0,0 @@
1
- //#region src/database/schema.ts
2
- /** A table's name: a leading `_` is the Database's own. */
3
- const TABLE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/u;
4
- const v = Object.freeze({
5
- string: () => "string",
6
- number: () => "number",
7
- boolean: () => "boolean",
8
- /** Any JSON value, at any depth. */
9
- document: () => "document",
10
- /** May be left out or null. */
11
- optional: (shape) => ({ optional: shape }),
12
- array: (shape) => ({ array: shape }),
13
- object: (fields) => ({ object: fields }),
14
- int64: () => "int64",
15
- bytes: () => "bytes",
16
- timestamp: () => "timestamp",
17
- decimal: () => "decimal",
18
- literal: (value) => ({ literal: value }),
19
- union: (...shapes) => ({ union: shapes }),
20
- record: (shape) => ({ record: shape }),
21
- id: (table) => ({ id: String(table) })
22
- });
23
- const INDEX = /^[A-Za-z][A-Za-z0-9_]{0,63}$/u;
24
- const INDEX_FIELDS = 8;
25
- const RESERVED_INDEXES = /* @__PURE__ */ new Set(["by_id", "by_creation_time"]);
26
- /** Whether an index may order a field of this shape: what the Database orders, its keys comparing as their values do. */
27
- function orderable(shape) {
28
- const inner = shape && typeof shape === "object" && "optional" in shape ? shape.optional : shape;
29
- if (typeof inner === "string") return [
30
- "string",
31
- "number",
32
- "boolean",
33
- "int64",
34
- "timestamp"
35
- ].includes(inner);
36
- if (!inner) return false;
37
- if ("id" in inner) return true;
38
- if ("literal" in inner) return [
39
- "string",
40
- "number",
41
- "boolean"
42
- ].includes(typeof inner.literal);
43
- if ("union" in inner) return inner.union.every(orderable);
44
- return false;
45
- }
46
- function tableOf(fields, indexes) {
47
- return Object.freeze({
48
- fields,
49
- indexes,
50
- index(name, field, { unique = false } = {}) {
51
- if (typeof name !== "string" || !INDEX.test(name) || RESERVED_INDEXES.has(name)) throw new TypeError(`index ${JSON.stringify(name)}: a name of [A-Za-z][A-Za-z0-9_]{0,63}, not by_id or by_creation_time`);
52
- if (name in indexes) throw new TypeError(`index ${name}: declared twice`);
53
- const list = Array.isArray(field) ? field : [field];
54
- if (!list.length || list.length > INDEX_FIELDS || new Set(list).size !== list.length) throw new TypeError(`index ${name}: a field, or a list of up to ${INDEX_FIELDS} different fields`);
55
- for (const one of list) {
56
- if (typeof one !== "string" || !(one in fields)) throw new TypeError(`index ${name}: ${JSON.stringify(one)} is not a field of the table`);
57
- if (!orderable(fields[one])) throw new TypeError(`index ${name}: ${one} is not a string, number or boolean`);
58
- }
59
- const on = list.length === 1 ? list[0] : Object.freeze([...list]);
60
- return tableOf(fields, Object.freeze({
61
- ...indexes,
62
- [name]: unique ? Object.freeze({
63
- fields: on,
64
- unique: true
65
- }) : on
66
- }));
67
- },
68
- searchIndex(name) {
69
- throw new TypeError(`searchIndex ${JSON.stringify(name)}: not available yet`);
70
- },
71
- vectorIndex(name) {
72
- throw new TypeError(`vectorIndex ${JSON.stringify(name)}: not available yet`);
73
- }
74
- });
75
- }
76
- /** An index's fields in order. */
77
- function indexFields(declared) {
78
- const fields = declared !== null && typeof declared === "object" && !Array.isArray(declared) ? declared.fields : declared;
79
- return Array.isArray(fields) ? [...fields] : [fields];
80
- }
81
- function defineTable(fields) {
82
- if (fields === null || typeof fields !== "object" || Array.isArray(fields)) throw new TypeError("defineTable({ <field>: v.<shape>() })");
83
- for (const [field, shape] of Object.entries(fields)) {
84
- if (field.startsWith("_")) throw new TypeError(`defineTable: ${field}: a leading _ is the Database's`);
85
- if (shapeError(shape, void 0, field)?.endsWith("not a shape")) throw new TypeError(`defineTable: ${field}: not a shape`);
86
- }
87
- return tableOf(Object.freeze({ ...fields }), Object.freeze({}));
88
- }
89
- function defineSchema(tables) {
90
- if (tables === null || typeof tables !== "object" || Array.isArray(tables)) throw new TypeError("defineSchema({ <table>: defineTable(...) })");
91
- const out = {};
92
- const indexes = {};
93
- for (const [name, table] of Object.entries(tables)) {
94
- if (!TABLE.test(name)) throw new TypeError(`defineSchema: "${name}" is not a table name`);
95
- if (!table?.fields) throw new TypeError(`defineSchema: "${name}" is not a defineTable(...)`);
96
- out[name] = table.fields;
97
- indexes[name] = table.indexes ?? Object.freeze({});
98
- }
99
- return Object.freeze({
100
- schema: true,
101
- tables: Object.freeze(out),
102
- indexes: Object.freeze(indexes)
103
- });
104
- }
105
- /** Whether `value` fits `shape`: null, or the reason. An id is a non-empty string. */
106
- function shapeError(shape, value, at = "the value") {
107
- const wrong = (what) => `${at}: ${what} expected`;
108
- if (shape === "document") return null;
109
- if (typeof shape === "string") switch (shape) {
110
- case "string": return typeof value === "string" ? null : wrong("a string");
111
- case "number": return typeof value === "number" && Number.isFinite(value) ? null : wrong("a number");
112
- case "boolean": return typeof value === "boolean" ? null : wrong("a boolean");
113
- case "int64": return Number.isSafeInteger(value) || typeof value === "string" && /^-?\d{1,19}$/u.test(value) ? null : wrong("a whole number of 64 bits");
114
- case "bytes": return typeof value === "string" && /^[A-Za-z0-9+/=_-]*$/u.test(value) ? null : wrong("bytes as base64");
115
- case "timestamp": return typeof value === "number" && Number.isFinite(value) ? null : wrong("a timestamp (milliseconds)");
116
- case "decimal": return typeof value === "string" && /^-?\d+(\.\d+)?$/u.test(value) ? null : wrong("a decimal as a string");
117
- default: return `${at}: no shape ${String(shape)}`;
118
- }
119
- if (shape && typeof shape === "object") {
120
- if ("optional" in shape) return value === void 0 || value === null ? null : shapeError(shape.optional, value, at);
121
- if ("array" in shape) return Array.isArray(value) ? value.map((item, k) => shapeError(shape.array, item, `${at}[${k}]`)).find(Boolean) ?? null : wrong("an array");
122
- if ("object" in shape) {
123
- if (value === null || typeof value !== "object" || Array.isArray(value)) return wrong("an object");
124
- const record = value;
125
- for (const key of Object.keys(record)) if (!(key in shape.object)) return `${at}.${key}: no such field`;
126
- for (const [key, inner] of Object.entries(shape.object)) {
127
- if (record[key] === void 0 && inner && typeof inner === "object" && "optional" in inner) continue;
128
- if (record[key] === void 0) return `${at}.${key}: missing`;
129
- const why = shapeError(inner, record[key], `${at}.${key}`);
130
- if (why) return why;
131
- }
132
- return null;
133
- }
134
- if ("literal" in shape) return JSON.stringify(value) === JSON.stringify(shape.literal) ? null : wrong(`the value ${JSON.stringify(shape.literal)}`);
135
- if ("union" in shape) return shape.union.some((one) => shapeError(one, value, at) === null) ? null : wrong("one of the union's shapes");
136
- if ("record" in shape) return value !== null && typeof value === "object" && !Array.isArray(value) ? Object.entries(value).map(([k, item]) => shapeError(shape.record, item, `${at}.${k}`)).find(Boolean) ?? null : wrong("an object");
137
- if ("id" in shape) return typeof value === "string" && value.length > 0 && value.length <= 256 ? null : wrong(`an id of ${shape.id}`);
138
- }
139
- return `${at}: not a shape`;
140
- }
141
- //#endregion
142
- export { shapeError as a, indexFields as i, defineSchema as n, v as o, defineTable as r, TABLE as t };