@midsummer-ai/sdk 0.1.0-next.900 → 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,9 +1,15 @@
1
- import { a as shapeError, i as indexFields } from "../schema-BF-Y1EVu.mjs";
2
- import { InsufficientError, NotFoundError, Refusal, isFunction } from "./server.mjs";
1
+ import { storage } from "../index.mjs";
2
+ import { standIn } from "../stand-in.mjs";
3
+ import { _ as shapeError, a as tagBytes, b as valueAt, f as indexFields, g as shapeAt, i as keyBytes, o as untagBytes, v as tableCode } from "../bytes-C2pcyl9u.mjs";
4
+ import { A as comparePrefix, M as indexTuple, O as valueKey, S as nextCron, T as readLimited, _ as isFunction, a as Refusal, b as limits, i as NotFoundError, j as documentBytes, k as compareKey, l as fetchOver, o as TooLarge, r as InsufficientError, y as isRouter } from "../server-EDRbF2u-.mjs";
3
5
  import { DatabaseError } from "./errors.mjs";
6
+ import { i as verifier, n as sessionEnd, r as trustedOf } from "../auth-1W-SzpD3.mjs";
7
+ import { standIn as standIn$1 } from "../vector/stand-in.mjs";
8
+ import { parse } from "acorn";
4
9
  import { mkdir, writeFile } from "node:fs/promises";
5
- import { join } from "node:path";
10
+ import { dirname, join } from "node:path";
6
11
  import { pathToFileURL } from "node:url";
12
+ import { AsyncLocalStorage } from "node:async_hooks";
7
13
  //#region src/database/stand-in.ts
8
14
  /**
9
15
  * The Database's Stand-in, for `midsummer dev`: a Project's own `db/` functions run in memory, with
@@ -17,46 +23,495 @@ import { pathToFileURL } from "node:url";
17
23
  * const database = databaseStandIn()
18
24
  * database.serve(await loadDatabase(built, folder))
19
25
  * const id = await database.client.as("ada").mutation("messages.send", { channel: "a", body: "hi" })
26
+ * const hook = await database.fetch(new Request("http://stand-in.localhost/http/hook", { method: "POST" }))
27
+ *
28
+ * Its files are kept in a Storage bucket (a Storage Stand-in's unless one is given). Its HTTP side,
29
+ * `fetch`, serves the files' URLs, the upload URLs and `/http<path>`, the HTTP actions.
30
+ *
31
+ * A caller signs in as a Database signs them in (`identify`): with a token of a provider
32
+ * `auth.config.ts` trusts, checked as `./auth` checks it, or with none where the Database admits
33
+ * anonymous callers.
20
34
  *
21
35
  * The Project's code runs in this process, as it does on its author's machine. Crons do not run
22
36
  * here yet.
37
+ *
38
+ * A search ranks by BM25 as published (k1 1.2, b 0.75, idf ln(1 + (N - df + 0.5) / (df + 0.5)), N
39
+ * the rows its field is text in and lengths against their mean), with equal scores newest first. The
40
+ * last word typed also matches the words it begins, each scored as itself, the best one counting.
41
+ * Words are letters and digits, in lower case, up to 32 bytes; longer ones are left out, and a
42
+ * search reads its first 16. That is what the contract promises; ties and tokens are Convex's.
43
+ *
44
+ * A vector index is served by a Vector engine, as the Database's are: a namespace of its own for each
45
+ * index, named for this Database alone, fed every committed change to the table, and asked by
46
+ * `ctx.vectorSearch` once every change before it is in. Vectors are sent at length 1, so a score is
47
+ * the cosine however long a vector is. A row whose field is not `dimensions` finite numbers, or is
48
+ * all zeros, is in no index. Each filter field's value is sent as `valueKey` gives it, so a missing
49
+ * field, null and any shape of value are told apart. An index whose feed failed is made again from
50
+ * the rows by the next search that needs it.
23
51
  */
24
- const SURFACE = /(\bfrom\s*)(["'])(@midsummer\/sdk\/server|\.\/_generated\/server(?:\.m?js)?)\2/gu;
52
+ /** Where the loaded surface waits for the shim each load imports it through. */
53
+ const HELD = Symbol.for("midsummer.database.surface");
54
+ /**
55
+ * The kind of function running now, through every await it makes: a module's global `fetch`
56
+ * reaches the network only inside an action, whatever module the call is written in.
57
+ */
58
+ const running = new AsyncLocalStorage();
59
+ /** Each load's own globals, by its folder: `process` (the environment's values it was loaded with) and `fetch`. */
60
+ const LOADS = Symbol.for("midsummer.database.loads");
25
61
  let loads = 0;
26
62
  /**
27
- * Writes a build's files under `folder` and loads them, each import of the surface naming this SDK.
28
- * Each load is a folder of its own, so a module loaded before never stands in for a newer one.
63
+ * The names a module binds in its own scope: its imports, its top-level declarations and their
64
+ * patterns, and every `var` outside a function, which binds there wherever it is written.
65
+ */
66
+ function topLevelNames(js) {
67
+ const names = /* @__PURE__ */ new Set();
68
+ const bind = (pattern) => {
69
+ if (!pattern) return;
70
+ if (pattern.type === "Identifier") names.add(pattern.name);
71
+ else if (pattern.type === "ObjectPattern") for (const p of pattern.properties) bind(p.type === "RestElement" ? p.argument : p.value);
72
+ else if (pattern.type === "ArrayPattern") for (const p of pattern.elements) bind(p);
73
+ else if (pattern.type === "AssignmentPattern") bind(pattern.left);
74
+ else if (pattern.type === "RestElement") bind(pattern.argument);
75
+ };
76
+ const tree = parse(js, {
77
+ ecmaVersion: "latest",
78
+ sourceType: "module"
79
+ });
80
+ for (const node of tree.body) {
81
+ const declaration = node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration" ? node.declaration : node;
82
+ if (node.type === "ImportDeclaration") for (const s of node.specifiers) names.add(s.local.name);
83
+ else if (declaration?.type === "VariableDeclaration") for (const one of declaration.declarations) bind(one.id);
84
+ else if ((declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration") && declaration.id) names.add(declaration.id.name);
85
+ }
86
+ const walk = (node) => {
87
+ if (/Function|StaticBlock/u.test(node.type)) return;
88
+ if (node.type === "VariableDeclaration" && node.kind === "var") for (const one of node.declarations) bind(one.id);
89
+ for (const value of Object.values(node)) if (Array.isArray(value)) {
90
+ for (const child of value) if (typeof child?.type === "string") walk(child);
91
+ } else if (typeof value?.type === "string") walk(value);
92
+ };
93
+ for (const node of tree.body) walk(node);
94
+ return names;
95
+ }
96
+ /**
97
+ * The host's globals a loaded module never sees, as a Database's realm has none of them: Node's
98
+ * and Bun's, and `process`, whose `env` is the load's values, never this process's. Each module of a build is
99
+ * loaded with these names bound to the stand-in values below, and `globalThis` (and `global`,
100
+ * `self`) to an object of its own holding only the allowed globals (`ALLOWED`). It is a boundary for honest code, so a function
101
+ * that works here works on the Database; it is no sandbox (`Function("return this")()` reaches past it).
102
+ */
103
+ const HIDDEN = [
104
+ "process",
105
+ "require",
106
+ "module",
107
+ "exports",
108
+ "Buffer",
109
+ "Bun",
110
+ "Deno",
111
+ "__dirname",
112
+ "__filename"
113
+ ];
114
+ const GLOBALS = [
115
+ "globalThis",
116
+ "global",
117
+ "self"
118
+ ];
119
+ /**
120
+ * The globals a loaded module's `globalThis` holds: the language's and the web's, as a Database's
121
+ * realm has them. Nothing else of the host's is on it.
122
+ */
123
+ const ALLOWED = [
124
+ "Object",
125
+ "Function",
126
+ "Array",
127
+ "Number",
128
+ "parseFloat",
129
+ "parseInt",
130
+ "Infinity",
131
+ "NaN",
132
+ "undefined",
133
+ "Boolean",
134
+ "String",
135
+ "Symbol",
136
+ "Date",
137
+ "Promise",
138
+ "RegExp",
139
+ "Error",
140
+ "AggregateError",
141
+ "EvalError",
142
+ "RangeError",
143
+ "ReferenceError",
144
+ "SyntaxError",
145
+ "TypeError",
146
+ "URIError",
147
+ "JSON",
148
+ "Math",
149
+ "Intl",
150
+ "ArrayBuffer",
151
+ "SharedArrayBuffer",
152
+ "Atomics",
153
+ "Uint8Array",
154
+ "Int8Array",
155
+ "Uint16Array",
156
+ "Int16Array",
157
+ "Uint32Array",
158
+ "Int32Array",
159
+ "Float32Array",
160
+ "Float64Array",
161
+ "Uint8ClampedArray",
162
+ "BigUint64Array",
163
+ "BigInt64Array",
164
+ "DataView",
165
+ "Map",
166
+ "BigInt",
167
+ "Set",
168
+ "WeakMap",
169
+ "WeakSet",
170
+ "Proxy",
171
+ "Reflect",
172
+ "FinalizationRegistry",
173
+ "WeakRef",
174
+ "decodeURI",
175
+ "decodeURIComponent",
176
+ "encodeURI",
177
+ "encodeURIComponent",
178
+ "escape",
179
+ "unescape",
180
+ "isFinite",
181
+ "isNaN",
182
+ "URL",
183
+ "URLSearchParams",
184
+ "TextEncoder",
185
+ "TextDecoder",
186
+ "TextEncoderStream",
187
+ "TextDecoderStream",
188
+ "atob",
189
+ "btoa",
190
+ "structuredClone",
191
+ "crypto",
192
+ "Crypto",
193
+ "CryptoKey",
194
+ "SubtleCrypto",
195
+ "console",
196
+ "setTimeout",
197
+ "clearTimeout",
198
+ "setInterval",
199
+ "clearInterval",
200
+ "queueMicrotask",
201
+ "Headers",
202
+ "Request",
203
+ "Response",
204
+ "Blob",
205
+ "File",
206
+ "FormData",
207
+ "ReadableStream",
208
+ "WritableStream",
209
+ "TransformStream",
210
+ "ReadableStreamDefaultReader",
211
+ "ByteLengthQueuingStrategy",
212
+ "CountQueuingStrategy",
213
+ "AbortController",
214
+ "AbortSignal",
215
+ "Event",
216
+ "EventTarget",
217
+ "DOMException",
218
+ "performance"
219
+ ];
220
+ /** Words a module can't declare a binding by, though a global may be named so. */
221
+ const RESERVED = /* @__PURE__ */ new Set([
222
+ "eval",
223
+ "arguments",
224
+ "await",
225
+ "break",
226
+ "case",
227
+ "catch",
228
+ "class",
229
+ "const",
230
+ "continue",
231
+ "debugger",
232
+ "default",
233
+ "delete",
234
+ "do",
235
+ "else",
236
+ "enum",
237
+ "export",
238
+ "extends",
239
+ "false",
240
+ "finally",
241
+ "for",
242
+ "function",
243
+ "if",
244
+ "implements",
245
+ "import",
246
+ "in",
247
+ "instanceof",
248
+ "interface",
249
+ "let",
250
+ "new",
251
+ "null",
252
+ "package",
253
+ "private",
254
+ "protected",
255
+ "public",
256
+ "return",
257
+ "static",
258
+ "super",
259
+ "switch",
260
+ "this",
261
+ "throw",
262
+ "true",
263
+ "try",
264
+ "typeof",
265
+ "var",
266
+ "void",
267
+ "while",
268
+ "with",
269
+ "yield"
270
+ ]);
271
+ let shutNames = null;
272
+ /**
273
+ * Every name the host's global has, its own and its prototypes', that a module may not see: each is bound
274
+ * to undefined on the module's first line, so a bare `WebSocket` or `Bun` is undefined, as on the Database.
275
+ */
276
+ function shut() {
277
+ if (shutNames) return shutNames;
278
+ const names = /* @__PURE__ */ new Set();
279
+ for (let at = globalThis; at; at = Object.getPrototypeOf(at)) for (const name of Object.getOwnPropertyNames(at)) names.add(name);
280
+ const seen = /* @__PURE__ */ new Set([
281
+ ...ALLOWED,
282
+ ...GLOBALS,
283
+ ...HIDDEN,
284
+ "process",
285
+ "fetch"
286
+ ]);
287
+ return shutNames = [...names].filter((name) => !seen.has(name) && !RESERVED.has(name) && /^[A-Za-z_$][\w$]*$/u.test(name)).sort();
288
+ }
289
+ function hostOf(process, fetch) {
290
+ const real = globalThis;
291
+ const box = Object.create(null);
292
+ for (const name of ALLOWED) {
293
+ if (!(name in real)) continue;
294
+ const value = real[name];
295
+ box[name] = typeof value === "function" && /^[a-z]/u.test(name) ? value.bind(real) : value;
296
+ }
297
+ for (const name of GLOBALS) box[name] = box;
298
+ box.process = process;
299
+ box.fetch = fetch;
300
+ return {
301
+ box,
302
+ process,
303
+ fetch
304
+ };
305
+ }
306
+ /**
307
+ * A built module as the Stand-in loads it: each import of the surface named by its shim, found
308
+ * by the parse so no string in the module is touched, and the host's globals bound to stand-ins on
309
+ * its first line, so every line stays where it was.
310
+ */
311
+ function loadable(path, text) {
312
+ const tree = parse(text, {
313
+ ecmaVersion: "latest",
314
+ sourceType: "module"
315
+ });
316
+ const up = "../".repeat(path.split("/").length - 1) || "./";
317
+ const own = topLevelNames(text);
318
+ const edits = [];
319
+ for (const node of tree.body) {
320
+ if (!node.source || !/^(Import|ExportNamed|ExportAll)Declaration$/u.test(node.type)) continue;
321
+ const spec = String(node.source.value);
322
+ const surface = /^@midsummer(?:-ai)?\/sdk\/server$/u.test(spec) ? "server" : /^\.\.?\//u.test(spec) ? GENERATED.exec(resolved(path, spec))?.[1] : void 0;
323
+ if (surface) edits.push({
324
+ at: node.source.start,
325
+ end: node.source.end,
326
+ text: JSON.stringify(`${up}_generated/${surface}.mjs`)
327
+ });
328
+ }
329
+ let out = text;
330
+ for (const edit of edits.sort((a, b) => b.at - a.at)) out = `${out.slice(0, edit.at)}${edit.text}${out.slice(edit.end)}`;
331
+ const bindings = [
332
+ ...GLOBALS.map((name) => `${name} = __host.box`),
333
+ "process = __host.process",
334
+ "fetch = __host.fetch",
335
+ ...HIDDEN.filter((name) => name !== "process").map((name) => `${name} = undefined`),
336
+ ...shut().map((name) => `${name} = undefined`)
337
+ ].filter((binding) => !own.has(binding.split(" ")[0]));
338
+ let host = "__host";
339
+ while (text.includes(host)) host = `_${host}`;
340
+ return `import * as ${host} from ${JSON.stringify(`${up}_generated/host.mjs`)}; const ${bindings.map((binding) => binding.replace("__host.", `${host}.`)).join(", ")}; ${out}`;
341
+ }
342
+ const GENERATED = /^_generated\/(server|api)(?:\.m?js)?$/u;
343
+ /** A relative import's path from the built file at `path`, by the build's paths. */
344
+ function resolved(path, spec) {
345
+ const out = path.split("/").slice(0, -1);
346
+ for (const part of spec.split("/")) if (part === "..") out.pop();
347
+ else if (part !== "." && part !== "") out.push(part);
348
+ return out.join("/");
349
+ }
350
+ /**
351
+ * Writes a build's files under `folder` and loads them, each import of the surface naming this SDK's
352
+ * `server.ts`. They reach it through a shim beside them, `_generated/server.mjs`, that re-exports the
353
+ * module loaded here: a file on disk can't import one inside a compiled CLI, where this SDK's files
354
+ * live only in the binary. Each load is a folder of its own, so a module loaded before never stands in
355
+ * for a newer one.
356
+ *
357
+ * `env` is the environment's values, each module's `process.env` (a copy: a module that sets one sets
358
+ * it for this load only). It is never written to disk; a change to it is a new load, as a deploy is.
359
+ * A module's global `fetch` is the network of the Stand-in that serves the load, https only, as
360
+ * `ctx.fetch` is, while an action runs; while a query or a mutation runs, or the module loads, it is
361
+ * refused, whichever module calls it. A module that binds `process` or `fetch` itself keeps its own.
29
362
  */
30
- async function loadDatabase(built, folder) {
31
- const server = new URL("./server.ts", import.meta.url).href;
363
+ async function loadDatabase(built, folder, options = {}) {
364
+ const surface = await import("./server.mjs");
365
+ globalThis[HELD] = surface;
366
+ const names = Object.keys(surface).filter((name) => name !== "default" && /^[A-Za-z_$][\w$]*$/.test(name));
32
367
  const dir = join(folder, `load-${process.pid}-${loads += 1}`);
368
+ let network = null;
369
+ const fetch = fetchOver((url, init) => {
370
+ if (running.getStore() !== "action") throw new TypeError("fetch: only an action reaches the network, never a query or a mutation");
371
+ if (!network) throw new TypeError("fetch: no network until a Stand-in serves this load");
372
+ return network(url, init);
373
+ });
374
+ const env = options.env ? Object.freeze({ ...options.env }) : null;
375
+ const globals = Object.freeze(hostOf(Object.freeze({ env: { ...env } }), fetch));
376
+ (globalThis[LOADS] ??= /* @__PURE__ */ new Map()).set(dir, globals);
33
377
  await mkdir(join(dir, "_generated"), { recursive: true });
34
378
  await writeFile(join(dir, "_generated", "api.mjs"), built.generated["api.mjs"]);
35
- for (const [name, text] of Object.entries(built.files)) await writeFile(join(dir, name), text.replace(SURFACE, (_all, from, quote) => `${from}${quote}${server}${quote}`));
379
+ await writeFile(join(dir, "_generated", "server.mjs"), `const surface = globalThis[Symbol.for("midsummer.database.surface")];\nexport const { ${names.join(", ")} } = surface;\n`);
380
+ await writeFile(join(dir, "_generated", "host.mjs"), `export const { box, process, fetch } = globalThis[Symbol.for("midsummer.database.loads")].get(${JSON.stringify(dir)});\n`);
381
+ for (const [name, text] of Object.entries(built.files)) {
382
+ await mkdir(dirname(join(dir, name)), { recursive: true });
383
+ await writeFile(join(dir, name), loadable(name, text));
384
+ }
36
385
  const functions = /* @__PURE__ */ new Map();
37
386
  for (const fn of built.functions) {
38
387
  const exported = (await import(pathToFileURL(join(dir, fn.file)).href))[fn.export];
39
388
  if (!isFunction(exported)) throw new Error(`${built.from[fn.file]}: ${fn.export} is not a function`);
40
389
  functions.set(fn.name, exported);
41
390
  }
391
+ let http = null;
392
+ if (built.http) {
393
+ const router = (await import(pathToFileURL(join(dir, built.http)).href)).default;
394
+ if (!isRouter(router)) throw new Error(`${built.from[built.http]}: its default export is not an httpRouter()`);
395
+ http = router;
396
+ }
42
397
  return {
43
398
  functions,
44
399
  tables: built.tables,
45
- indexes: built.indexes
400
+ indexes: built.indexes,
401
+ search: built.search,
402
+ vector: built.vector,
403
+ http,
404
+ auth: built.auth,
405
+ crons: built.crons ?? [],
406
+ env,
407
+ useNetwork: (next) => {
408
+ network = next;
409
+ }
46
410
  };
47
411
  }
412
+ /** How deep calls may nest in one call: deeper is refused, so a call that calls itself ends. */
413
+ const NESTED_DEPTH = 16;
414
+ /** How many times a nested mutation runs before a read that keeps changing under it refuses it. */
415
+ const NESTED_RUNS = 100;
48
416
  /** A value as the wire carries it: JSON, `undefined` gone. */
49
- const wire = (value) => value === void 0 ? null : JSON.parse(JSON.stringify(value));
417
+ /** A copy of `value` as the wire carries it: JSON, with bytes kept as bytes. */
418
+ const wire = (value) => value === void 0 ? null : JSON.parse(JSON.stringify(value, tagBytes), untagBytes);
50
419
  const hex = (bytes) => [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
51
420
  const nameOf = (fn) => typeof fn === "string" ? fn : fn.name;
52
- /** Orders index keys as the Database does: by type (null, numbers, strings, booleans), then by value. */
421
+ /** Orders index keys by value type, then by value, with missing fields before null. */
53
422
  function compare(a, b) {
54
- const rank = (x) => x === null || x === void 0 ? 0 : typeof x === "number" ? 1 : typeof x === "string" ? 2 : typeof x === "boolean" ? 3 : 4;
55
- const ra = rank(a), rb = rank(b);
56
- if (ra !== rb) return ra - rb;
57
- if (ra === 4) return 0;
58
- return a < b ? -1 : a > b ? 1 : 0;
423
+ return compareKey(a, b);
424
+ }
425
+ const WORD = /[\p{L}\p{N}]+/gu;
426
+ const encoder = new TextEncoder();
427
+ /** A text's words, in order: letters and digits, in lower case, up to 32 bytes each (longer ones left out). */
428
+ const wordsOf = (text) => (text.match(WORD) ?? []).map((word) => word.toLowerCase()).filter((word) => encoder.encode(word).length <= 32);
429
+ /**
430
+ * The Stand-in's search: BM25 over the rows whose field is text, of those matching `eq` (each its
431
+ * `valueKey`), best first, and equal scores newest first by creation time.
432
+ */
433
+ function searched(rows, declared, text, eq, limit, fields, after, through) {
434
+ const typed = wordsOf(text).slice(0, 16);
435
+ const prefix = typed.at(-1);
436
+ const exact = new Set(typed.slice(0, -1).filter((word) => word !== prefix));
437
+ const docs = rows.flatMap((row) => {
438
+ const body = valueAt(row, declared.field);
439
+ if (typeof body !== "string") return [];
440
+ const counts = /* @__PURE__ */ new Map();
441
+ const words = wordsOf(body);
442
+ for (const word of words) counts.set(word, (counts.get(word) ?? 0) + 1);
443
+ return [{
444
+ row,
445
+ counts,
446
+ length: words.length
447
+ }];
448
+ });
449
+ const n = docs.length;
450
+ const mean = n ? docs.reduce((sum, doc) => sum + doc.length, 0) / n : 1;
451
+ const df = /* @__PURE__ */ new Map();
452
+ for (const doc of docs) for (const word of doc.counts.keys()) df.set(word, (df.get(word) ?? 0) + 1);
453
+ const weight = (word, doc) => {
454
+ const tf = doc.counts.get(word) ?? 0, d = df.get(word) ?? 0;
455
+ if (!tf || !d) return 0;
456
+ return Math.log(1 + (n - d + .5) / (d + .5)) * tf * 2.2 / (tf + 1.2 * (.25 + .75 * doc.length / Math.max(mean, 1e-9)));
457
+ };
458
+ const shapeOf = (field) => fields ? shapeAt(fields, field) : void 0;
459
+ const want = Object.entries(eq).map(([field, value]) => [field, valueKey(value, shapeOf(field))]);
460
+ const scored = [];
461
+ for (const doc of docs) {
462
+ if (!want.every(([field, key]) => valueKey(valueAt(doc.row, field), shapeOf(field)) === key)) continue;
463
+ let score = 0;
464
+ for (const word of exact) score += weight(word, doc);
465
+ if (prefix !== void 0) score += Math.max(0, ...[...doc.counts.keys()].filter((word) => word.startsWith(prefix)).map((word) => weight(word, doc)));
466
+ if (score > 0) scored.push({
467
+ row: doc.row,
468
+ score
469
+ });
470
+ }
471
+ const created = (row) => Number(row._creationTime);
472
+ const order = (a, b) => b.score - a.score || b.created - a.created || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
473
+ const ranked = scored.map(({ row, score }) => ({
474
+ row,
475
+ at: {
476
+ id: row._id,
477
+ score,
478
+ created: created(row)
479
+ }
480
+ })).sort((a, b) => order(a.at, b.at));
481
+ const placed = (position) => {
482
+ const next = ranked.findIndex((one) => order(one.at, position) > 0);
483
+ return next < 0 ? ranked.length : next;
484
+ };
485
+ const start = after ? placed(after) : 0;
486
+ const end = through ? placed(through) : ranked.length;
487
+ return ranked.slice(start, Math.max(start, end)).slice(0, limit).map(({ row, at }) => ({
488
+ ...row,
489
+ _score: at.score
490
+ }));
491
+ }
492
+ /**
493
+ * A row's vector for `declared` at length 1, and its filter fields' `valueKey`s by position; null
494
+ * when it is in no index: not `dimensions` finite numbers, or all zeros.
495
+ */
496
+ function vectorOf(row, declared, fields) {
497
+ const values = unit(valueAt(row, declared.field), declared.dimensions);
498
+ if (!values) return null;
499
+ return {
500
+ values,
501
+ metadata: Object.fromEntries(declared.filters.map((field, k) => [`f${k}`, valueKey(valueAt(row, field), fields ? shapeAt(fields, field) : void 0)]))
502
+ };
503
+ }
504
+ /** `values` scaled to length 1 without overflowing, or null when they are not `dimensions` finite numbers or are all zeros. */
505
+ function unit(values, dimensions) {
506
+ if (!Array.isArray(values) || values.length !== dimensions || !values.every((x) => typeof x === "number" && Number.isFinite(x))) return null;
507
+ const largest = Math.max(...values.map(Math.abs));
508
+ if (!largest) return null;
509
+ const scaled = values.map((x) => x / largest);
510
+ const length = Math.hypot(...scaled);
511
+ return scaled.map((x) => x / length);
59
512
  }
513
+ /** Who a caller is, for the answers kept under their tags: the server, or a user of one issuer. */
514
+ const callerKey = (caller) => JSON.stringify(caller.server ? ["server"] : [caller.issuer ?? null, caller.user]);
60
515
  /** Why a call was refused, as the client carries it. */
61
516
  function refusalOf(error) {
62
517
  if (error instanceof DatabaseError) return error;
@@ -67,44 +522,130 @@ function refusalOf(error) {
67
522
  }
68
523
  /**
69
524
  * `rows` are the rows it starts with, as `rows()` gave them (a branch's, from its parent);
70
- * `committed` is told every mutation's changes as it commits them, in order. `admits` is asked as a
525
+ * `committed` is told every mutation's changes as it commits them, in order, before they apply: one
526
+ * that throws refuses the commit, and nothing the mutation wrote is kept. `admits` is asked as a
71
527
  * mutation starts, and what it returns is asked in the same step as the mutation commits, with nothing
72
528
  * between: so the commit can require what held at the start (a Database's lifecycle version). A reason
73
529
  * refuses the commit, and the mutation is refused as `unavailable` with nothing it wrote kept.
74
530
  * `read` is told how many rows each read gave a function, a mutation's own writes included.
531
+ * Legacy rows without creation metadata read as time 0. Their first later write stores 0 and keeps it.
532
+ * `network` is what an action's `ctx.fetch` and global `fetch` reach (the real network unless given).
533
+ * `storage` keeps the files, in its bucket `database-files` under `database/` (a random name unless
534
+ * given), so Databases that share a Storage never reach each other's files. `origin` is where `fetch`
535
+ * is served, which the files' and upload URLs start with. `verify` turns an HTTP request's bearer
536
+ * token into its caller's subject, or null when it does not verify; without it every HTTP action's
537
+ * caller is anonymous. `limits.fileBytes` lowers the largest file (`limits.fileBytes` of the server).
75
538
  */
76
539
  function databaseStandIn(options = {}) {
77
540
  const clock = options.clock ?? Date.now;
78
541
  const random = options.random ?? ((bytes) => crypto.getRandomValues(new Uint8Array(bytes)));
542
+ const network = options.network ?? ((url, init) => fetch(url, init));
543
+ const origin = options.origin ?? (() => "http://stand-in.localhost");
544
+ const bucket = (options.storage ?? storage(standIn({ clock }))).bucket("database-files");
545
+ const scope = options.database ?? hex(random(8));
546
+ const keyOf = (id) => `${scope}/${id}`;
547
+ const fileLimit = Math.min(options.limits?.fileBytes ?? limits.fileBytes, limits.fileBytes);
548
+ const files = new Map(Object.entries(options.files ?? {}));
549
+ const unswept = /* @__PURE__ */ new Set();
550
+ const uploads = /* @__PURE__ */ new Map();
79
551
  const tables = new Map(Object.entries(options.rows ?? {}).map(([name, rows]) => [name, new Map(Object.entries(rows))]));
80
552
  const answers = /* @__PURE__ */ new Map();
553
+ /** Each watch: `check` runs its query again and gives back what to tell its caller, or nothing when it didn't change. */
81
554
  const watchers = /* @__PURE__ */ new Set();
555
+ let waking = Promise.resolve();
556
+ /**
557
+ * Runs every watched query again after a change and tells their callers in one turn, so a socket
558
+ * sends one change's values together and related queries never show half of it. Wakes run in turn,
559
+ * so an older change's values never arrive after a newer one's.
560
+ */
561
+ const wake = () => {
562
+ waking = waking.then(async () => {
563
+ for (const tell of await Promise.all([...watchers].map((watcher) => watcher.check()))) told(tell);
564
+ }).catch((error) => {
565
+ console.error("Watches could not be run again:", error);
566
+ });
567
+ return waking;
568
+ };
569
+ /** Tells a watch's caller its value. A callback that throws is the caller's bug: it is reported, and stops no other watch nor a later value. */
570
+ const told = (tell) => {
571
+ try {
572
+ tell?.();
573
+ } catch (error) {
574
+ console.error("A watch's callback threw:", error);
575
+ }
576
+ };
82
577
  const scheduled = /* @__PURE__ */ new Map();
83
578
  let loaded = null;
579
+ /**
580
+ * The deployment a call was taken from, held from its selection to its end: its handler, schema, indexes,
581
+ * auth config and environment are all that one's, whatever is served meanwhile. A call it makes or schedules is
582
+ * taken anew, so it is the deployment served then. Outside a call, the one served now.
583
+ */
584
+ const calling = new AsyncLocalStorage();
585
+ const deployment = () => {
586
+ const call = calling.getStore();
587
+ return call ? call.served : loaded;
588
+ };
84
589
  let turn = Promise.resolve();
590
+ const vectors = options.vector ?? standIn$1();
591
+ /**
592
+ * Each vector index's namespace, by table and index: what it was made for, and whether a feed to it
593
+ * failed, when it is made again from the rows before it is searched. Its name is this Database's
594
+ * alone, so Databases sharing an engine never share one.
595
+ */
596
+ const namespaces = /* @__PURE__ */ new Map();
597
+ const own = `db-${hex(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(6)))}`;
598
+ let made = 0;
599
+ /** Every change sent to the vector indexes, in order: a vector search waits for it. */
600
+ let fed = Promise.resolve();
601
+ let trust = null;
602
+ const verifiers = /* @__PURE__ */ new Map();
603
+ function trustFor(next) {
604
+ if (!next.auth?.providers.length) return null;
605
+ try {
606
+ const trusted = trustedOf(next.auth, next.env ? (name) => next.env[name] : env);
607
+ const key = JSON.stringify(trusted);
608
+ let verify = verifiers.get(key);
609
+ if (!verify) verifiers.set(key, verify = verifier(trusted, {
610
+ ...options.fetch ? { fetch: options.fetch } : {},
611
+ now: clock
612
+ }));
613
+ return verify;
614
+ } catch (error) {
615
+ return new DatabaseError("unavailable", error.message);
616
+ }
617
+ }
618
+ const env = options.env ?? ((name) => globalThis.process?.env?.[name]);
85
619
  const tableOf = (name) => {
86
620
  let table = tables.get(name);
87
621
  if (!table) tables.set(name, table = /* @__PURE__ */ new Map());
88
622
  return table;
89
623
  };
90
624
  /**
91
- * The rows a function reads: the committed ones, and those `overlay` wrote, which a mutation's own
92
- * reads see. Each is a copy, so a function that changes a value it read changes only its copy: a
93
- * kept row changes only by a write that commits, and so does every Database or branch sharing it.
625
+ * The rows a function reads: the committed ones, and those `layer` and the layers under it wrote,
626
+ * which a mutation's own reads see. Each is a copy, so a function that changes a value it read
627
+ * changes only its copy: a kept row changes only by a write that commits, and so does every
628
+ * Database or branch sharing it.
94
629
  */
95
- function reading(overlay) {
630
+ function reading(layer, counted = true) {
96
631
  const get = (table, id) => {
97
- const written = overlay?.get(table);
98
- const row = written?.has(id) ? written.get(id) : tables.get(table)?.get(id);
632
+ let row;
633
+ for (let at = layer; at && row === void 0; at = at.parent ?? void 0) {
634
+ const written = at.writes.get(table);
635
+ if (written?.has(id)) row = written.get(id);
636
+ }
637
+ if (row === void 0) row = tables.get(table)?.get(id);
99
638
  return row ? structuredClone(row) : null;
100
639
  };
101
- const counted = (table, id) => {
640
+ const read = (table, id) => {
102
641
  const row = get(table, id);
103
- if (row) options.read?.(1);
642
+ if (row && counted) options.read?.(1);
104
643
  return row;
105
644
  };
106
645
  const range = (table, index, bounds) => {
107
- const rows = [.../* @__PURE__ */ new Set([...tables.get(table)?.keys() ?? [], ...overlay?.get(table)?.keys() ?? []])].flatMap((id) => {
646
+ const ids = new Set(tables.get(table)?.keys() ?? []);
647
+ for (let at = layer; at; at = at.parent ?? void 0) for (const id of at.writes.get(table)?.keys() ?? []) ids.add(id);
648
+ const rows = [...ids].flatMap((id) => {
108
649
  const row = get(table, id);
109
650
  return row ? [{
110
651
  ...row,
@@ -112,22 +653,32 @@ function databaseStandIn(options = {}) {
112
653
  }] : [];
113
654
  });
114
655
  let fields = [];
115
- if (index !== "_id") {
116
- const declared = loaded?.indexes?.[table]?.[index];
656
+ if (index === "by_creation_time") fields = ["_creationTime"];
657
+ else if (index !== "_id" && index !== "by_id") {
658
+ const declared = deployment()?.indexes?.[table]?.[index];
117
659
  if (declared === void 0) throw new Refusal("invalid", `${table} has no index ${index}`);
118
- fields = indexFields(declared);
660
+ fields = [...indexFields(declared), "_creationTime"];
119
661
  }
120
- const keyOf = (row) => index === "_id" ? [row._id] : [...fields.map((field) => row[field]), row._id];
662
+ const keyFields = [...fields, "_id"];
663
+ const tuple = (values) => indexTuple(values, keyFields, deployment()?.tables?.[table]);
664
+ const keyOf = (row) => tuple([...fields.map((field) => field === "_creationTime" ? row._creationTime : row[field]), row._id]);
121
665
  const eq = bounds.eq ?? [];
122
- const at = eq.length;
666
+ if (!Number.isSafeInteger(bounds.limit) || bounds.limit < 0 || !Array.isArray(eq) || eq.length > fields.length + 1 || bounds.order !== void 0 && bounds.order !== "asc" && bounds.order !== "desc") throw new Refusal("invalid", "invalid index range");
667
+ for (const bound of [
668
+ bounds.gt,
669
+ bounds.gte,
670
+ bounds.lt,
671
+ bounds.lte
672
+ ]) if (bound !== void 0 && (!Array.isArray(bound) || bound.length === 0 || bound.length > fields.length + 1)) throw new Refusal("invalid", "invalid index bound");
673
+ const equality = tuple(eq);
674
+ const gte = bounds.gte && tuple(bounds.gte), gt = bounds.gt && tuple(bounds.gt), lte = bounds.lte && tuple(bounds.lte), lt = bounds.lt && tuple(bounds.lt);
123
675
  const kept = rows.filter((row) => {
124
676
  const key = keyOf(row);
125
- if (eq.some((value, k) => compare(key[k], value) !== 0)) return false;
126
- const next = key[at];
127
- if (bounds.gte !== void 0 && compare(next, bounds.gte) < 0) return false;
128
- if (bounds.gt !== void 0 && compare(next, bounds.gt) <= 0) return false;
129
- if (bounds.lte !== void 0 && compare(next, bounds.lte) > 0) return false;
130
- if (bounds.lt !== void 0 && compare(next, bounds.lt) >= 0) return false;
677
+ if (comparePrefix(key, equality) !== 0) return false;
678
+ if (gte !== void 0 && comparePrefix(key, gte) < 0) return false;
679
+ if (gt !== void 0 && comparePrefix(key, gt) <= 0) return false;
680
+ if (lte !== void 0 && comparePrefix(key, lte) > 0) return false;
681
+ if (lt !== void 0 && comparePrefix(key, lt) >= 0) return false;
131
682
  return true;
132
683
  });
133
684
  kept.sort((a, b) => {
@@ -139,18 +690,178 @@ function databaseStandIn(options = {}) {
139
690
  return 0;
140
691
  });
141
692
  if (bounds.order === "desc") kept.reverse();
142
- const page = kept.slice(0, bounds.limit);
143
- options.read?.(page.length);
693
+ let page = kept.slice(0, bounds.limit);
694
+ if (bounds.bytes !== void 0) {
695
+ let spent = 0;
696
+ const at = page.findIndex((row) => (spent += documentBytes(row)) >= bounds.bytes);
697
+ if (at >= 0) page = page.slice(0, at + 1);
698
+ }
699
+ if (counted) options.read?.(page.length);
700
+ return page;
701
+ };
702
+ const search = (table, index, text, eq, limit, after, through) => {
703
+ const declared = deployment()?.search?.[table]?.[index];
704
+ if (!declared) throw new Refusal("invalid", `${table} has no search index ${index}`);
705
+ if (declared.staged) throw new Refusal("invalid", `${table}.${index}: the index is staged; it serves no search until it is not`);
706
+ for (const field of Object.keys(eq)) if (!declared.filters.includes(field)) throw new Refusal("invalid", `${table}.${index}: ${field} is not one of its filterFields`);
707
+ const ids = new Set(tables.get(table)?.keys() ?? []);
708
+ for (let at = layer; at; at = at.parent ?? void 0) for (const id of at.writes.get(table)?.keys() ?? []) ids.add(id);
709
+ const page = searched([...ids].flatMap((id) => {
710
+ const row = get(table, id);
711
+ return row ? [{
712
+ ...row,
713
+ _id: id
714
+ }] : [];
715
+ }), declared, String(text), eq, Math.max(0, Math.floor(limit)), deployment()?.tables?.[table], after, through);
716
+ if (counted) options.read?.(page.length);
144
717
  return page;
145
718
  };
146
719
  return {
147
- get: counted,
720
+ get: read,
148
721
  range,
722
+ search,
149
723
  peek: get
150
724
  };
151
725
  }
152
- function schedule(ms, name, args) {
153
- const id = `s${hex(random(8))}`;
726
+ /**
727
+ * Runs `work` on the vector indexes after every change sent before it. `work` marks the namespace
728
+ * it fails on as broken; if it throws anyway, every namespace is, so none is searched stale and the
729
+ * next search of each makes it again. The chain itself never stays failed.
730
+ */
731
+ function feeding(work) {
732
+ fed = fed.then(work).catch(() => {
733
+ for (const namespace of namespaces.values()) namespace.broken = true;
734
+ });
735
+ return fed;
736
+ }
737
+ const pointsOf = (table, declared) => [...tables.get(table) ?? []].flatMap(([id, row]) => {
738
+ const point = vectorOf(row, declared, loaded?.tables?.[table]);
739
+ return point ? [{
740
+ id,
741
+ values: point.values,
742
+ metadata: point.metadata
743
+ }] : [];
744
+ });
745
+ /** Makes a namespace and fills it from the rows; a failure leaves it broken, to be made again. */
746
+ async function build(key, table, declared) {
747
+ const namespace = {
748
+ name: `${own}-${made += 1}`,
749
+ table,
750
+ declared,
751
+ broken: true
752
+ };
753
+ namespaces.set(key, namespace);
754
+ try {
755
+ await vectors.create(namespace.name, {
756
+ dimension: declared.dimensions,
757
+ metric: "cosine"
758
+ });
759
+ const points = pointsOf(table, declared);
760
+ for (let at = 0; at < points.length; at += 100) await vectors.upsert(namespace.name, points.slice(at, at + 100));
761
+ namespace.broken = false;
762
+ } catch {}
763
+ }
764
+ /** Namespaces whose drop failed: each later feed tries them again until they are gone, so no old vectors stay behind. */
765
+ const dropping = /* @__PURE__ */ new Set();
766
+ async function drop(name) {
767
+ try {
768
+ await vectors.drop(name);
769
+ dropping.delete(name);
770
+ } catch {
771
+ dropping.add(name);
772
+ }
773
+ }
774
+ /** Sends committed changes to the vector indexes of their tables. */
775
+ function feed(changes) {
776
+ const sending = changes.filter((change) => loaded?.vector?.[change.table]);
777
+ if (!sending.length && !dropping.size) return;
778
+ feeding(async () => {
779
+ for (const name of [...dropping]) await drop(name);
780
+ for (const change of sending) for (const namespace of namespaces.values()) {
781
+ if (namespace.table !== change.table || namespace.broken) continue;
782
+ const point = vectorOf(change.row, namespace.declared, loaded?.tables?.[namespace.table]);
783
+ try {
784
+ if (point) await vectors.upsert(namespace.name, [{
785
+ id: change.id,
786
+ values: point.values,
787
+ metadata: point.metadata
788
+ }]);
789
+ else await vectors.delete(namespace.name, [change.id]);
790
+ } catch {
791
+ namespace.broken = true;
792
+ }
793
+ }
794
+ });
795
+ }
796
+ /** Makes a namespace for each vector index `next` declares and serves (not staged), filled from the rows, and drops those it no longer does. */
797
+ function indexVectors(next) {
798
+ feeding(async () => {
799
+ const wanted = new Map(Object.entries(next.vector ?? {}).flatMap(([table, indexes]) => Object.entries(indexes).filter(([, declared]) => !declared.staged).map(([index, declared]) => [`${table}\u0000${index}`, {
800
+ table,
801
+ declared
802
+ }])));
803
+ for (const [key, namespace] of [...namespaces]) {
804
+ const want = wanted.get(key);
805
+ if (want && JSON.stringify(want.declared) === JSON.stringify(namespace.declared)) {
806
+ wanted.delete(key);
807
+ continue;
808
+ }
809
+ namespaces.delete(key);
810
+ await drop(namespace.name);
811
+ }
812
+ for (const [key, { table, declared }] of wanted) await build(key, table, declared);
813
+ });
814
+ }
815
+ /**
816
+ * A vector index's nearest rows once every change before it is in. A filter asks once for each
817
+ * field it names (the engine's filter is all of its fields) and keeps each row's best; an empty one
818
+ * finds nothing.
819
+ */
820
+ async function vectorSearch(table, index, query) {
821
+ const declared = deployment()?.vector?.[table]?.[index];
822
+ if (!declared) throw new Refusal("invalid", `${table} has no vector index ${index}`);
823
+ if (declared.staged) throw new Refusal("invalid", `${table}.${index}: the index is staged; it serves no search until it is not`);
824
+ const key = `${table}\u0000${index}`;
825
+ await feeding(async () => {
826
+ const namespace = namespaces.get(key);
827
+ if (namespace?.broken) {
828
+ await drop(namespace.name);
829
+ await build(key, table, declared);
830
+ }
831
+ });
832
+ const namespace = namespaces.get(key);
833
+ if (!namespace) throw new Refusal("invalid", `${table} has no vector index ${index}`);
834
+ if (namespace.broken) throw new Refusal("unavailable", `${table}.${index}: the vector index can't be reached right now. Try again.`);
835
+ const vector = unit(query.vector, declared.dimensions);
836
+ if (!vector) throw new Refusal("invalid", `${table}.${index}: a vector of ${declared.dimensions} finite numbers, not all zeros`);
837
+ const byField = /* @__PURE__ */ new Map();
838
+ for (const [field, value] of query.filter ?? []) {
839
+ const at = declared.filters.indexOf(field);
840
+ if (at < 0) throw new Refusal("invalid", `${table}.${index}: ${field} is not one of its filterFields`);
841
+ byField.set(`f${at}`, [...byField.get(`f${at}`) ?? [], valueKey(value, deployment()?.tables?.[table] ? shapeAt(deployment().tables[table], field) : void 0)]);
842
+ }
843
+ if (query.filter && !byField.size) return [];
844
+ const ask = (filter) => vectors.query(namespace.name, {
845
+ vector,
846
+ topK: query.limit,
847
+ includeValues: false,
848
+ includeMetadata: false,
849
+ ...filter ? { filter } : {}
850
+ });
851
+ let found;
852
+ try {
853
+ found = byField.size ? (await Promise.all([...byField].map(([field, values]) => ask({ [field]: { $in: values } })))).flat() : await ask();
854
+ } catch {
855
+ throw new Refusal("unavailable", `${table}.${index}: the vector index can't be reached right now. Try again.`);
856
+ }
857
+ const best = /* @__PURE__ */ new Map();
858
+ for (const match of found) best.set(match.id, Math.max(best.get(match.id) ?? -Infinity, match.score));
859
+ return [...best].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).slice(0, query.limit).map(([_id, _score]) => ({
860
+ _id,
861
+ _score
862
+ }));
863
+ }
864
+ function schedule(ms, name, args, id = `s${hex(random(8))}`) {
154
865
  const entry = {
155
866
  name,
156
867
  args: wire(args),
@@ -191,8 +902,8 @@ function databaseStandIn(options = {}) {
191
902
  entry.state = "canceled";
192
903
  return true;
193
904
  };
194
- function functionFor(name, kind, caller) {
195
- const fn = loaded?.functions.get(name);
905
+ function functionFor(served, name, kind, caller) {
906
+ const fn = served?.functions.get(name);
196
907
  if (!fn) throw new DatabaseError("no function", `no function ${name}`);
197
908
  if (fn.options.kind !== kind) throw new DatabaseError("no function", `no ${kind} ${name} (it is a ${fn.options.kind})`);
198
909
  if (fn.options.internal && !caller.internal) throw new DatabaseError("internal", `${name} is internal: no client may call it`);
@@ -214,26 +925,261 @@ function databaseStandIn(options = {}) {
214
925
  const refusedRows = (what) => () => {
215
926
  throw new DatabaseError("refused", `a query ${what}: only a mutation writes`);
216
927
  };
928
+ const fileUrl = (id) => files.has(id) ? `${origin()}/files/${encodeURIComponent(id)}` : null;
929
+ const fileMetadata = (id) => files.get(id) ?? null;
930
+ /** The tables that have rows, committed or written in `layer` or a layer under it. */
931
+ const tablesIn = (layer) => () => {
932
+ const names = new Set(tables.keys());
933
+ for (let at = layer; at; at = at.parent ?? void 0) for (const name of at.writes.keys()) names.add(name);
934
+ return [...names];
935
+ };
936
+ const UPLOAD_MS = 36e5;
937
+ const newUpload = (token) => `${origin()}/files?upload=${token}`;
938
+ const filesChanged = () => {
939
+ wake();
940
+ };
941
+ /**
942
+ * Removes the bytes of files already gone from `files`. A delete has happened once `files` lost the
943
+ * id, so a bucket that fails leaves the bytes in `unswept`, for the next sweep, and fails nothing.
944
+ */
945
+ async function sweep() {
946
+ for (const id of [...unswept]) try {
947
+ await bucket.delete(keyOf(id));
948
+ unswept.delete(id);
949
+ } catch {}
950
+ }
951
+ /** Deletes a file of this Database: another Database's id, or none, changes nothing. */
952
+ function forget(ids) {
953
+ const gone = ids.filter((id) => files.delete(id));
954
+ for (const id of gone) unswept.add(id);
955
+ if (gone.length) filesChanged();
956
+ }
957
+ async function keepFile(bytes, contentType) {
958
+ if (bytes.byteLength > fileLimit) throw new TooLarge("a file", fileLimit);
959
+ const id = `${tableCode("_storage")}${hex(random(12))}`;
960
+ await bucket.put(keyOf(id), bytes, { contentType });
961
+ const sha256 = btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))));
962
+ files.set(id, Object.freeze({
963
+ sha256,
964
+ size: bytes.byteLength,
965
+ contentType,
966
+ creationTime: clock()
967
+ }));
968
+ filesChanged();
969
+ return id;
970
+ }
971
+ /**
972
+ * `rows` with its nested calls (`runNested`): each runs the function it names on the same
973
+ * transaction, as call `<call>.<n>` (so a mutation it runs inserts ids of its own), internal ones
974
+ * admitted. In a mutation each nested call writes into a layer of its own over `layer`: put into
975
+ * `layer` when the call returns, dropped when it throws, so a nested call that fails undoes only
976
+ * itself, whatever its siblings did meanwhile.
977
+ */
978
+ function nesting(rows, depth, layer) {
979
+ let calls = 0;
980
+ const runNested = async (name, kind, args) => {
981
+ if (kind === "mutation" && !layer) throw new DatabaseError("refused", `a query runs no mutation (${name})`);
982
+ if (depth >= NESTED_DEPTH) throw new DatabaseError("refused", `${name}: calls nested more than ${NESTED_DEPTH} deep`);
983
+ const fn = functionFor(deployment(), name, kind, {
984
+ user: rows.user,
985
+ server: rows.server,
986
+ internal: true
987
+ });
988
+ const given = wire(args);
989
+ checked(fn, given);
990
+ const call = `${rows.call ?? "q"}.${(calls++).toString(36)}`;
991
+ if (!layer) return answered(fn, await fn.handler(nesting({
992
+ ...rows,
993
+ internal: true,
994
+ call
995
+ }, depth + 1, null), given));
996
+ for (let attempt = 1;; attempt += 1) {
997
+ open(layer);
998
+ const inner = layerOver(layer);
999
+ try {
1000
+ const value = answered(fn, await fn.handler(nesting({
1001
+ ...writing(inner, rows),
1002
+ internal: true,
1003
+ call
1004
+ }, depth + 1, inner), given));
1005
+ if (unchanged(inner)) {
1006
+ settle(inner);
1007
+ return value;
1008
+ }
1009
+ } catch (error) {
1010
+ if (unchanged(inner)) throw error;
1011
+ }
1012
+ if (attempt >= NESTED_RUNS) throw new DatabaseError("refused", `${name}: ran ${NESTED_RUNS} times, and each time what it read changed before it ended`);
1013
+ }
1014
+ };
1015
+ return {
1016
+ ...rows,
1017
+ runNested
1018
+ };
1019
+ }
1020
+ /** A layer of writes over `parent`, or the transaction's own. */
1021
+ const layerOver = (parent) => ({
1022
+ writes: /* @__PURE__ */ new Map(),
1023
+ later: [],
1024
+ cancels: /* @__PURE__ */ new Set(),
1025
+ tokens: [],
1026
+ dropped: [],
1027
+ reads: [],
1028
+ parent,
1029
+ ended: false
1030
+ });
1031
+ /** Whether everything a nested call read under its layer reads the same now, in the layer it would join. */
1032
+ const unchanged = (layer) => layer.reads.every((read) => JSON.stringify(read.look(reading(layer.parent, false)), keyBytes) === read.seen.get(layer.parent));
1033
+ const open = (layer) => {
1034
+ for (let at = layer; at; at = at.parent) if (at.ended) throw new DatabaseError("refused", "the mutation this call was part of has ended");
1035
+ };
1036
+ /** A nested call's layer, put into the one under it. */
1037
+ function settle(layer) {
1038
+ const parent = layer.parent;
1039
+ open(parent);
1040
+ for (const [table, changed] of layer.writes) {
1041
+ let into = parent.writes.get(table);
1042
+ if (!into) parent.writes.set(table, into = /* @__PURE__ */ new Map());
1043
+ for (const [id, row] of changed) into.set(id, row);
1044
+ }
1045
+ parent.later.push(...layer.later);
1046
+ for (const id of layer.cancels) parent.cancels.add(id);
1047
+ parent.tokens.push(...layer.tokens);
1048
+ parent.dropped.push(...layer.dropped);
1049
+ if (parent.parent) parent.reads.push(...layer.reads.filter((read) => read.seen.has(parent.parent)));
1050
+ }
1051
+ /** Whether a run is canceled in `layer` or a layer under it. */
1052
+ const canceledIn = (layer, id) => {
1053
+ for (let at = layer; at; at = at.parent) if (at.cancels.has(id)) return true;
1054
+ return false;
1055
+ };
1056
+ const droppedIn = (layer, id) => {
1057
+ for (let at = layer; at; at = at.parent) if (at.dropped.includes(id)) return true;
1058
+ return false;
1059
+ };
1060
+ const laterIn = (layer, id) => {
1061
+ for (let at = layer; at; at = at.parent) {
1062
+ const run = at.later.find((one) => one.id === id);
1063
+ if (run) return run;
1064
+ }
1065
+ return null;
1066
+ };
1067
+ /** A mutation's rows over `layer`: its reads see the layer's writes, and its writes, runs and cancels go into it. */
1068
+ function writing(layer, base) {
1069
+ const { get, range, search, peek } = reading(layer);
1070
+ /** A read, kept with what it gave over each layer under this one, so each join can check it still gives that. */
1071
+ const record = (look) => {
1072
+ const seen = /* @__PURE__ */ new Map();
1073
+ for (let at = layer.parent; at; at = at.parent) seen.set(at, JSON.stringify(look(reading(at, false)), keyBytes));
1074
+ if (seen.size) layer.reads.push({
1075
+ look,
1076
+ seen
1077
+ });
1078
+ };
1079
+ const written = (table) => {
1080
+ open(layer);
1081
+ let map = layer.writes.get(table);
1082
+ if (!map) layer.writes.set(table, map = /* @__PURE__ */ new Map());
1083
+ return map;
1084
+ };
1085
+ return {
1086
+ ...base,
1087
+ get: (table, id) => {
1088
+ record((view) => view.get(table, id));
1089
+ return get(table, id);
1090
+ },
1091
+ range: (table, index, bounds) => {
1092
+ record((view) => view.range(table, index, bounds));
1093
+ return range(table, index, bounds);
1094
+ },
1095
+ search: (table, index, text, eq, limit, after, through) => {
1096
+ record((view) => view.search(table, index, text, eq, limit, after, through));
1097
+ return search(table, index, text, eq, limit, after, through);
1098
+ },
1099
+ set: (table, id, fields) => {
1100
+ const previous = peek(table, id);
1101
+ written(table).set(id, structuredClone({
1102
+ ...fields,
1103
+ _creationTime: previous ? previous._creationTime : base.now,
1104
+ _version: (previous?._version ?? 0) + 1
1105
+ }));
1106
+ },
1107
+ delete: (table, id) => written(table).set(id, null),
1108
+ runAfter: (ms, name, args) => {
1109
+ open(layer);
1110
+ const id = `s${hex(random(8))}`;
1111
+ layer.later.push({
1112
+ id,
1113
+ ms,
1114
+ name,
1115
+ args,
1116
+ due: clock() + ms
1117
+ });
1118
+ return id;
1119
+ },
1120
+ cancelScheduled: (id) => {
1121
+ open(layer);
1122
+ const later = laterIn(layer, id);
1123
+ if (canceledIn(layer, id) || !later && scheduled.get(id)?.state !== "pending") return false;
1124
+ layer.cancels.add(id);
1125
+ return true;
1126
+ },
1127
+ scheduledRow: (id) => {
1128
+ const later = laterIn(layer, id);
1129
+ const row = later ? {
1130
+ name: later.name,
1131
+ args: wire(later.args),
1132
+ due: later.due,
1133
+ state: "pending"
1134
+ } : scheduledRow(id);
1135
+ return row && canceledIn(layer, id) && row.state === "pending" ? {
1136
+ ...row,
1137
+ state: "canceled"
1138
+ } : row;
1139
+ },
1140
+ fileUrl: (id) => droppedIn(layer, id) ? null : fileUrl(id),
1141
+ fileMetadata: (id) => droppedIn(layer, id) ? null : fileMetadata(id),
1142
+ tables: tablesIn(layer),
1143
+ uploadUrl: () => {
1144
+ open(layer);
1145
+ const token = hex(random(16));
1146
+ layer.tokens.push(token);
1147
+ return newUpload(token);
1148
+ },
1149
+ deleteFile: (id) => {
1150
+ open(layer);
1151
+ layer.dropped.push(id);
1152
+ }
1153
+ };
1154
+ }
217
1155
  async function runQuery(fn, args, caller) {
218
- const { get, range } = reading();
219
- const rows = {
1156
+ const { get, range, search } = reading();
1157
+ const rows = nesting({
220
1158
  get,
221
1159
  range,
1160
+ search,
1161
+ searchIndexes: deployment()?.search ?? {},
222
1162
  set: refusedRows("writes"),
223
1163
  delete: refusedRows("deletes"),
224
1164
  now: clock(),
225
1165
  user: caller.user,
226
1166
  server: caller.server,
227
- issuer: null,
1167
+ issuer: caller.issuer ?? null,
1168
+ claims: caller.claims ?? null,
228
1169
  internal: caller.internal,
229
- schema: loaded?.tables ?? null,
1170
+ schema: deployment()?.tables ?? null,
1171
+ indexes: deployment()?.indexes ?? null,
230
1172
  runAfter: refusedRows("schedules"),
231
1173
  scheduledRow,
232
- cancelScheduled: refusedRows("cancels")
233
- };
234
- return answered(fn, await fn.handler(rows, args));
1174
+ cancelScheduled: refusedRows("cancels"),
1175
+ fileUrl,
1176
+ fileMetadata,
1177
+ tables: tablesIn()
1178
+ }, 0, null);
1179
+ return answered(fn, await running.run("query", () => fn.handler(rows, args)));
235
1180
  }
236
- function runMutation(fn, args, caller, tag) {
1181
+ function runMutation(fn, args, caller, given) {
1182
+ const tag = given === void 0 ? void 0 : `${callerKey(caller)}|${given}`;
237
1183
  const run = async () => {
238
1184
  const admitted = options.admits?.();
239
1185
  if (tag !== void 0) {
@@ -243,61 +1189,65 @@ function databaseStandIn(options = {}) {
243
1189
  return had.value;
244
1190
  }
245
1191
  }
246
- const overlay = /* @__PURE__ */ new Map();
247
- const later = [];
248
- const { get, range, peek } = reading(overlay);
249
- const written = (table) => {
250
- let map = overlay.get(table);
251
- if (!map) overlay.set(table, map = /* @__PURE__ */ new Map());
252
- return map;
253
- };
254
- const rows = {
255
- get,
256
- range,
1192
+ const layer = layerOver(null);
1193
+ const rows = nesting(writing(layer, {
1194
+ get: () => null,
1195
+ range: () => [],
1196
+ set: () => void 0,
1197
+ delete: () => void 0,
1198
+ runAfter: () => "",
1199
+ scheduledRow,
1200
+ cancelScheduled: () => false,
1201
+ searchIndexes: deployment()?.search ?? {},
257
1202
  now: clock(),
258
1203
  user: caller.user,
259
1204
  server: caller.server,
260
- issuer: null,
1205
+ issuer: caller.issuer ?? null,
1206
+ claims: caller.claims ?? null,
261
1207
  internal: caller.internal,
262
1208
  call: tag ?? `c${hex(random(8))}`,
263
- schema: loaded?.tables ?? null,
264
- set: (table, id, fields) => written(table).set(id, structuredClone({
265
- ...fields,
266
- _version: (peek(table, id)?._version ?? 0) + 1
267
- })),
268
- delete: (table, id) => written(table).set(id, null),
269
- runAfter: (ms, name, args) => {
270
- const id = `s${hex(random(8))}`;
271
- later.push({
272
- ms,
273
- name,
274
- args
275
- });
276
- return id;
277
- },
278
- scheduledRow,
279
- cancelScheduled
280
- };
1209
+ schema: deployment()?.tables ?? null,
1210
+ indexes: deployment()?.indexes ?? null
1211
+ }), 0, layer);
281
1212
  try {
282
- const value = answered(fn, await fn.handler(rows, args));
1213
+ const value = answered(fn, await running.run("mutation", () => fn.handler(rows, args)));
1214
+ layer.ended = true;
283
1215
  const refused = admitted?.() ?? null;
284
1216
  if (refused !== null) throw new DatabaseError("unavailable", refused);
285
- const changes = [];
286
- for (const [table, changed] of overlay) for (const [id, row] of changed) {
287
- if (row) tableOf(table).set(id, row);
288
- else tables.get(table)?.delete(id);
289
- changes.push({
290
- table,
291
- id,
292
- row
293
- });
1217
+ if (!deployment()?.tables) {
1218
+ const codes = /* @__PURE__ */ new Map();
1219
+ for (const table of /* @__PURE__ */ new Set([...tables.keys(), ...layer.writes.keys()])) {
1220
+ const other = codes.get(tableCode(table));
1221
+ if (other !== void 0) throw new DatabaseError("invalid", `${table}: its ids would look like those of ${other}; rename one of them`);
1222
+ codes.set(tableCode(table), table);
1223
+ }
294
1224
  }
1225
+ const changes = [];
1226
+ for (const [table, changed] of layer.writes) for (const [id, row] of changed) changes.push({
1227
+ table,
1228
+ id,
1229
+ row
1230
+ });
295
1231
  if (changes.length) options.committed?.(changes);
296
- for (const run of later) schedule(run.ms, run.name, run.args);
1232
+ for (const { table, id, row } of changes) if (row) tableOf(table).set(id, row);
1233
+ else tables.get(table)?.delete(id);
1234
+ if (changes.length) feed(changes);
1235
+ for (const id of layer.cancels) cancelScheduled(id);
1236
+ for (const later of layer.later) if (layer.cancels.has(later.id)) scheduled.set(later.id, {
1237
+ name: later.name,
1238
+ args: wire(later.args),
1239
+ due: later.due,
1240
+ state: "canceled"
1241
+ });
1242
+ else schedule(later.ms, later.name, later.args, later.id);
1243
+ for (const token of layer.tokens) uploads.set(token, clock() + UPLOAD_MS);
1244
+ forget(layer.dropped);
297
1245
  if (tag !== void 0) answers.set(tag, { value });
298
- if (overlay.size) for (const watcher of watchers) watcher.run();
1246
+ if (layer.writes.size) wake();
1247
+ if (layer.dropped.length) sweep();
299
1248
  return value;
300
1249
  } catch (error) {
1250
+ layer.ended = true;
301
1251
  const refusal = refusalOf(error);
302
1252
  if (tag !== void 0) answers.set(tag, { error: refusal });
303
1253
  throw refusal;
@@ -307,22 +1257,23 @@ function databaseStandIn(options = {}) {
307
1257
  turn = result.catch(() => void 0);
308
1258
  return result;
309
1259
  }
310
- async function runAction(fn, args, caller) {
1260
+ function capabilitiesFor(caller) {
311
1261
  const { get, range } = reading();
312
- const capabilities = {
1262
+ return {
313
1263
  get: async (table, id) => get(table, id),
314
1264
  range: async (table, index, bounds) => range(table, index, bounds),
315
1265
  user: caller.user,
316
1266
  server: caller.server,
317
- issuer: null,
1267
+ issuer: caller.issuer ?? null,
1268
+ claims: caller.claims ?? null,
318
1269
  internal: caller.internal,
319
- fetch: (url, init) => fetch(url, init),
1270
+ fetch: network,
320
1271
  now: clock,
321
1272
  random,
322
- run: (name, args) => invokeAny(name, args, {
1273
+ run: (name, args, kind) => invoke(name, args, {
323
1274
  ...caller,
324
1275
  internal: true
325
- }),
1276
+ }, kind),
326
1277
  schedule: async (ms, name, args) => schedule(ms, name, args),
327
1278
  scheduled: async (id) => {
328
1279
  const row = scheduledRow(id);
@@ -334,14 +1285,221 @@ function databaseStandIn(options = {}) {
334
1285
  ...row.error ? { error: row.error } : {}
335
1286
  } : null;
336
1287
  },
337
- cancel: async (id) => cancelScheduled(id)
1288
+ cancel: async (id) => cancelScheduled(id),
1289
+ vectorSearch,
1290
+ vectorIndexes: deployment()?.vector ?? {},
1291
+ files: {
1292
+ store: keepFile,
1293
+ get: async (id) => {
1294
+ const read = files.has(id) ? await bucket.get(keyOf(id)) : null;
1295
+ return read ? {
1296
+ bytes: read.body,
1297
+ contentType: read.contentType
1298
+ } : null;
1299
+ },
1300
+ delete: async (id) => {
1301
+ forget([id]);
1302
+ await sweep();
1303
+ },
1304
+ url: async (id) => fileUrl(id),
1305
+ metadata: async (id) => fileMetadata(id),
1306
+ uploadUrl: async () => {
1307
+ const token = hex(random(16));
1308
+ uploads.set(token, clock() + UPLOAD_MS);
1309
+ return newUpload(token);
1310
+ }
1311
+ }
1312
+ };
1313
+ }
1314
+ async function runAction(fn, args, caller) {
1315
+ return answered(fn, await running.run("action", () => fn.handler(capabilitiesFor(caller), args)));
1316
+ }
1317
+ const notFound = (error, headers) => Response.json({ error }, {
1318
+ status: 404,
1319
+ ...headers ? { headers } : {}
1320
+ });
1321
+ const tooLarge = (limit, headers) => Response.json({ error: `the body is larger than ${limit} bytes` }, {
1322
+ status: 413,
1323
+ ...headers ? { headers } : {}
1324
+ });
1325
+ /**
1326
+ * A refused body's rest, read and dropped, never kept, but no more than `bytes` more and for no
1327
+ * longer than `DRAIN_MS`: Bun's server reuses a connection only once the request on it was read to
1328
+ * its end, so a client that sent a little too much keeps its connection. Past either bound the body
1329
+ * is cancelled and the refusal goes out at once; that connection may then be lost, which a client
1330
+ * that keeps sending past the limit earns.
1331
+ */
1332
+ async function discard(reader, bytes) {
1333
+ const DRAIN_MS = 2e3;
1334
+ let timer;
1335
+ const stop = new Promise((resolve) => {
1336
+ timer = setTimeout(() => resolve("stop"), DRAIN_MS);
1337
+ });
1338
+ try {
1339
+ for (let left = bytes; left >= 0;) {
1340
+ const read = await Promise.race([reader.read(), stop]);
1341
+ if (read === "stop") break;
1342
+ if (read.done) return;
1343
+ left -= read.value.byteLength;
1344
+ }
1345
+ reader.cancel().catch(() => {});
1346
+ } finally {
1347
+ clearTimeout(timer);
1348
+ }
1349
+ }
1350
+ /**
1351
+ * A body read whole, at most `limit` bytes. One that says it is larger is refused before any of it
1352
+ * is read; one that turns out larger is refused as soon as it passes the limit, dropping what was
1353
+ * read. Either way at most `limit` more bytes are read and dropped (`discard`).
1354
+ */
1355
+ async function bodyWithin(request, limit, what) {
1356
+ const said = Number(request.headers.get("content-length") ?? NaN);
1357
+ if (said > limit) {
1358
+ if (request.body) await discard(request.body.getReader(), said > 2 * limit ? -1 : limit);
1359
+ throw new TooLarge(what, limit);
1360
+ }
1361
+ if (request.body === null) return /* @__PURE__ */ new Uint8Array(0);
1362
+ const reader = request.body.getReader();
1363
+ let chunks = [];
1364
+ let size = 0;
1365
+ for (let read = await reader.read(); !read.done; read = await reader.read()) {
1366
+ size += read.value.byteLength;
1367
+ if (size > limit) {
1368
+ chunks = [];
1369
+ await discard(reader, limit);
1370
+ throw new TooLarge(what, limit);
1371
+ }
1372
+ chunks.push(read.value);
1373
+ }
1374
+ const out = new Uint8Array(size);
1375
+ let at = 0;
1376
+ for (const chunk of chunks) {
1377
+ out.set(chunk, at);
1378
+ at += chunk.byteLength;
1379
+ }
1380
+ return out;
1381
+ }
1382
+ const CORS = { "access-control-allow-origin": "*" };
1383
+ /**
1384
+ * The caller an HTTP request carries: a bearer token that verifies, or no one. Never the server's own code.
1385
+ * Where `auth.config.ts` names providers, a token is checked as a client's is (`identify`), its claims kept.
1386
+ */
1387
+ async function httpCaller(request) {
1388
+ const token = /^Bearer\s+(\S+)$/iu.exec(request.headers.get("authorization") ?? "")?.[1];
1389
+ if (token && deployment()?.auth?.providers.length) return identify(token).catch(() => ({
1390
+ user: null,
1391
+ server: false,
1392
+ internal: false
1393
+ }));
1394
+ return {
1395
+ user: (token && options.verify ? await options.verify(token) : null) ?? null,
1396
+ server: false,
1397
+ internal: false
338
1398
  };
339
- return answered(fn, await fn.handler(capabilities, args));
340
1399
  }
341
- async function invoke(name, args, caller, kind, tag) {
342
- const fn = kind ? functionFor(name, kind, caller) : loaded?.functions.get(name);
1400
+ /** The Database's HTTP side, as `StandIn.fetch` says. */
1401
+ async function serveHttp(request) {
1402
+ const url = new URL(request.url);
1403
+ const reading = request.method === "GET" || request.method === "HEAD";
1404
+ if (url.pathname === "/files" || url.pathname.startsWith("/files/")) {
1405
+ if (request.method === "OPTIONS") return new Response(null, {
1406
+ status: 204,
1407
+ headers: {
1408
+ ...CORS,
1409
+ "access-control-allow-methods": "GET, HEAD, POST, OPTIONS",
1410
+ "access-control-allow-headers": request.headers.get("access-control-request-headers") || "content-type",
1411
+ "access-control-max-age": "86400"
1412
+ }
1413
+ });
1414
+ if (url.pathname === "/files" && request.method === "POST" && url.searchParams.has("upload")) {
1415
+ const token = url.searchParams.get("upload");
1416
+ const expires = uploads.get(token);
1417
+ uploads.delete(token);
1418
+ if (expires === void 0 || expires <= clock()) return notFound("this upload URL was used, has expired, or was never made", CORS);
1419
+ try {
1420
+ const storageId = await keepFile(await bodyWithin(request, fileLimit, "a file"), request.headers.get("content-type") ?? "application/octet-stream");
1421
+ return Response.json({ storageId }, { headers: CORS });
1422
+ } catch (error) {
1423
+ if (error instanceof TooLarge) return tooLarge(error.limit, CORS);
1424
+ throw error;
1425
+ }
1426
+ }
1427
+ if (url.pathname.startsWith("/files/") && reading) {
1428
+ const id = decodeURIComponent(url.pathname.slice(7));
1429
+ const read = files.has(id) ? await bucket.get(keyOf(id)) : null;
1430
+ if (!read) return notFound("no such file", CORS);
1431
+ return new Response(request.method === "HEAD" ? null : read.body, { headers: {
1432
+ ...CORS,
1433
+ "content-type": read.contentType,
1434
+ "content-length": String(read.size)
1435
+ } });
1436
+ }
1437
+ return notFound(`nothing at ${request.method} ${url.pathname}`, CORS);
1438
+ }
1439
+ if (url.pathname === "/http" || url.pathname.startsWith("/http/")) {
1440
+ const path = url.pathname.slice(5) || "/";
1441
+ const served = loaded;
1442
+ return calling.run({
1443
+ served,
1444
+ trust
1445
+ }, async () => {
1446
+ const route = served?.http?.lookup(path, request.method);
1447
+ if (!route) return notFound(`no HTTP action for ${request.method} ${path}`);
1448
+ let given = request;
1449
+ if (request.body !== null) try {
1450
+ given = new Request(request.url, {
1451
+ method: request.method,
1452
+ headers: request.headers,
1453
+ body: await bodyWithin(request, limits.httpBody, "a request to an HTTP action")
1454
+ });
1455
+ } catch (error) {
1456
+ if (error instanceof TooLarge) return tooLarge(error.limit);
1457
+ throw error;
1458
+ }
1459
+ try {
1460
+ const caps = capabilitiesFor(await httpCaller(request));
1461
+ const response = await running.run("action", () => route[0].handler(caps, given));
1462
+ if (request.method === "HEAD") return new Response(null, {
1463
+ status: response.status,
1464
+ statusText: response.statusText,
1465
+ headers: response.headers
1466
+ });
1467
+ if (response.body === null || [
1468
+ 101,
1469
+ 204,
1470
+ 205,
1471
+ 304
1472
+ ].includes(response.status)) return response;
1473
+ const body = await readLimited(response.body, limits.httpResponse, "an HTTP action's response");
1474
+ return new Response(body, {
1475
+ status: response.status,
1476
+ statusText: response.statusText,
1477
+ headers: response.headers
1478
+ });
1479
+ } catch (error) {
1480
+ return Response.json({ error: refusalOf(error).message }, { status: 500 });
1481
+ }
1482
+ });
1483
+ }
1484
+ return notFound(`nothing at ${url.pathname}`);
1485
+ }
1486
+ /**
1487
+ * Runs a function of the deployment served as it is called. The function and that whole deployment (its schema,
1488
+ * indexes, auth config and environment) are taken together and held to the call's end (`calling`), so a call that waits
1489
+ * (a mutation queued behind a deploy) runs as the deployment that served it, never by one served since. A nested
1490
+ * call in a query or mutation is part of it; a call an action makes, or a scheduled one, is taken anew.
1491
+ */
1492
+ function invoke(name, args, caller, kind, tag) {
1493
+ const served = loaded;
1494
+ return calling.run({
1495
+ served,
1496
+ trust
1497
+ }, () => invokeOn(served, name, args, caller, kind, tag));
1498
+ }
1499
+ async function invokeOn(served, name, args, caller, kind, tag) {
1500
+ const fn = kind ? functionFor(served, name, kind, caller) : served?.functions.get(name);
343
1501
  if (!fn) throw new DatabaseError("no function", `no function ${name}`);
344
- if (!kind) functionFor(name, fn.options.kind, caller);
1502
+ if (!kind) functionFor(served, name, fn.options.kind, caller);
345
1503
  const given = wire(args ?? {});
346
1504
  try {
347
1505
  checked(fn, given);
@@ -352,7 +1510,6 @@ function databaseStandIn(options = {}) {
352
1510
  throw refusalOf(error);
353
1511
  }
354
1512
  }
355
- const invokeAny = (name, args, caller) => invoke(name, args, caller);
356
1513
  const clientFor = (user) => callerClient({
357
1514
  user,
358
1515
  server: false,
@@ -363,29 +1520,173 @@ function databaseStandIn(options = {}) {
363
1520
  query: (fn, args) => invoke(nameOf(fn), args, caller, "query"),
364
1521
  mutation: (fn, args, options = {}) => invoke(nameOf(fn), args, caller, "mutation", options.tag),
365
1522
  action: (fn, args) => invoke(nameOf(fn), args, caller, "action"),
366
- watch(fn, args, onValue) {
1523
+ watch(fn, args, onValue, onError) {
367
1524
  let last, stopped = false;
368
- const watcher = { async run() {
1525
+ const watcher = { async check() {
1526
+ let tell, text;
369
1527
  try {
370
1528
  const value = await invoke(nameOf(fn), args, caller, "query");
371
- const text = JSON.stringify(value);
1529
+ text = JSON.stringify(value, keyBytes);
1530
+ tell = () => onValue(value);
1531
+ } catch (error) {
1532
+ const refusal = refusalOf(error);
1533
+ text = `!${refusal.code}:${refusal.message}`;
1534
+ tell = () => onError?.(refusal);
1535
+ }
1536
+ return () => {
372
1537
  if (!stopped && text !== last) {
373
1538
  last = text;
374
- onValue(value);
1539
+ tell();
375
1540
  }
376
- } catch {}
1541
+ };
377
1542
  } };
378
1543
  watchers.add(watcher);
379
- watcher.run();
1544
+ watcher.check().then(told);
380
1545
  return () => {
381
1546
  stopped = true;
382
1547
  watchers.delete(watcher);
383
1548
  };
384
1549
  },
385
1550
  as: (subject) => clientFor(subject),
1551
+ withToken: (token) => signedIn(token),
386
1552
  tag: async () => `t${hex(random(12))}`
387
1553
  };
388
1554
  }
1555
+ async function identify(token) {
1556
+ const auth = deployment()?.auth ?? null;
1557
+ if (token === null || token === "") {
1558
+ if (auth?.anonymous) return {
1559
+ user: null,
1560
+ server: false,
1561
+ internal: false
1562
+ };
1563
+ throw new DatabaseError("unauthenticated", "this database needs a signed-in caller: connect with a token from a sign-in provider its auth.config.ts trusts");
1564
+ }
1565
+ if (!auth?.providers.length) throw new DatabaseError("unauthenticated", "this database trusts no sign-in provider: name yours in db/auth.config.ts");
1566
+ const call = calling.getStore();
1567
+ const verify = call ? call.trust : trust;
1568
+ if (verify instanceof DatabaseError) throw verify;
1569
+ if (verify === null) throw new DatabaseError("unauthenticated", "this database trusts no sign-in provider: name yours in db/auth.config.ts");
1570
+ const verified = await verify(token);
1571
+ return {
1572
+ user: verified.subject,
1573
+ server: false,
1574
+ internal: false,
1575
+ issuer: verified.issuer,
1576
+ claims: verified.claims
1577
+ };
1578
+ }
1579
+ /**
1580
+ * A client whose every call first signs `token` in; a refusal refuses each call. Its session ends with its
1581
+ * token (`sessionEnd`): a call after is refused `unauthenticated`, and its watches are given nothing more.
1582
+ */
1583
+ function signedIn(token) {
1584
+ const signed = identify(token).then((caller) => ({
1585
+ caller,
1586
+ client: callerClient(caller),
1587
+ ends: sessionEnd(caller.claims)
1588
+ }));
1589
+ signed.catch(() => {});
1590
+ const live = async () => {
1591
+ const session = await signed;
1592
+ if (clock() > session.ends) throw new DatabaseError("unauthenticated", "the token expired during the session: connect again with a new one");
1593
+ return session;
1594
+ };
1595
+ return {
1596
+ query: async (fn, args) => (await live()).client.query(fn, args),
1597
+ mutation: async (fn, args, options) => (await live()).client.mutation(fn, args, options),
1598
+ action: async (fn, args, options) => (await live()).client.action(fn, args, options),
1599
+ watch(fn, args, onValue, onError) {
1600
+ let stop = null, stopped = false;
1601
+ signed.then((session) => {
1602
+ if (!stopped) stop = session.client.watch(fn, args, (value) => {
1603
+ if (clock() <= session.ends) onValue(value);
1604
+ else stop?.();
1605
+ }, (error) => {
1606
+ if (clock() <= session.ends) onError?.(error);
1607
+ else stop?.();
1608
+ });
1609
+ }, (error) => {
1610
+ if (!stopped) onError?.(refusalOf(error));
1611
+ });
1612
+ return () => {
1613
+ stopped = true;
1614
+ stop?.();
1615
+ };
1616
+ },
1617
+ as: (subject) => clientFor(subject),
1618
+ withToken: (other) => signedIn(other),
1619
+ tag: async () => `t${hex(random(12))}`
1620
+ };
1621
+ }
1622
+ /**
1623
+ * Runs the served build's schedules, as the Database runs them: `crons.ts`'s runs and each
1624
+ * function's own `cron`, by the server as an internal call. A run whose job's last run is still
1625
+ * going is skipped, as Convex skips it, even when that run began under the build served before.
1626
+ * Each job has one timer, and its runs are counted in `cronState`. Serving another build replaces
1627
+ * the timers.
1628
+ */
1629
+ const cronTimers = /* @__PURE__ */ new Map();
1630
+ const cronState = /* @__PURE__ */ new Map();
1631
+ function runCrons(next) {
1632
+ for (const timer of cronTimers.values()) clearTimeout(timer);
1633
+ cronTimers.clear();
1634
+ const jobs = /* @__PURE__ */ new Map();
1635
+ for (const job of next?.crons ?? []) jobs.set(`crons.ts:${job.name}`, job);
1636
+ for (const [name, fn] of next?.functions ?? []) if (fn.options.cron) jobs.set(`cron:${name}`, {
1637
+ name,
1638
+ cron: fn.options.cron,
1639
+ function: name,
1640
+ args: {}
1641
+ });
1642
+ for (const [key, state] of cronState) if (!jobs.has(key) && !state.running) cronState.delete(key);
1643
+ const run = (key, job) => {
1644
+ const state = cronState.get(key);
1645
+ if (state.running) {
1646
+ state.skipped += 1;
1647
+ return;
1648
+ }
1649
+ state.running = true;
1650
+ state.runs += 1;
1651
+ invoke(job.function, job.args, {
1652
+ user: null,
1653
+ server: true,
1654
+ internal: true
1655
+ }).then(() => {
1656
+ state.error = null;
1657
+ }, (error) => {
1658
+ state.error = refusalOf(error).message;
1659
+ }).finally(() => {
1660
+ state.running = false;
1661
+ });
1662
+ };
1663
+ const later = (key, at, then) => {
1664
+ const wait = Math.min(Math.max(0, at - clock()), 2e9);
1665
+ cronTimers.set(key, setTimeout(() => clock() >= at ? then() : later(key, at, then), wait));
1666
+ };
1667
+ for (const [key, job] of jobs) {
1668
+ if (!cronState.has(key)) cronState.set(key, {
1669
+ name: job.name,
1670
+ runs: 0,
1671
+ skipped: 0,
1672
+ running: false,
1673
+ error: null
1674
+ });
1675
+ if ("every" in job) {
1676
+ const tick = (at) => later(key, at, () => {
1677
+ run(key, job);
1678
+ tick(at + job.every);
1679
+ });
1680
+ tick(clock() + job.every);
1681
+ } else {
1682
+ const tick = () => later(key, nextCron(job.cron, clock()), () => {
1683
+ run(key, job);
1684
+ tick();
1685
+ });
1686
+ tick();
1687
+ }
1688
+ }
1689
+ }
389
1690
  function exclusive(work) {
390
1691
  const result = turn.then(work, work);
391
1692
  turn = result.catch(() => void 0);
@@ -393,28 +1694,47 @@ function databaseStandIn(options = {}) {
393
1694
  }
394
1695
  return {
395
1696
  serve(next) {
1697
+ next.useNetwork?.(network);
1698
+ trust = trustFor(next);
396
1699
  loaded = next;
397
- for (const watcher of watchers) watcher.run();
1700
+ indexVectors(next);
1701
+ runCrons(next);
1702
+ wake();
398
1703
  },
399
1704
  exclusive,
400
1705
  client: clientFor(null),
1706
+ identify,
1707
+ get auth() {
1708
+ return loaded?.auth ?? null;
1709
+ },
401
1710
  caller: callerClient,
402
1711
  kind: (name) => loaded?.functions.get(name)?.options.kind,
403
1712
  rows: () => Object.fromEntries([...tables].map(([name, rows]) => [name, Object.fromEntries(rows)])),
1713
+ crons: () => [...cronState.values()].map((state) => ({
1714
+ name: state.name,
1715
+ runs: state.runs,
1716
+ skipped: state.skipped,
1717
+ running: state.running,
1718
+ error: state.error
1719
+ })),
1720
+ files: () => Object.fromEntries(files),
404
1721
  commit(write) {
405
1722
  return exclusive(() => {
406
1723
  const changes = write(Object.fromEntries([...tables].map(([name, rows]) => [name, Object.fromEntries(rows)])));
1724
+ if (changes.length) options.committed?.(changes);
407
1725
  for (const change of changes) if (change.row) tableOf(change.table).set(change.id, change.row);
408
1726
  else tables.get(change.table)?.delete(change.id);
409
1727
  if (changes.length) {
410
- options.committed?.(changes);
411
- for (const watcher of watchers) watcher.run();
1728
+ feed(changes);
1729
+ wake();
412
1730
  }
413
1731
  return changes;
414
1732
  });
415
1733
  },
1734
+ fetch: serveHttp,
416
1735
  close() {
417
1736
  for (const entry of scheduled.values()) clearTimeout(entry.timer);
1737
+ runCrons(null);
418
1738
  }
419
1739
  };
420
1740
  }