@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.
- package/auth-1W-SzpD3.mjs +441 -0
- package/build-DQo-JrlN.d.mts +120 -0
- package/bytes-C2pcyl9u.mjs +280 -0
- package/{connection-CDk7H1FL.mjs → connection-Cu2GSOaR.mjs} +171 -31
- package/database/build.d.mts +2 -2
- package/database/build.mjs +1404 -117
- package/database/client.d.mts +85 -9
- package/database/client.mjs +550 -32
- package/database/contract.d.mts +92 -2
- package/database/contract.mjs +2179 -3
- package/database/errors.d.mts +1 -22
- package/database/react.d.mts +133 -0
- package/database/react.mjs +488 -0
- package/database/server.d.mts +2 -3
- package/database/server.mjs +3 -320
- package/database/stand-in.d.mts +95 -9
- package/database/stand-in.mjs +1436 -116
- package/errors-x2vXKi0u.d.mts +25 -0
- package/index-DNNXNny7.d.mts +410 -0
- package/key-BrRdFY-n.mjs +11 -0
- package/package.json +114 -1
- package/schema-CTHQMRsW.mjs +217 -0
- package/server-B5HK2Ou9.d.mts +574 -0
- package/server-EDRbF2u-.mjs +1893 -0
- package/{store-BzI9at5x.mjs → store-lIZ5GxVv.mjs} +1 -1
- package/{tabs-D-P8_ci_.mjs → tabs-zCh8kceo.mjs} +1 -1
- package/vector/contract.d.mts +1 -1
- package/vector/contract.mjs +773 -1
- package/vector/index.d.mts +2 -2
- package/vector/index.mjs +71 -3
- package/vector/stand-in.d.mts +1 -1
- package/vector/stand-in.mjs +326 -23
- package/vector/wire.d.mts +11 -2
- package/vector/wire.mjs +179 -14
- package/build-SQ44jwSa.d.mts +0 -41
- package/index-DdoK0y7D.d.mts +0 -192
- package/schema-BF-Y1EVu.mjs +0 -142
- package/schema-DS8x1Dn8.mjs +0 -115
- package/schema-f7E9uzUn.d.mts +0 -74
- package/server-C7O7CICU.d.mts +0 -182
package/database/build.mjs
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { f as indexFields, h as orderable, l as defineSchema, u as defineTable, y as v } from "../bytes-C2pcyl9u.mjs";
|
|
2
|
+
import { E as scheduleOf } from "../server-EDRbF2u-.mjs";
|
|
3
|
+
import { t as authConfigOf } from "../auth-1W-SzpD3.mjs";
|
|
2
4
|
import { parse } from "acorn";
|
|
3
5
|
//#region src/database/build.ts
|
|
4
6
|
/**
|
|
@@ -12,14 +14,30 @@ import { parse } from "acorn";
|
|
|
12
14
|
* built.generated // the files of db/_generated/: api.mjs and the types
|
|
13
15
|
*
|
|
14
16
|
* `strip` takes TypeScript to JavaScript, keeping every position, so a refusal points at the author's
|
|
15
|
-
* line: `transformSync(ts, { mode: "strip-only" }).code` of `amaro`. Only types are taken out
|
|
16
|
-
*
|
|
17
|
+
* line: `transformSync(ts, { mode: "strip-only" }).code` of `amaro`. Only types are taken out, and
|
|
18
|
+
* imports of names used only as types with them, as TypeScript does; an enum of numbers and strings
|
|
19
|
+
* is written as the object TypeScript makes of it, and a namespace or any other enum is refused.
|
|
20
|
+
* Nothing here runs the Project's code.
|
|
17
21
|
*
|
|
18
22
|
* What is admitted: imports of `@midsummer-ai/sdk/server`, `./_generated/server` and
|
|
19
|
-
* `./_generated/api` by name (no renaming),
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
+
* `./_generated/api` by name (no renaming), of the folder's own modules at any depth, and of installed
|
|
24
|
+
* packages that ship ES modules, and JSON files of the project; functions as top-level exports
|
|
25
|
+
* (`export const send = mutation({ ... })`) of the files directly in the folder, the files in folders
|
|
26
|
+
* below holding only helpers, queries, mutations and actions side by side; the schema as literals
|
|
27
|
+
* (`export default defineSchema({ ... })` in `schema.ts`), which may read constants and enums of the
|
|
28
|
+
* modules it imports; whom the Database trusts to sign users in as literals too
|
|
29
|
+
* (`export default { providers: [...] }` in `auth.config.ts`, each value a string or
|
|
30
|
+
* `process.env.NAME`; see `./auth`); HTTP actions as top-level exports or as a route's `handler`
|
|
31
|
+
* (`http.route({ ..., handler: httpAction(...) })`), and their router as `http.ts`'s default export;
|
|
32
|
+
* scheduled runs as `crons.ts`'s `cronJobs()`, read as literals into `crons`. Never `eval`, a dynamic
|
|
33
|
+
* `import()`, `import.meta` or import attributes, in a package's files too.
|
|
34
|
+
*
|
|
35
|
+
* An installed package is read through `packages`, from the `node_modules` folders at and above the
|
|
36
|
+
* folder, as Node finds them, and built in beside the folder's own modules: each file it reaches is
|
|
37
|
+
* `node_modules/<name>@<version>/<path>.mjs`, and every import in the build names a file of the build.
|
|
38
|
+
* So the build is closed: the Database runs it with nothing installed. The same sources and packages
|
|
39
|
+
* build to the same files, and the build is refused over `MODULE_BYTES` a file, `BUILD_BYTES` in all or
|
|
40
|
+
* `BUILD_FILES` files.
|
|
23
41
|
*/
|
|
24
42
|
/** A file the Database would refuse; the message gives the file, and the line when there is one. */
|
|
25
43
|
var Refused = class extends Error {
|
|
@@ -28,6 +46,12 @@ var Refused = class extends Error {
|
|
|
28
46
|
this.name = "Refused";
|
|
29
47
|
}
|
|
30
48
|
};
|
|
49
|
+
/** The most one built file may be, as a deploy admits it. */
|
|
50
|
+
const MODULE_BYTES = 1048576;
|
|
51
|
+
/** The most a whole build may be: the folder's modules and every package file they reach. */
|
|
52
|
+
const BUILD_BYTES = 8388608;
|
|
53
|
+
/** The most files a build may have, as a deploy admits it. */
|
|
54
|
+
const BUILD_FILES = 4e3;
|
|
31
55
|
const SOURCES = [
|
|
32
56
|
".ts",
|
|
33
57
|
".mts",
|
|
@@ -35,8 +59,16 @@ const SOURCES = [
|
|
|
35
59
|
".js"
|
|
36
60
|
];
|
|
37
61
|
const extensionOf = (name) => /\.[^.]*$/u.exec(name)?.[0] ?? "";
|
|
38
|
-
/**
|
|
39
|
-
const
|
|
62
|
+
/** A file directly in `db/`: a module named as a function's first part, or `auth.config`. Another dotted name there, such as `vite.config.ts`, is no source. */
|
|
63
|
+
const TOP_LEVEL = /^(?:[A-Za-z0-9_-]+|auth\.config)\.[a-z]+$/u;
|
|
64
|
+
/**
|
|
65
|
+
* Whether a file of `db/`, by its path in it, is a source: types (`.d.ts`), dotfiles, `_generated/`, `node_modules/` and
|
|
66
|
+
* a dotted name directly in the folder other than `auth.config` are none.
|
|
67
|
+
*/
|
|
68
|
+
const isSource = (name) => {
|
|
69
|
+
const parts = name.split("/");
|
|
70
|
+
return SOURCES.includes(extensionOf(name)) && !name.endsWith(".d.ts") && parts.every((part) => part !== "" && !part.startsWith(".") && part !== "node_modules") && parts[0] !== "_generated" && (parts.length > 1 || TOP_LEVEL.test(name));
|
|
71
|
+
};
|
|
40
72
|
const SDK = "@midsummer-ai/sdk/server";
|
|
41
73
|
const DEFINERS = [
|
|
42
74
|
"query",
|
|
@@ -46,9 +78,10 @@ const DEFINERS = [
|
|
|
46
78
|
"action",
|
|
47
79
|
"internalAction"
|
|
48
80
|
];
|
|
49
|
-
const ACTIONS = /* @__PURE__ */ new Set(["action", "internalAction"]);
|
|
50
81
|
const ADMITTED = /* @__PURE__ */ new Set([
|
|
51
82
|
...DEFINERS,
|
|
83
|
+
"httpAction",
|
|
84
|
+
"httpRouter",
|
|
52
85
|
"v",
|
|
53
86
|
"increment",
|
|
54
87
|
"take",
|
|
@@ -56,7 +89,9 @@ const ADMITTED = /* @__PURE__ */ new Set([
|
|
|
56
89
|
"InsufficientError",
|
|
57
90
|
"NotFoundError",
|
|
58
91
|
"defineSchema",
|
|
59
|
-
"defineTable"
|
|
92
|
+
"defineTable",
|
|
93
|
+
"paginationOptsValidator",
|
|
94
|
+
"cronJobs"
|
|
60
95
|
]);
|
|
61
96
|
const API_NAMES = /* @__PURE__ */ new Set(["api", "internal"]);
|
|
62
97
|
const SURFACES = new Map([[SDK, ADMITTED], ...[
|
|
@@ -65,7 +100,12 @@ const SURFACES = new Map([[SDK, ADMITTED], ...[
|
|
|
65
100
|
".mjs"
|
|
66
101
|
].flatMap((x) => [[`./_generated/server${x}`, ADMITTED], [`./_generated/api${x}`, API_NAMES]])]);
|
|
67
102
|
const SCHEMA_FILE = "schema.mjs";
|
|
103
|
+
const CRONS_FILE = "crons.mjs";
|
|
104
|
+
const HTTP_FILE = "http.mjs";
|
|
105
|
+
const AUTH_FILE = "auth.config.mjs";
|
|
68
106
|
const FUNCTION_NAME = /^[A-Za-z][A-Za-z0-9_]{0,63}$/u;
|
|
107
|
+
/** The most parts a function's name has: its folders, its file and its export. */
|
|
108
|
+
const FUNCTION_DEPTH = 8;
|
|
69
109
|
const FORBIDDEN = /* @__PURE__ */ new Set([
|
|
70
110
|
"eval",
|
|
71
111
|
"__realm",
|
|
@@ -77,7 +117,31 @@ function* nodes(node) {
|
|
|
77
117
|
for (const child of value) if (typeof child?.type === "string") yield* nodes(child);
|
|
78
118
|
} else if (typeof value?.type === "string") yield* nodes(value);
|
|
79
119
|
}
|
|
80
|
-
/**
|
|
120
|
+
/** A folder's path with `/`, its last part taken off: "" for a file at the top. */
|
|
121
|
+
const dirOf = (path) => path.slice(0, Math.max(0, path.lastIndexOf("/")));
|
|
122
|
+
/** `spec` resolved against the folder `dir`, or null when it climbs above the top. Absolute paths keep their `/`. */
|
|
123
|
+
function joined(dir, spec) {
|
|
124
|
+
const out = [];
|
|
125
|
+
for (const part of `${dir}/${spec}`.split("/")) {
|
|
126
|
+
if (part === "" || part === ".") continue;
|
|
127
|
+
if (part === "..") {
|
|
128
|
+
if (!out.length) return null;
|
|
129
|
+
out.pop();
|
|
130
|
+
} else out.push(part);
|
|
131
|
+
}
|
|
132
|
+
return `${dir.startsWith("/") ? "/" : ""}${out.join("/")}`;
|
|
133
|
+
}
|
|
134
|
+
/** The import of built file `to` from built file `from`, both by their paths in the build. */
|
|
135
|
+
function relativeSpec(from, to) {
|
|
136
|
+
const a = dirOf(from).split("/").filter(Boolean), b = to.split("/");
|
|
137
|
+
let same = 0;
|
|
138
|
+
while (same < a.length && same < b.length - 1 && a[same] === b[same]) same += 1;
|
|
139
|
+
return `${a.length > same ? "../".repeat(a.length - same) : "./"}${b.slice(same).join("/")}`;
|
|
140
|
+
}
|
|
141
|
+
const GENERATED = /^_generated\/(server|api)(?:\.m?js)?$/u;
|
|
142
|
+
const bytesOf = (text) => new TextEncoder().encode(text).length;
|
|
143
|
+
const mib = (bytes) => `${(bytes / 1024 / 1024).toFixed(1)} MiB`;
|
|
144
|
+
/** Strips each source: its built file by `<path>.mjs`. Throws `Refused` with the author's file. */
|
|
81
145
|
function stripSources(sources, strip) {
|
|
82
146
|
const entries = Object.keys(sources).filter(isSource);
|
|
83
147
|
const names = /* @__PURE__ */ new Map();
|
|
@@ -87,51 +151,836 @@ function stripSources(sources, strip) {
|
|
|
87
151
|
if (first !== void 0) throw new Refused(`${first} and ${file} compile to ${name}.mjs. Rename one file.`);
|
|
88
152
|
names.set(name, file);
|
|
89
153
|
}
|
|
90
|
-
const
|
|
91
|
-
for (const [name, file] of names) {
|
|
92
|
-
|
|
154
|
+
const stripped = /* @__PURE__ */ new Map();
|
|
155
|
+
for (const [name, file] of names) stripped.set(name, {
|
|
156
|
+
file,
|
|
157
|
+
js: stripped1(file, sources[file], strip)
|
|
158
|
+
});
|
|
159
|
+
return {
|
|
160
|
+
stripped,
|
|
161
|
+
built: new Map(Object.keys(sources).filter((path) => path.startsWith("node_modules/") && path.endsWith(".mjs") && !path.split("/").some((part) => part === "" || part === "." || part === "..")).map((path) => [path, sources[path]]))
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
/** The most enums one source may have, each written as an object before the source is stripped again. */
|
|
165
|
+
const ENUMS = 256;
|
|
166
|
+
/**
|
|
167
|
+
* One source as JavaScript: TypeScript stripped of its types, keeping every position. An enum is
|
|
168
|
+
* written as the object TypeScript makes of it (`enumAsObject`), and an import of names used only
|
|
169
|
+
* as types is dropped, as TypeScript drops it, so `import { Doc } from "./_generated/dataModel"`
|
|
170
|
+
* needs no `type`.
|
|
171
|
+
*/
|
|
172
|
+
function stripped1(file, text, strip) {
|
|
173
|
+
if (!/\.m?ts$/u.test(file)) return text;
|
|
174
|
+
let ts = text;
|
|
175
|
+
for (let n = 0;; n += 1) try {
|
|
176
|
+
return typeImportsDropped(strip(ts));
|
|
177
|
+
} catch (error) {
|
|
178
|
+
const { startLine: line, startColumn: column, code, message } = error ?? {};
|
|
179
|
+
const lowered = code === "UnsupportedSyntax" && /\benum\b/u.test(String(message)) && Number.isInteger(line) && Number.isInteger(column) && n < ENUMS ? enumAsObject(ts, line, column) : null;
|
|
180
|
+
if (lowered !== null) {
|
|
181
|
+
ts = lowered;
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
const why = `${file}${Number.isInteger(line) ? `:${line}` : ""}: ${String(message ?? error).split("\n")[0]}`;
|
|
185
|
+
throw new Refused(code === "UnsupportedSyntax" ? `${why}. Write it as JavaScript instead: an object of constants for an enum whose members aren't numbers or strings, plain exports for a namespace.` : why);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* TypeScript with the enum that starts at `line` and `column` written as the object TypeScript
|
|
190
|
+
* makes of it: `enum Status { New, Done }` is `const Status = { "New": 0, "0": "New", "Done": 1,
|
|
191
|
+
* "1": "Done" }`. Lines stay where they were. Null when a member's value is anything but a number
|
|
192
|
+
* or a string.
|
|
193
|
+
*/
|
|
194
|
+
function enumAsObject(ts, line, column) {
|
|
195
|
+
let at = 0;
|
|
196
|
+
for (let n = 1; n < line; n += 1) {
|
|
197
|
+
at = ts.indexOf("\n", at) + 1;
|
|
198
|
+
if (at === 0) return null;
|
|
199
|
+
}
|
|
200
|
+
at += column;
|
|
201
|
+
const head = /^(?:const\s+)?enum\s+([A-Za-z_$][\w$]*)\s*\{/u.exec(ts.slice(at));
|
|
202
|
+
if (!head) return null;
|
|
203
|
+
let i = at + head[0].length;
|
|
204
|
+
const skip = () => {
|
|
205
|
+
for (;;) {
|
|
206
|
+
while (i < ts.length && /\s/u.test(ts[i])) i += 1;
|
|
207
|
+
if (ts.startsWith("//", i)) {
|
|
208
|
+
const end = ts.indexOf("\n", i);
|
|
209
|
+
i = end < 0 ? ts.length : end;
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (ts.startsWith("/*", i)) {
|
|
213
|
+
const end = ts.indexOf("*/", i + 2);
|
|
214
|
+
i = end < 0 ? ts.length : end + 2;
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
const quoted = () => {
|
|
221
|
+
const quote = ts[i];
|
|
222
|
+
let j = i + 1;
|
|
223
|
+
while (j < ts.length && ts[j] !== quote && ts[j] !== "\n") j += ts[j] === "\\" ? 2 : 1;
|
|
224
|
+
if (ts[j] !== quote) return null;
|
|
225
|
+
const body = ts.slice(i + 1, j);
|
|
226
|
+
i = j + 1;
|
|
93
227
|
try {
|
|
94
|
-
|
|
95
|
-
} catch
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
228
|
+
return JSON.parse(`"${quote === "'" ? body.replace(/\\'/gu, "'").replace(/(^|[^\\])"/gu, "$1\\\"") : body}"`);
|
|
229
|
+
} catch {
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
const members = [];
|
|
234
|
+
let next = 0;
|
|
235
|
+
for (;;) {
|
|
236
|
+
skip();
|
|
237
|
+
if (ts[i] === "}") {
|
|
238
|
+
i += 1;
|
|
239
|
+
break;
|
|
240
|
+
}
|
|
241
|
+
let key = null;
|
|
242
|
+
if (ts[i] === "'" || ts[i] === "\"") key = quoted();
|
|
243
|
+
else {
|
|
244
|
+
const word = /^[A-Za-z_$][\w$]*/u.exec(ts.slice(i));
|
|
245
|
+
if (word) {
|
|
246
|
+
key = word[0];
|
|
247
|
+
i += key.length;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
if (key === null) return null;
|
|
251
|
+
skip();
|
|
252
|
+
let value;
|
|
253
|
+
if (ts[i] === "=") {
|
|
254
|
+
i += 1;
|
|
255
|
+
skip();
|
|
256
|
+
if (ts[i] === "'" || ts[i] === "\"") {
|
|
257
|
+
const text = quoted();
|
|
258
|
+
if (text === null) return null;
|
|
259
|
+
value = text;
|
|
260
|
+
next = null;
|
|
261
|
+
} else {
|
|
262
|
+
const number = /^-?(?:0[xX][0-9a-fA-F]+|\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)(?![\w$.])/u.exec(ts.slice(i));
|
|
263
|
+
if (!number) return null;
|
|
264
|
+
value = Number(number[0]);
|
|
265
|
+
i += number[0].length;
|
|
266
|
+
next = value + 1;
|
|
267
|
+
}
|
|
268
|
+
} else {
|
|
269
|
+
if (next === null) return null;
|
|
270
|
+
value = next;
|
|
271
|
+
next += 1;
|
|
272
|
+
}
|
|
273
|
+
members.push([key, value]);
|
|
274
|
+
skip();
|
|
275
|
+
if (ts[i] === ",") {
|
|
276
|
+
i += 1;
|
|
277
|
+
continue;
|
|
99
278
|
}
|
|
100
|
-
|
|
101
|
-
|
|
279
|
+
if (ts[i] === "}") {
|
|
280
|
+
i += 1;
|
|
281
|
+
break;
|
|
282
|
+
}
|
|
283
|
+
return null;
|
|
102
284
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
285
|
+
const entries = members.flatMap(([key, value]) => typeof value === "number" ? [`${JSON.stringify(key)}: ${value}`, `${JSON.stringify(String(value))}: ${JSON.stringify(key)}`] : [`${JSON.stringify(key)}: ${JSON.stringify(value)}`]);
|
|
286
|
+
return `${ts.slice(0, at)}const ${head[1]} = { ${entries.join(", ")} };${"\n".repeat(ts.slice(at, i).split("\n").length - 1)}${ts.slice(i)}`;
|
|
287
|
+
}
|
|
288
|
+
/** The names a binding pattern declares: `a`, `{ b, c: d }`, `[e, ...f]`, `g = 1`. */
|
|
289
|
+
function bindingNames(node, into) {
|
|
290
|
+
if (!node) return into;
|
|
291
|
+
if (node.type === "Identifier") into.add(node.name);
|
|
292
|
+
else if (node.type === "ObjectPattern") for (const p of node.properties) bindingNames(p.type === "RestElement" ? p.argument : p.value, into);
|
|
293
|
+
else if (node.type === "ArrayPattern") for (const e of node.elements) bindingNames(e, into);
|
|
294
|
+
else if (node.type === "RestElement") bindingNames(node.argument, into);
|
|
295
|
+
else if (node.type === "AssignmentPattern") bindingNames(node.left, into);
|
|
296
|
+
return into;
|
|
297
|
+
}
|
|
298
|
+
/** The nodes a `var` never hoists out of: functions, and a class's static blocks. */
|
|
299
|
+
const FUNCTION_NODES = /^(FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|StaticBlock)$/u;
|
|
300
|
+
/** The names a block declares itself: `let`, `const`, classes and functions in it, and with `vars`, every `var` under it outside nested functions. */
|
|
301
|
+
function scopeNames(statements, vars) {
|
|
302
|
+
const names = /* @__PURE__ */ new Set();
|
|
303
|
+
const hoist = (node) => {
|
|
304
|
+
if (!node || typeof node.type !== "string" || FUNCTION_NODES.test(node.type)) return;
|
|
305
|
+
if (node.type === "VariableDeclaration" && node.kind === "var") for (const d of node.declarations) bindingNames(d.id, names);
|
|
306
|
+
for (const value of Object.values(node)) if (Array.isArray(value)) {
|
|
307
|
+
for (const child of value) if (typeof child?.type === "string") hoist(child);
|
|
308
|
+
} else if (typeof value?.type === "string") hoist(value);
|
|
106
309
|
};
|
|
310
|
+
for (const node of statements) {
|
|
311
|
+
const declaration = /^Export(Named|Default)Declaration$/u.test(node.type) ? node.declaration : node;
|
|
312
|
+
if (!declaration) continue;
|
|
313
|
+
if (declaration.type === "VariableDeclaration" && declaration.kind !== "var") for (const d of declaration.declarations) bindingNames(d.id, names);
|
|
314
|
+
if ((declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") && declaration.id) names.add(declaration.id.name);
|
|
315
|
+
if (vars) hoist(node);
|
|
316
|
+
}
|
|
317
|
+
return names;
|
|
107
318
|
}
|
|
108
|
-
/**
|
|
109
|
-
|
|
319
|
+
/**
|
|
320
|
+
* The imported names a module uses as values: each reference to a name that no scope inside the
|
|
321
|
+
* module declares again. A parameter, variable, function or class of the same name in a nested
|
|
322
|
+
* scope hides the import there, as it does when the code runs.
|
|
323
|
+
*/
|
|
324
|
+
function importsUsed(tree) {
|
|
325
|
+
const used = /* @__PURE__ */ new Set();
|
|
326
|
+
const hidden = (scopes, name) => scopes.some((scope) => scope.has(name));
|
|
327
|
+
const pattern = (node, scopes) => {
|
|
328
|
+
if (!node || node.type === "Identifier") return;
|
|
329
|
+
if (node.type === "ObjectPattern") for (const p of node.properties) if (p.type === "RestElement") pattern(p.argument, scopes);
|
|
330
|
+
else {
|
|
331
|
+
if (p.computed) visit(p.key, scopes);
|
|
332
|
+
pattern(p.value, scopes);
|
|
333
|
+
}
|
|
334
|
+
else if (node.type === "ArrayPattern") for (const e of node.elements) pattern(e, scopes);
|
|
335
|
+
else if (node.type === "RestElement") pattern(node.argument, scopes);
|
|
336
|
+
else if (node.type === "AssignmentPattern") {
|
|
337
|
+
pattern(node.left, scopes);
|
|
338
|
+
visit(node.right, scopes);
|
|
339
|
+
} else visit(node, scopes);
|
|
340
|
+
};
|
|
341
|
+
const children = (node, scopes, skip = /* @__PURE__ */ new Set()) => {
|
|
342
|
+
for (const [field, value] of Object.entries(node)) {
|
|
343
|
+
if (skip.has(field)) continue;
|
|
344
|
+
if (Array.isArray(value)) {
|
|
345
|
+
for (const child of value) if (typeof child?.type === "string") visit(child, scopes);
|
|
346
|
+
} else if (typeof value?.type === "string") visit(value, scopes);
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
function visit(node, scopes) {
|
|
350
|
+
if (!node || typeof node.type !== "string") return;
|
|
351
|
+
switch (node.type) {
|
|
352
|
+
case "ImportDeclaration": return;
|
|
353
|
+
case "Identifier":
|
|
354
|
+
if (!hidden(scopes, node.name)) used.add(node.name);
|
|
355
|
+
return;
|
|
356
|
+
case "MemberExpression":
|
|
357
|
+
visit(node.object, scopes);
|
|
358
|
+
if (node.computed) visit(node.property, scopes);
|
|
359
|
+
return;
|
|
360
|
+
case "Property":
|
|
361
|
+
case "MethodDefinition":
|
|
362
|
+
case "PropertyDefinition":
|
|
363
|
+
if (node.computed) visit(node.key, scopes);
|
|
364
|
+
visit(node.value, scopes);
|
|
365
|
+
return;
|
|
366
|
+
case "LabeledStatement":
|
|
367
|
+
visit(node.body, scopes);
|
|
368
|
+
return;
|
|
369
|
+
case "BreakStatement":
|
|
370
|
+
case "ContinueStatement":
|
|
371
|
+
case "MetaProperty": return;
|
|
372
|
+
case "VariableDeclarator":
|
|
373
|
+
pattern(node.id, scopes);
|
|
374
|
+
visit(node.init, scopes);
|
|
375
|
+
return;
|
|
376
|
+
case "FunctionDeclaration":
|
|
377
|
+
case "FunctionExpression":
|
|
378
|
+
case "ArrowFunctionExpression": {
|
|
379
|
+
const params = /* @__PURE__ */ new Set();
|
|
380
|
+
if (node.type === "FunctionExpression" && node.id) params.add(node.id.name);
|
|
381
|
+
for (const p of node.params) bindingNames(p, params);
|
|
382
|
+
const head = [...scopes, params];
|
|
383
|
+
for (const p of node.params) pattern(p, head);
|
|
384
|
+
const inner = node.body.type === "BlockStatement" ? [...head, scopeNames(node.body.body, true)] : head;
|
|
385
|
+
if (node.body.type === "BlockStatement") for (const statement of node.body.body) visit(statement, inner);
|
|
386
|
+
else visit(node.body, inner);
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
case "ClassDeclaration":
|
|
390
|
+
case "ClassExpression": {
|
|
391
|
+
const inner = node.type === "ClassExpression" && node.id ? [...scopes, /* @__PURE__ */ new Set([node.id.name])] : scopes;
|
|
392
|
+
visit(node.superClass, inner);
|
|
393
|
+
visit(node.body, inner);
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
case "BlockStatement": {
|
|
397
|
+
const inner = [...scopes, scopeNames(node.body, false)];
|
|
398
|
+
for (const statement of node.body) visit(statement, inner);
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
case "StaticBlock": {
|
|
402
|
+
const inner = [...scopes, scopeNames(node.body, true)];
|
|
403
|
+
for (const statement of node.body) visit(statement, inner);
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
case "SwitchStatement": {
|
|
407
|
+
visit(node.discriminant, scopes);
|
|
408
|
+
const inner = [...scopes, scopeNames(node.cases.flatMap((c) => c.consequent), false)];
|
|
409
|
+
for (const c of node.cases) children(c, inner);
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
case "ForStatement":
|
|
413
|
+
case "ForInStatement":
|
|
414
|
+
case "ForOfStatement": {
|
|
415
|
+
const head = node.type === "ForStatement" ? node.init : node.left;
|
|
416
|
+
const own = /* @__PURE__ */ new Set();
|
|
417
|
+
if (head?.type === "VariableDeclaration" && head.kind !== "var") for (const d of head.declarations) bindingNames(d.id, own);
|
|
418
|
+
const inner = own.size ? [...scopes, own] : scopes;
|
|
419
|
+
children(node, inner);
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
case "CatchClause": {
|
|
423
|
+
const inner = [...scopes, bindingNames(node.param, /* @__PURE__ */ new Set())];
|
|
424
|
+
pattern(node.param, inner);
|
|
425
|
+
visit(node.body, inner);
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
case "AssignmentExpression":
|
|
429
|
+
pattern(node.left, scopes);
|
|
430
|
+
visit(node.right, scopes);
|
|
431
|
+
return;
|
|
432
|
+
default: children(node, scopes);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
for (const statement of tree.body) visit(statement, []);
|
|
436
|
+
return used;
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* Stripped TypeScript with each imported name used only as a type taken out, as TypeScript takes it
|
|
440
|
+
* out: an import left with no names goes whole. JavaScript that doesn't parse is kept, for the
|
|
441
|
+
* build's own refusal to name.
|
|
442
|
+
*/
|
|
443
|
+
function typeImportsDropped(js) {
|
|
110
444
|
let tree;
|
|
111
445
|
try {
|
|
112
446
|
tree = parse(js, {
|
|
113
447
|
ecmaVersion: "latest",
|
|
114
448
|
sourceType: "module"
|
|
115
449
|
});
|
|
450
|
+
} catch {
|
|
451
|
+
return js;
|
|
452
|
+
}
|
|
453
|
+
const used = importsUsed(tree);
|
|
454
|
+
const edits = [];
|
|
455
|
+
for (const node of tree.body) {
|
|
456
|
+
if (node.type !== "ImportDeclaration" || !node.specifiers.length) continue;
|
|
457
|
+
const kept = node.specifiers.filter((s) => used.has(s.local.name));
|
|
458
|
+
if (kept.length === node.specifiers.length) continue;
|
|
459
|
+
const lines = "\n".repeat(js.slice(node.start, node.end).split("\n").length - 1);
|
|
460
|
+
const named = kept.filter((s) => s.type === "ImportSpecifier").map((s) => js.slice(s.start, s.end));
|
|
461
|
+
const clause = [...kept.filter((s) => s.type !== "ImportSpecifier").map((s) => js.slice(s.start, s.end)), ...named.length ? [`{ ${named.join(", ")} }`] : []].join(", ");
|
|
462
|
+
edits.push({
|
|
463
|
+
at: node.start,
|
|
464
|
+
end: node.end,
|
|
465
|
+
text: kept.length ? `import ${clause} from ${js.slice(node.source.start, node.source.end)};${lines}` : lines
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
return edited(js, edits);
|
|
469
|
+
}
|
|
470
|
+
/** `js` with each import passed to `link`, which returns the import's new text or null to keep it. */
|
|
471
|
+
function linked(label, js, link) {
|
|
472
|
+
let tree;
|
|
473
|
+
try {
|
|
474
|
+
tree = parse(js, {
|
|
475
|
+
ecmaVersion: "latest",
|
|
476
|
+
sourceType: "module",
|
|
477
|
+
locations: true
|
|
478
|
+
});
|
|
116
479
|
} catch (error) {
|
|
117
|
-
throw new Refused(`${
|
|
480
|
+
throw new Refused(`${label}: does not parse as a module: ${error.message}`);
|
|
118
481
|
}
|
|
119
482
|
const edits = [];
|
|
120
483
|
for (const node of tree.body) {
|
|
121
484
|
if (!node.source || !/^(Import|ExportNamed|ExportAll)Declaration$/u.test(node.type)) continue;
|
|
122
|
-
const
|
|
123
|
-
if (
|
|
485
|
+
const text = link(node.source.value, node);
|
|
486
|
+
if (text !== null) edits.push({
|
|
124
487
|
at: node.source.start,
|
|
125
488
|
end: node.source.end,
|
|
126
|
-
text: JSON.stringify(
|
|
489
|
+
text: JSON.stringify(text)
|
|
127
490
|
});
|
|
128
491
|
}
|
|
129
|
-
|
|
130
|
-
|
|
492
|
+
return {
|
|
493
|
+
out: edited(js, edits),
|
|
494
|
+
tree
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
const edited = (text, edits) => {
|
|
498
|
+
let out = text;
|
|
499
|
+
for (const edit of [...edits].sort((a, b) => b.at - a.at)) out = `${out.slice(0, edit.at)}${edit.text}${out.slice(edit.end)}`;
|
|
131
500
|
return out;
|
|
501
|
+
};
|
|
502
|
+
/** The names a binding pattern declares: `a`, `{ a, b: [c] }`, `...d`, `e = 1`. */
|
|
503
|
+
function patternNames(node, out) {
|
|
504
|
+
if (!node) return;
|
|
505
|
+
if (node.type === "Identifier") out.add(node.name);
|
|
506
|
+
else if (node.type === "ObjectPattern") for (const p of node.properties) patternNames(p.type === "RestElement" ? p.argument : p.value, out);
|
|
507
|
+
else if (node.type === "ArrayPattern") for (const e of node.elements) patternNames(e, out);
|
|
508
|
+
else if (node.type === "RestElement") patternNames(node.argument, out);
|
|
509
|
+
else if (node.type === "AssignmentPattern") patternNames(node.left, out);
|
|
510
|
+
}
|
|
511
|
+
/** The names statements declare in their own block: variables, functions, classes and imports. */
|
|
512
|
+
function blockNames(statements, out) {
|
|
513
|
+
for (const one of statements) {
|
|
514
|
+
const node = one.type === "ExportNamedDeclaration" || one.type === "ExportDefaultDeclaration" ? one.declaration : one;
|
|
515
|
+
if (!node) continue;
|
|
516
|
+
if (node.type === "VariableDeclaration") for (const d of node.declarations) patternNames(d.id, out);
|
|
517
|
+
if ((node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") && node.id) out.add(node.id.name);
|
|
518
|
+
if (node.type === "ImportDeclaration") for (const s of node.specifiers) out.add(s.local.name);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
/** The `var`s a function body or a module declares anywhere in it, outside the functions inside it. */
|
|
522
|
+
function varNames(node, out) {
|
|
523
|
+
for (const value of Object.values(node)) for (const child of Array.isArray(value) ? value : [value]) {
|
|
524
|
+
if (!child || typeof child.type !== "string" || /Function/u.test(child.type)) continue;
|
|
525
|
+
if (child.type === "VariableDeclaration" && child.kind === "var") for (const d of child.declarations) patternNames(d.id, out);
|
|
526
|
+
varNames(child, out);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
/** Every call of `name` where no scope around it binds `name`: the global's, which a module may not call. */
|
|
530
|
+
function unboundCalls(tree, name) {
|
|
531
|
+
const found = [];
|
|
532
|
+
const visit = (node, bound) => {
|
|
533
|
+
let here = bound;
|
|
534
|
+
if (!here) {
|
|
535
|
+
const names = /* @__PURE__ */ new Set();
|
|
536
|
+
if (node.type === "Program") {
|
|
537
|
+
blockNames(node.body, names);
|
|
538
|
+
varNames(node, names);
|
|
539
|
+
} else if (/^(FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/u.test(node.type)) {
|
|
540
|
+
for (const p of node.params) patternNames(p, names);
|
|
541
|
+
if (node.type === "FunctionExpression" && node.id) names.add(node.id.name);
|
|
542
|
+
if (node.body.type === "BlockStatement") {
|
|
543
|
+
blockNames(node.body.body, names);
|
|
544
|
+
varNames(node.body, names);
|
|
545
|
+
}
|
|
546
|
+
} else if (node.type === "BlockStatement" || node.type === "StaticBlock") blockNames(node.body, names);
|
|
547
|
+
else if (node.type === "SwitchStatement") blockNames(node.cases.flatMap((c) => c.consequent), names);
|
|
548
|
+
else if (node.type === "ForStatement" && node.init?.type === "VariableDeclaration") blockNames([node.init], names);
|
|
549
|
+
else if ((node.type === "ForInStatement" || node.type === "ForOfStatement") && node.left.type === "VariableDeclaration") blockNames([node.left], names);
|
|
550
|
+
else if (node.type === "CatchClause") patternNames(node.param, names);
|
|
551
|
+
else if (node.type === "ClassExpression" && node.id) names.add(node.id.name);
|
|
552
|
+
here = names.has(name);
|
|
553
|
+
}
|
|
554
|
+
if (!here && node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === name) found.push(node);
|
|
555
|
+
for (const value of Object.values(node)) for (const child of Array.isArray(value) ? value : [value]) if (child && typeof child.type === "string") visit(child, here);
|
|
556
|
+
};
|
|
557
|
+
visit(tree, false);
|
|
558
|
+
return found;
|
|
559
|
+
}
|
|
560
|
+
/** Whether a module's parse has an import or export of its own. */
|
|
561
|
+
const hasModuleSyntax = (tree) => tree.body.some((node) => /^(Import|ExportNamed|ExportAll|ExportDefault)Declaration$/u.test(node.type));
|
|
562
|
+
/** Whether a package's .js file is CommonJS: no import or export of its own, in a package that doesn't say `"type": "module"`. */
|
|
563
|
+
function isCommonJs(text, pkg) {
|
|
564
|
+
let tree;
|
|
565
|
+
try {
|
|
566
|
+
tree = parse(text, {
|
|
567
|
+
ecmaVersion: "latest",
|
|
568
|
+
sourceType: "module"
|
|
569
|
+
});
|
|
570
|
+
} catch {
|
|
571
|
+
return true;
|
|
572
|
+
}
|
|
573
|
+
if (hasModuleSyntax(tree)) return false;
|
|
574
|
+
return pkg.json.type !== "module";
|
|
575
|
+
}
|
|
576
|
+
/** What an ES module import may resolve to, and what a `require` may: each in the package's own order, the other after. */
|
|
577
|
+
const IMPORTING = /* @__PURE__ */ new Set([
|
|
578
|
+
"import",
|
|
579
|
+
"module",
|
|
580
|
+
"default"
|
|
581
|
+
]);
|
|
582
|
+
const REQUIRING = /* @__PURE__ */ new Set(["require", "default"]);
|
|
583
|
+
function exportTarget(entry, conditions) {
|
|
584
|
+
if (typeof entry === "string") return entry;
|
|
585
|
+
if (Array.isArray(entry)) {
|
|
586
|
+
for (const one of entry) {
|
|
587
|
+
const found = exportTarget(one, conditions);
|
|
588
|
+
if (found) return found;
|
|
589
|
+
}
|
|
590
|
+
return null;
|
|
591
|
+
}
|
|
592
|
+
if (entry && typeof entry === "object") {
|
|
593
|
+
for (const [key, value] of Object.entries(entry)) if (conditions.has(key)) {
|
|
594
|
+
const found = exportTarget(value, conditions);
|
|
595
|
+
if (found) return found;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
return null;
|
|
599
|
+
}
|
|
600
|
+
/**
|
|
601
|
+
* The file a package's `exports` gives `sub` ("." or "./<path>"), with `*` patterns; null when it
|
|
602
|
+
* gives none. Of the patterns that match, the longest part before `*` wins, then the longest key, as Node orders them.
|
|
603
|
+
*/
|
|
604
|
+
function exported(exports, sub, conditions = IMPORTING) {
|
|
605
|
+
const map = exports && typeof exports === "object" && !Array.isArray(exports) && Object.keys(exports).some((key) => key.startsWith(".")) ? exports : { ".": exports };
|
|
606
|
+
if (Object.hasOwn(map, sub)) return exportTarget(map[sub], conditions);
|
|
607
|
+
let best = null;
|
|
608
|
+
for (const [key, value] of Object.entries(map)) {
|
|
609
|
+
const star = key.indexOf("*");
|
|
610
|
+
if (star < 0 || key.indexOf("*", star + 1) >= 0) continue;
|
|
611
|
+
const prefix = key.slice(0, star), suffix = key.slice(star + 1);
|
|
612
|
+
if (sub.length < key.length - 1 || !sub.startsWith(prefix) || !sub.endsWith(suffix)) continue;
|
|
613
|
+
if (!best || prefix.length > best.prefix.length || prefix.length === best.prefix.length && key.length > best.key.length) best = {
|
|
614
|
+
key,
|
|
615
|
+
prefix,
|
|
616
|
+
match: sub.slice(prefix.length, sub.length - suffix.length),
|
|
617
|
+
value
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
return best ? exportTarget(best.value, conditions)?.replaceAll("*", best.match) ?? null : null;
|
|
621
|
+
}
|
|
622
|
+
/** The path of a package or project file in the build: its own path, with `.mjs` added unless it ends so, so no two files share one. */
|
|
623
|
+
const builtName = (inside) => inside.endsWith(".mjs") ? inside : `${inside}.mjs`;
|
|
624
|
+
const PROJECT = "node_modules/.project";
|
|
625
|
+
/**
|
|
626
|
+
* Builds every module the folder's sources reach: theirs, the project's files outside the folder
|
|
627
|
+
* they import, and each installed package file they import or require, in the order found, so the
|
|
628
|
+
* same inputs build the same files. Throws `Refused`.
|
|
629
|
+
*/
|
|
630
|
+
function linkAll(sources, packages, strip) {
|
|
631
|
+
const { stripped, built } = sources;
|
|
632
|
+
const files = {}, from = {};
|
|
633
|
+
const inputs = /* @__PURE__ */ new Set();
|
|
634
|
+
const found = /* @__PURE__ */ new Map();
|
|
635
|
+
const prefixes = /* @__PURE__ */ new Map();
|
|
636
|
+
const owners = /* @__PURE__ */ new Map();
|
|
637
|
+
const queue = [];
|
|
638
|
+
const builtOf = (name) => `${name}.mjs`;
|
|
639
|
+
const root = packages?.root ?? "";
|
|
640
|
+
for (const [name, { file, js }] of stripped) {
|
|
641
|
+
queue.push({
|
|
642
|
+
path: builtOf(name),
|
|
643
|
+
label: file,
|
|
644
|
+
text: js,
|
|
645
|
+
kind: "author",
|
|
646
|
+
at: dirOf(file) ? `${root}/${dirOf(file)}` : root
|
|
647
|
+
});
|
|
648
|
+
owners.set(builtOf(name), `db:${file}`);
|
|
649
|
+
}
|
|
650
|
+
for (const [path, text] of built) {
|
|
651
|
+
queue.push({
|
|
652
|
+
path,
|
|
653
|
+
label: path,
|
|
654
|
+
text,
|
|
655
|
+
kind: "built",
|
|
656
|
+
at: ""
|
|
657
|
+
});
|
|
658
|
+
owners.set(path, `upload:${path}`);
|
|
659
|
+
}
|
|
660
|
+
const read = (path) => {
|
|
661
|
+
const text = packages.read(path);
|
|
662
|
+
if (text !== null) inputs.add(path);
|
|
663
|
+
return text;
|
|
664
|
+
};
|
|
665
|
+
const exists = (path) => packages.read(path) !== null;
|
|
666
|
+
const probe = (path, extensions) => {
|
|
667
|
+
for (const candidate of [
|
|
668
|
+
path,
|
|
669
|
+
...extensions.map((x) => `${path}${x}`),
|
|
670
|
+
...extensions.map((x) => `${path}/index${x}`)
|
|
671
|
+
]) if (exists(candidate)) return candidate;
|
|
672
|
+
return null;
|
|
673
|
+
};
|
|
674
|
+
/** The folder files outside `db/` may come from: the nearest one at or above it with a package.json, else the one holding it. */
|
|
675
|
+
let project = null;
|
|
676
|
+
const projectRoot = () => {
|
|
677
|
+
if (project !== null) return project;
|
|
678
|
+
for (let dir = root; dir; dir = dirOf(dir)) if (exists(`${dir}/package.json`)) return project = dir;
|
|
679
|
+
return project = dirOf(root);
|
|
680
|
+
};
|
|
681
|
+
/** The package a bare import names, from the folder `at` up, as Node looks for it. */
|
|
682
|
+
function packageFor(name, at) {
|
|
683
|
+
for (let dir = at;; dir = dirOf(dir)) {
|
|
684
|
+
const text = packages.read(`${dir}/node_modules/${name}/package.json`);
|
|
685
|
+
if (text !== null) {
|
|
686
|
+
const real = packages.real(`${dir}/node_modules/${name}`);
|
|
687
|
+
const known = found.get(real);
|
|
688
|
+
if (known) return known;
|
|
689
|
+
let json;
|
|
690
|
+
try {
|
|
691
|
+
json = JSON.parse(text);
|
|
692
|
+
} catch {
|
|
693
|
+
throw new Refused(`${name}: its package.json does not parse`);
|
|
694
|
+
}
|
|
695
|
+
inputs.add(`${real}/package.json`);
|
|
696
|
+
const version = typeof json.version === "string" ? json.version : "0.0.0";
|
|
697
|
+
const copies = (prefixes.get(`${name}@${version}`) ?? 0) + 1;
|
|
698
|
+
prefixes.set(`${name}@${version}`, copies);
|
|
699
|
+
const pkg = {
|
|
700
|
+
name,
|
|
701
|
+
version,
|
|
702
|
+
dir: real,
|
|
703
|
+
json,
|
|
704
|
+
prefix: `${name}@${version}${copies > 1 ? `~${copies}` : ""}`
|
|
705
|
+
};
|
|
706
|
+
found.set(real, pkg);
|
|
707
|
+
return pkg;
|
|
708
|
+
}
|
|
709
|
+
if (!dir || dir === "/" || dirOf(dir) === dir) return null;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
/** A file's built path, its module queued to build once; a different file at the same path is refused. */
|
|
713
|
+
function take(path, file, make) {
|
|
714
|
+
const owner = owners.get(path);
|
|
715
|
+
if (owner === void 0) {
|
|
716
|
+
owners.set(path, file);
|
|
717
|
+
queue.push(make());
|
|
718
|
+
} else if (owner !== file) throw new Refused(`${file} and ${owner} would both be built as ${path}. Rename one file.`);
|
|
719
|
+
return path;
|
|
720
|
+
}
|
|
721
|
+
function takePackage(pkg, file, label) {
|
|
722
|
+
const inside = file.slice(pkg.dir.length + 1);
|
|
723
|
+
const where = `${pkg.prefix}/${inside}`;
|
|
724
|
+
const ext = extensionOf(inside);
|
|
725
|
+
if (![
|
|
726
|
+
".js",
|
|
727
|
+
".mjs",
|
|
728
|
+
".cjs",
|
|
729
|
+
".json"
|
|
730
|
+
].includes(ext)) throw new Refused(`${label}: ${where} is not JavaScript or JSON (a package's .js, .mjs, .cjs and .json files are built in)`);
|
|
731
|
+
return take(`node_modules/${pkg.prefix}/${builtName(inside)}`, file, () => {
|
|
732
|
+
const text = read(file);
|
|
733
|
+
const kind = ext === ".json" ? "json" : ext === ".cjs" || ext === ".js" && isCommonJs(text, pkg) ? "cjs" : "esm";
|
|
734
|
+
return {
|
|
735
|
+
path: `node_modules/${pkg.prefix}/${builtName(inside)}`,
|
|
736
|
+
label: where,
|
|
737
|
+
text,
|
|
738
|
+
kind,
|
|
739
|
+
at: dirOf(file),
|
|
740
|
+
pkg
|
|
741
|
+
};
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
function takeProject(file, line) {
|
|
745
|
+
const inside = file.slice(projectRoot().length + 1);
|
|
746
|
+
if (![
|
|
747
|
+
".ts",
|
|
748
|
+
".mts",
|
|
749
|
+
".js",
|
|
750
|
+
".mjs",
|
|
751
|
+
".json"
|
|
752
|
+
].includes(extensionOf(inside))) throw new Refused(`${line}: ${inside} is not a source (.ts, .mts, .js or .mjs) or JSON`);
|
|
753
|
+
const real = packages.real(file), realRoot = packages.real(projectRoot());
|
|
754
|
+
if (!real.startsWith(`${realRoot}/`) || real.slice(realRoot.length).split("/").includes("node_modules")) throw new Refused(`${line}: ${inside} links to a file outside the project (${realRoot || "/"}); a file outside db/ is built in only from the project's own folders`);
|
|
755
|
+
const label = relativeSpec(`${root.replace(/^\//u, "")}/_`, file.replace(/^\//u, ""));
|
|
756
|
+
if (extensionOf(inside) === ".json") return take(`${PROJECT}/${builtName(inside)}`, file, () => ({
|
|
757
|
+
path: `${PROJECT}/${builtName(inside)}`,
|
|
758
|
+
label,
|
|
759
|
+
text: read(file),
|
|
760
|
+
kind: "json",
|
|
761
|
+
at: dirOf(file)
|
|
762
|
+
}));
|
|
763
|
+
return take(`${PROJECT}/${builtName(inside)}`, file, () => ({
|
|
764
|
+
path: `${PROJECT}/${builtName(inside)}`,
|
|
765
|
+
label,
|
|
766
|
+
text: stripped1(label, read(file), strip),
|
|
767
|
+
kind: "project",
|
|
768
|
+
at: dirOf(file)
|
|
769
|
+
}));
|
|
770
|
+
}
|
|
771
|
+
/** A bare specifier's file in its package, as `conditions` choose it, the other kind of import's after. */
|
|
772
|
+
function packageFile(spec, at, conditions, line) {
|
|
773
|
+
const bare = /^((?:@[^/]+\/)?[^/@:][^/:]*)(\/.*)?$/u.exec(spec);
|
|
774
|
+
const pkg = bare && packages ? packageFor(bare[1], at) : null;
|
|
775
|
+
if (!bare || !pkg) return null;
|
|
776
|
+
const sub = `.${bare[2] ?? ""}`;
|
|
777
|
+
let target;
|
|
778
|
+
if (pkg.json.exports !== void 0) {
|
|
779
|
+
target = exported(pkg.json.exports, sub, conditions) ?? exported(pkg.json.exports, sub, conditions === IMPORTING ? REQUIRING : IMPORTING);
|
|
780
|
+
if (target === null) throw new Refused(`${line}: import of "${spec}": ${pkg.name}@${pkg.version} exports no "${sub}"`);
|
|
781
|
+
} else target = sub === "." ? String((conditions === IMPORTING ? pkg.json.module : void 0) ?? pkg.json.main ?? "index.js") : sub;
|
|
782
|
+
const at2 = joined(pkg.dir, target);
|
|
783
|
+
const file = at2 === null || !at2.startsWith(`${pkg.dir}/`) ? null : probe(at2, [
|
|
784
|
+
".mjs",
|
|
785
|
+
".js",
|
|
786
|
+
".cjs",
|
|
787
|
+
".json"
|
|
788
|
+
]);
|
|
789
|
+
if (file === null) throw new Refused(`${line}: import of "${spec}": ${pkg.name}@${pkg.version} has no file ${target}`);
|
|
790
|
+
return {
|
|
791
|
+
pkg,
|
|
792
|
+
file
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
/** Where a relative import from `one` leads, as a built path; null when it leads nowhere admitted. */
|
|
796
|
+
function relative(one, spec, line) {
|
|
797
|
+
if (one.kind === "author") {
|
|
798
|
+
const at = joined(dirOf(one.path), spec);
|
|
799
|
+
if (at !== null) {
|
|
800
|
+
if (GENERATED.test(at)) return null;
|
|
801
|
+
if (at.endsWith(".json") && packages && exists(`${root}/${at}`)) return takeProject(`${root}/${at}`, line);
|
|
802
|
+
const name = at.replace(/\.(?:ts|mts|js|mjs)$/u, "");
|
|
803
|
+
const hit = stripped.has(name) ? name : stripped.has(`${name}/index`) ? `${name}/index` : null;
|
|
804
|
+
return hit === null ? null : builtOf(hit);
|
|
805
|
+
}
|
|
806
|
+
if (!packages) return null;
|
|
807
|
+
}
|
|
808
|
+
if (one.kind === "author" || one.kind === "project") {
|
|
809
|
+
const at = joined(one.at, spec);
|
|
810
|
+
if (at === null) return null;
|
|
811
|
+
if (at.startsWith(`${root}/`)) {
|
|
812
|
+
const name = at.slice(root.length + 1).replace(/\.(?:ts|mts|js|mjs)$/u, "");
|
|
813
|
+
return stripped.has(name) ? builtOf(name) : stripped.has(`${name}/index`) ? builtOf(`${name}/index`) : null;
|
|
814
|
+
}
|
|
815
|
+
if (!at.startsWith(`${projectRoot()}/`) || at.split("/").includes("node_modules")) throw new Refused(`${line}: import of "${spec}": outside the project (${projectRoot() || "/"}); a file outside db/ is built in only from the project's own folders`);
|
|
816
|
+
const file = probe(at, [
|
|
817
|
+
".ts",
|
|
818
|
+
".mts",
|
|
819
|
+
".js",
|
|
820
|
+
".mjs"
|
|
821
|
+
]);
|
|
822
|
+
if (file === null) throw new Refused(`${line}: import of "${spec}": no such file`);
|
|
823
|
+
return takeProject(file, line);
|
|
824
|
+
}
|
|
825
|
+
const at = joined(one.at, spec);
|
|
826
|
+
const file = at === null || !at.startsWith(`${one.pkg.dir}/`) ? null : probe(at, [
|
|
827
|
+
".mjs",
|
|
828
|
+
".js",
|
|
829
|
+
".cjs",
|
|
830
|
+
".json"
|
|
831
|
+
]);
|
|
832
|
+
if (file === null) throw new Refused(`${line}: import of "${spec}": no such file in ${one.pkg.prefix}`);
|
|
833
|
+
return takePackage(one.pkg, file, line);
|
|
834
|
+
}
|
|
835
|
+
while (queue.length) {
|
|
836
|
+
const one = queue.shift();
|
|
837
|
+
from[one.path] = one.label;
|
|
838
|
+
if (one.kind === "json") {
|
|
839
|
+
files[one.path] = jsonModule(one.label, one.text);
|
|
840
|
+
continue;
|
|
841
|
+
}
|
|
842
|
+
if (one.kind === "cjs") {
|
|
843
|
+
const { body, facade } = commonJsModule(one.label, one.text, `./${one.path.split("/").at(-1).replace(/\.mjs$/u, ".load.mjs")}`, (spec, line) => {
|
|
844
|
+
const at = spec.startsWith("./") || spec.startsWith("../") ? joined(one.at, spec) : null;
|
|
845
|
+
const file = at !== null ? at.startsWith(`${one.pkg.dir}/`) ? probe(at, [
|
|
846
|
+
".js",
|
|
847
|
+
".cjs",
|
|
848
|
+
".json",
|
|
849
|
+
".mjs"
|
|
850
|
+
]) : null : packageFile(spec, one.at, REQUIRING, `${one.label}:${line}`);
|
|
851
|
+
if (file === null) return null;
|
|
852
|
+
const [pkg, path] = typeof file === "string" ? [one.pkg, file] : [file.pkg, file.file];
|
|
853
|
+
const built = takePackage(pkg, path, `${one.label}:${line}`);
|
|
854
|
+
const ext = extensionOf(path);
|
|
855
|
+
return relativeSpec(one.path, ext === ".cjs" || ext === ".js" && isCommonJs(read(path), pkg) ? lazyOf(built) : built);
|
|
856
|
+
});
|
|
857
|
+
files[one.path] = facade;
|
|
858
|
+
files[lazyOf(one.path)] = body;
|
|
859
|
+
from[lazyOf(one.path)] = one.label;
|
|
860
|
+
continue;
|
|
861
|
+
}
|
|
862
|
+
const { out } = linked(one.label, one.text, (spec, node) => {
|
|
863
|
+
const line = `${one.label}${node.loc ? `:${node.loc.start.line}` : ""}`;
|
|
864
|
+
if (spec === SDK) return null;
|
|
865
|
+
if (one.kind === "built") return null;
|
|
866
|
+
if (spec.startsWith("./") || spec.startsWith("../")) {
|
|
867
|
+
const target = relative(one, spec, line);
|
|
868
|
+
return target === null ? null : relativeSpec(one.path, target);
|
|
869
|
+
}
|
|
870
|
+
if (/^[a-z]+:/u.test(spec)) return null;
|
|
871
|
+
const resolved = packageFile(spec, one.at, IMPORTING, line);
|
|
872
|
+
if (!resolved) throw new Refused(`${line}: import of "${spec}": no installed package ${spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/")} (a package is found in node_modules at db/ or a folder above it)`);
|
|
873
|
+
return relativeSpec(one.path, takePackage(resolved.pkg, resolved.file, line));
|
|
874
|
+
});
|
|
875
|
+
files[one.path] = out;
|
|
876
|
+
}
|
|
877
|
+
const sorted = Object.fromEntries(Object.entries(files).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
|
878
|
+
const count = Object.keys(sorted).length;
|
|
879
|
+
if (count > 4e3) throw new Refused(`The build is ${count} files, over ${BUILD_FILES}. Import fewer packages, or smaller parts of them.`);
|
|
880
|
+
let total = 0;
|
|
881
|
+
const byPackage = /* @__PURE__ */ new Map();
|
|
882
|
+
for (const [path, text] of Object.entries(sorted)) {
|
|
883
|
+
const bytes = bytesOf(text);
|
|
884
|
+
if (bytes > 1048576) throw new Refused(`${from[path]} is ${mib(bytes)}, over ${mib(MODULE_BYTES)} for one file. ${path.startsWith("node_modules/") ? "Import a smaller part of its package" : "Split it into smaller modules"}.`);
|
|
885
|
+
total += bytes;
|
|
886
|
+
const pkg = /^node_modules\/((?:@[^/]+\/)?[^/]+)\//u.exec(path)?.[1];
|
|
887
|
+
if (pkg) byPackage.set(pkg, (byPackage.get(pkg) ?? 0) + bytes);
|
|
888
|
+
}
|
|
889
|
+
if (total > 8388608) {
|
|
890
|
+
const largest = [...byPackage].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).slice(0, 3).map(([name, bytes]) => `${name} (${mib(bytes)})`);
|
|
891
|
+
throw new Refused(`The build is ${mib(total)}, over ${mib(BUILD_BYTES)}.${largest.length ? ` Its largest packages: ${largest.join(", ")}.` : ""}`);
|
|
892
|
+
}
|
|
893
|
+
return {
|
|
894
|
+
files: sorted,
|
|
895
|
+
from: Object.fromEntries(Object.keys(sorted).map((path) => [path, from[path]])),
|
|
896
|
+
inputs: [...inputs].sort()
|
|
897
|
+
};
|
|
898
|
+
}
|
|
899
|
+
/** A JSON file as a module: its value, as `require` and a default import give it. */
|
|
900
|
+
function jsonModule(label, text) {
|
|
901
|
+
try {
|
|
902
|
+
JSON.parse(text);
|
|
903
|
+
} catch {
|
|
904
|
+
throw new Refused(`${label}: does not parse as JSON`);
|
|
905
|
+
}
|
|
906
|
+
return `const json = JSON.parse(${JSON.stringify(text)});\nexport default json;\nexport { json as "module.exports" };\n`;
|
|
907
|
+
}
|
|
908
|
+
/** The built path of a CommonJS file's code, run when first required: `index.js.mjs`'s is `index.js.load.mjs`. */
|
|
909
|
+
const lazyOf = (path) => path.replace(/\.mjs$/u, ".load.mjs");
|
|
910
|
+
/**
|
|
911
|
+
* A CommonJS file as ES modules. Its `body` defines `__load()`, which runs its code once, the first
|
|
912
|
+
* time it is called, in a function given `module`, `exports` and `require`, and gives `module.exports`
|
|
913
|
+
* (the exports so far while it runs, so a cycle sees partial exports, as Node gives them). A
|
|
914
|
+
* `require("<literal>")` of another CommonJS file reaches that file's `__load`, so a require in a
|
|
915
|
+
* branch that never runs runs nothing. The `facade`, which an import reaches, loads it and exports
|
|
916
|
+
* `module.exports` as the default and by each name it assigns. A `require` of what the build has not
|
|
917
|
+
* (a Node built-in, a package not installed) throws when it runs, as an optional one is meant to. A
|
|
918
|
+
* body that throws is run again by the next require, as Node runs it again. The body keeps its lines.
|
|
919
|
+
*/
|
|
920
|
+
function commonJsModule(label, text, body, resolve) {
|
|
921
|
+
const code = text.startsWith("#!") ? `//${text.slice(2)}` : text;
|
|
922
|
+
let tree;
|
|
923
|
+
try {
|
|
924
|
+
tree = parse(code, {
|
|
925
|
+
ecmaVersion: "latest",
|
|
926
|
+
sourceType: "script",
|
|
927
|
+
allowReturnOutsideFunction: true,
|
|
928
|
+
locations: true
|
|
929
|
+
});
|
|
930
|
+
} catch (error) {
|
|
931
|
+
throw new Refused(`${label}: does not parse as CommonJS: ${error.message}`);
|
|
932
|
+
}
|
|
933
|
+
const specs = /* @__PURE__ */ new Map();
|
|
934
|
+
const names = /* @__PURE__ */ new Set();
|
|
935
|
+
const isExports = (node) => node.type === "Identifier" && node.name === "exports" || node.type === "MemberExpression" && !node.computed && node.object.type === "Identifier" && node.object.name === "module" && node.property.name === "exports";
|
|
936
|
+
const keyOf = (node) => node.type === "Identifier" ? node.name : node.type === "Literal" && typeof node.value === "string" ? node.value : null;
|
|
937
|
+
for (const node of nodes(tree)) {
|
|
938
|
+
if (node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "require" && node.arguments.length === 1 && node.arguments[0].type === "Literal" && typeof node.arguments[0].value === "string") {
|
|
939
|
+
const spec = node.arguments[0].value;
|
|
940
|
+
if (!specs.has(spec)) specs.set(spec, resolve(spec, node.loc?.start.line ?? 0));
|
|
941
|
+
}
|
|
942
|
+
if (node.type === "AssignmentExpression" && node.left.type === "MemberExpression" && isExports(node.left.object)) {
|
|
943
|
+
const key = node.left.computed ? keyOf(node.left.property) : node.left.property.name;
|
|
944
|
+
if (key) names.add(key);
|
|
945
|
+
}
|
|
946
|
+
if (node.type === "AssignmentExpression" && isExports(node.left) && node.left.type === "MemberExpression" && node.right.type === "ObjectExpression") for (const p of node.right.properties) {
|
|
947
|
+
const key = p.type === "Property" && !p.computed ? keyOf(p.key) : null;
|
|
948
|
+
if (key) names.add(key);
|
|
949
|
+
}
|
|
950
|
+
if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && !node.callee.computed && node.callee.object.type === "Identifier" && node.callee.object.name === "Object" && node.callee.property.name === "defineProperty" && node.arguments[0] && isExports(node.arguments[0]) && node.arguments[1]) {
|
|
951
|
+
const key = keyOf(node.arguments[1]);
|
|
952
|
+
if (key) names.add(key);
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
for (const reserved of [
|
|
956
|
+
"default",
|
|
957
|
+
"__esModule",
|
|
958
|
+
"module.exports"
|
|
959
|
+
]) names.delete(reserved);
|
|
960
|
+
const imported = [...specs].filter(([, path]) => path !== null);
|
|
961
|
+
const head = [
|
|
962
|
+
...imported.map(([, path], i) => `import * as __i${i} from ${JSON.stringify(path)};`),
|
|
963
|
+
"let __m = null;",
|
|
964
|
+
"const __r = (ns) => (\"__load\" in ns ? ns.__load() : \"module.exports\" in ns ? ns[\"module.exports\"] : ns);",
|
|
965
|
+
`const __require = (spec) => { switch (spec) { ${[...specs].map(([spec, path]) => `case ${JSON.stringify(spec)}: ${path === null ? `throw new Error(${JSON.stringify(`require(${JSON.stringify(spec)}) in ${label}: not in this build (a Node built-in, or a package that is not installed)`)});` : `return __r(__i${imported.findIndex(([s]) => s === spec)});`}`).join(" ")} default: throw new Error("require(" + JSON.stringify(spec) + ") in " + ${JSON.stringify(label)} + ": not in this build (only a require of a literal is built in)"); } };`,
|
|
966
|
+
"export function __load() { if (__m) return __m.exports; const m = (__m = { exports: {} }); try {",
|
|
967
|
+
"(function (exports, require, module, __filename, __dirname) {"
|
|
968
|
+
].join(" ");
|
|
969
|
+
const tail = "}).call(m.exports, m.exports, __require, m, undefined, undefined); } catch (error) { __m = null; throw error } return m.exports; }";
|
|
970
|
+
const facade = [
|
|
971
|
+
`import { __load } from ${JSON.stringify(body)};`,
|
|
972
|
+
"const __e = __load();",
|
|
973
|
+
"export default (__e && __e.__esModule && \"default\" in __e) ? __e.default : __e;",
|
|
974
|
+
"export { __e as \"module.exports\" };",
|
|
975
|
+
...[...names].sort().map((name, i) => `const __x${i} = __e[${JSON.stringify(name)}]; export { __x${i} as ${JSON.stringify(name)} };`)
|
|
976
|
+
].join("\n");
|
|
977
|
+
return {
|
|
978
|
+
body: `${head}${code}\n${tail}\n`,
|
|
979
|
+
facade: `${facade}\n`
|
|
980
|
+
};
|
|
132
981
|
}
|
|
133
982
|
/** Parses one built module and checks every rule of admission. Throws `Refused` naming the author's file and line. */
|
|
134
|
-
function inspect(file, text,
|
|
983
|
+
function inspect(file, path, text, built) {
|
|
135
984
|
const refuse = (why, node) => {
|
|
136
985
|
throw new Refused(`${file}${node?.loc ? `:${node.loc.start.line}` : ""}: ${why}`);
|
|
137
986
|
};
|
|
@@ -145,6 +994,8 @@ function inspect(file, text, siblings) {
|
|
|
145
994
|
} catch (error) {
|
|
146
995
|
return refuse(`does not parse as a module: ${error.message}`);
|
|
147
996
|
}
|
|
997
|
+
const unbound = unboundCalls(tree, "require")[0];
|
|
998
|
+
if (unbound) refuse("require() in an ES module (the Database has none: import it)", unbound);
|
|
148
999
|
for (const node of nodes(tree)) {
|
|
149
1000
|
if (node.type === "ImportExpression") refuse("a dynamic import() (a function loads nothing at runtime)", node);
|
|
150
1001
|
if (node.type === "MetaProperty" && node.meta.name === "import") refuse("import.meta", node);
|
|
@@ -152,23 +1003,28 @@ function inspect(file, text, siblings) {
|
|
|
152
1003
|
if (!node.source || !/^(Import|ExportNamed|ExportAll)Declaration$/u.test(node.type)) continue;
|
|
153
1004
|
if (node.attributes?.length) refuse("import attributes", node);
|
|
154
1005
|
const spec = node.source.value;
|
|
155
|
-
const
|
|
1006
|
+
const relative = spec.startsWith("./") || spec.startsWith("../") ? joined(dirOf(path), spec) : null;
|
|
1007
|
+
const generated = relative !== null && !path.startsWith("node_modules/") ? GENERATED.exec(relative) : null;
|
|
1008
|
+
const allowed = SURFACES.get(generated ? `./_generated/${generated[1]}` : spec);
|
|
156
1009
|
if (allowed) {
|
|
157
1010
|
const names = (node.specifiers ?? []).map((s) => s.type === "ImportSpecifier" && s.imported.type === "Identifier" && s.imported.name === s.local.name ? s.local.name : null);
|
|
158
1011
|
if (names.includes("defineFunction")) refuse("defineFunction: define with query, mutation or action", node);
|
|
159
1012
|
if (node.type !== "ImportDeclaration" || !names.length || !names.every((name) => name !== null && allowed.has(name))) refuse(`only \`import { ${[...allowed].join(", ")} } from "${spec}"\` (no renaming)`, node);
|
|
160
1013
|
continue;
|
|
161
1014
|
}
|
|
162
|
-
|
|
163
|
-
if (!sibling || !siblings.has(sibling)) refuse(`import of "${spec}" (only "${SDK}", "./_generated/server", "./_generated/api" and modules of this folder are admitted)`, node);
|
|
1015
|
+
if (relative === null || !Object.hasOwn(built, relative)) refuse(`import of "${spec}" (only "${SDK}", "./_generated/server", "./_generated/api", modules of this project and installed packages are admitted)`, node);
|
|
164
1016
|
}
|
|
165
1017
|
return tree;
|
|
166
1018
|
}
|
|
167
|
-
/**
|
|
1019
|
+
/**
|
|
1020
|
+
* A file's functions, as top-level exports; the HTTP actions written as a route's `handler`; and the
|
|
1021
|
+
* count of definer calls anywhere (each must be one of them).
|
|
1022
|
+
*/
|
|
168
1023
|
function definersOf(tree, base) {
|
|
169
|
-
const isDefiner = (n) => n?.type === "CallExpression" && n.callee.type === "Identifier" && DEFINERS.includes(n.callee.name);
|
|
1024
|
+
const isDefiner = (n) => n?.type === "CallExpression" && n.callee.type === "Identifier" && [...DEFINERS, "httpAction"].includes(n.callee.name);
|
|
170
1025
|
const literal = (n) => n?.type === "Literal" && typeof n.value === "string" ? n.value : null;
|
|
171
1026
|
const calls = [...nodes(tree)].filter(isDefiner).length;
|
|
1027
|
+
const routed = [...nodes(tree)].filter((n) => n.type === "CallExpression" && n.callee.type === "MemberExpression" && !n.callee.computed && n.callee.property.name === "route").flatMap((n) => (n.arguments[0]?.properties ?? []).filter((p) => p.type === "Property" && !p.computed && (p.key.name ?? p.key.value) === "handler" && p.value.type === "CallExpression" && p.value.callee.type === "Identifier" && p.value.callee.name === "httpAction")).length;
|
|
172
1028
|
const defs = [];
|
|
173
1029
|
for (const top of tree.body) {
|
|
174
1030
|
if (top.type === "ExportDefaultDeclaration" && isDefiner(top.declaration)) {
|
|
@@ -187,27 +1043,80 @@ function definersOf(tree, base) {
|
|
|
187
1043
|
kind: one.init.callee.name,
|
|
188
1044
|
name: `${base}.${one.id.name}`,
|
|
189
1045
|
export: one.id.name,
|
|
190
|
-
named: one.init.arguments[0]?.type !== "ObjectExpression",
|
|
1046
|
+
named: one.init.callee.name !== "httpAction" && one.init.arguments[0]?.type !== "ObjectExpression",
|
|
191
1047
|
call: one.init
|
|
192
1048
|
});
|
|
193
1049
|
}
|
|
194
1050
|
}
|
|
195
1051
|
return {
|
|
196
1052
|
defs,
|
|
197
|
-
calls
|
|
1053
|
+
calls,
|
|
1054
|
+
routed
|
|
198
1055
|
};
|
|
199
1056
|
}
|
|
1057
|
+
/** How deep the schema's reader follows imports for the constants it reads. */
|
|
1058
|
+
const IMPORT_DEPTH = 8;
|
|
1059
|
+
/** A built module's top-level constants that are literals, by name, as `literalReader` reads them; null when it does not parse. */
|
|
1060
|
+
function moduleConsts(path, files, depth) {
|
|
1061
|
+
let tree;
|
|
1062
|
+
try {
|
|
1063
|
+
tree = parse(files[path], {
|
|
1064
|
+
ecmaVersion: "latest",
|
|
1065
|
+
sourceType: "module"
|
|
1066
|
+
});
|
|
1067
|
+
} catch {
|
|
1068
|
+
return null;
|
|
1069
|
+
}
|
|
1070
|
+
return literalReader(tree, () => {
|
|
1071
|
+
throw new Error("not a literal");
|
|
1072
|
+
}, true, false, {
|
|
1073
|
+
path,
|
|
1074
|
+
files,
|
|
1075
|
+
depth
|
|
1076
|
+
}).consts;
|
|
1077
|
+
}
|
|
200
1078
|
/**
|
|
201
1079
|
* A reader of literal values in a module's parse (the schema's, and a function's `args`): literals,
|
|
202
|
-
* arrays, objects, `v.<shape>(...)`, `defineTable(...).index(...)
|
|
203
|
-
* `const`s of these.
|
|
1080
|
+
* arrays, objects, `v.<shape>(...)`, `defineTable(...).index(...)`, a member of one
|
|
1081
|
+
* (`Status.New`, `VALUES[0]`) and the module's top-level `const`s of these. With `from`, a name
|
|
1082
|
+
* imported from another module of the build is read there too, so `v.literal(Status.New)` reads
|
|
1083
|
+
* an enum of a file the schema imports. Anything else calls `refuse`.
|
|
204
1084
|
*/
|
|
205
|
-
function literalReader(tree, refuse, lenient = false) {
|
|
1085
|
+
function literalReader(tree, refuse, lenient = false, env = false, from) {
|
|
206
1086
|
const consts = /* @__PURE__ */ new Map();
|
|
1087
|
+
const imported = /* @__PURE__ */ new Map();
|
|
1088
|
+
if (from && from.depth < IMPORT_DEPTH) for (const node of tree.body) {
|
|
1089
|
+
if (node.type !== "ImportDeclaration" || typeof node.source?.value !== "string" || !/^\.\.?\//u.test(node.source.value)) continue;
|
|
1090
|
+
const target = joined(dirOf(from.path), node.source.value);
|
|
1091
|
+
if (target === null || !Object.hasOwn(from.files, target)) continue;
|
|
1092
|
+
let read;
|
|
1093
|
+
for (const one of node.specifiers) {
|
|
1094
|
+
const name = one.type === "ImportSpecifier" ? one.imported.name ?? one.imported.value : null;
|
|
1095
|
+
if (name === null) continue;
|
|
1096
|
+
imported.set(one.local.name, () => {
|
|
1097
|
+
read ??= moduleConsts(target, from.files, from.depth + 1);
|
|
1098
|
+
return read?.has(name) ? {
|
|
1099
|
+
found: true,
|
|
1100
|
+
value: read.get(name)
|
|
1101
|
+
} : { found: false };
|
|
1102
|
+
});
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
207
1105
|
const vShapes = v;
|
|
208
1106
|
const value = (node) => {
|
|
209
1107
|
if (!node) return refuse(null);
|
|
210
1108
|
if (node.type === "Identifier" && consts.has(node.name)) return consts.get(node.name);
|
|
1109
|
+
if (env && node.type === "MemberExpression" && !node.computed && !node.optional && node.object.type === "MemberExpression" && !node.object.computed && node.object.object.type === "Identifier" && node.object.object.name === "process" && node.object.property.name === "env") return { env: node.property.name };
|
|
1110
|
+
if (node.type === "Identifier" && imported.has(node.name)) {
|
|
1111
|
+
const got = imported.get(node.name)();
|
|
1112
|
+
if (got.found) return got.value;
|
|
1113
|
+
}
|
|
1114
|
+
if (node.type === "MemberExpression" && !node.optional) {
|
|
1115
|
+
const object = value(node.object);
|
|
1116
|
+
const key = node.computed ? node.property.type === "Literal" && (typeof node.property.value === "string" || typeof node.property.value === "number") ? String(node.property.value) : null : node.property.name;
|
|
1117
|
+
if (key !== null && object !== null && typeof object === "object" && Object.hasOwn(object, key)) return object[key];
|
|
1118
|
+
return refuse(node);
|
|
1119
|
+
}
|
|
211
1120
|
if (node.type === "Literal" && !node.regex && typeof node.value !== "bigint") return node.value;
|
|
212
1121
|
if (node.type === "UnaryExpression" && node.operator === "-" && node.argument.type === "Literal" && typeof node.argument.value === "number") return -node.argument.value;
|
|
213
1122
|
if (node.type === "ArrayExpression" && node.elements.every((e) => e && e.type !== "SpreadElement")) return node.elements.map(value);
|
|
@@ -249,7 +1158,10 @@ function literalReader(tree, refuse, lenient = false) {
|
|
|
249
1158
|
} catch {}
|
|
250
1159
|
}
|
|
251
1160
|
}
|
|
252
|
-
return {
|
|
1161
|
+
return {
|
|
1162
|
+
value,
|
|
1163
|
+
consts
|
|
1164
|
+
};
|
|
253
1165
|
}
|
|
254
1166
|
/** A function's `args` fields and `returns` shape as written, for its types; null where they are not literals. */
|
|
255
1167
|
function signatureOf(tree, call) {
|
|
@@ -282,14 +1194,26 @@ function signatureOf(tree, call) {
|
|
|
282
1194
|
returns: read(prop("returns"))
|
|
283
1195
|
};
|
|
284
1196
|
}
|
|
285
|
-
function schemaOf(file, tree) {
|
|
1197
|
+
function schemaOf(file, tree, path, files) {
|
|
286
1198
|
const refuse = (why, node) => {
|
|
287
1199
|
throw new Refused(`${file}${node?.loc ? `:${node.loc.start.line}` : ""}: ${why}`);
|
|
288
1200
|
};
|
|
289
1201
|
const literal = "the schema is written as literals: defineSchema({ <table>: defineTable({ <field>: v.<shape>(...) }) })";
|
|
1202
|
+
/** What the reader could not read, said as exactly as it can be. */
|
|
1203
|
+
const unread = (node) => {
|
|
1204
|
+
const callee = node?.type === "CallExpression" ? node.callee : null;
|
|
1205
|
+
if (callee?.type === "MemberExpression" && callee.object.type === "Identifier" && callee.object.name === "v" && !callee.computed && !Object.hasOwn(v, callee.property.name)) return refuse(`v.${callee.property.name}() is not a shape. The shapes are ${Object.keys(v).map((name) => `v.${name}()`).join(", ")}`, node);
|
|
1206
|
+
if (node?.type === "Identifier") return refuse(`${node.name} is not a value the schema can read: write it in schema.ts, or as a top-level const (or an enum) of a module schema.ts imports`, node);
|
|
1207
|
+
if (node?.type === "MemberExpression") return refuse("a member the schema can read is of a const or an enum it can read, by one of its own keys", node);
|
|
1208
|
+
return refuse(literal, node);
|
|
1209
|
+
};
|
|
290
1210
|
let value;
|
|
291
1211
|
try {
|
|
292
|
-
({value} = literalReader(tree,
|
|
1212
|
+
({value} = literalReader(tree, unread, false, false, {
|
|
1213
|
+
path,
|
|
1214
|
+
files,
|
|
1215
|
+
depth: 0
|
|
1216
|
+
}));
|
|
293
1217
|
} catch (error) {
|
|
294
1218
|
if (error instanceof Refused) throw error;
|
|
295
1219
|
return refuse(error.message, null);
|
|
@@ -300,36 +1224,136 @@ function schemaOf(file, tree) {
|
|
|
300
1224
|
const built = defineSchema(value(declaration.arguments[0]));
|
|
301
1225
|
return {
|
|
302
1226
|
tables: built.tables,
|
|
303
|
-
indexes: built.indexes
|
|
1227
|
+
indexes: built.indexes,
|
|
1228
|
+
search: built.search,
|
|
1229
|
+
vector: built.vector
|
|
304
1230
|
};
|
|
305
1231
|
} catch (error) {
|
|
306
1232
|
if (error instanceof Refused) throw error;
|
|
307
1233
|
return refuse(error.message, declaration);
|
|
308
1234
|
}
|
|
309
1235
|
}
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
1236
|
+
const CRON_KINDS = /* @__PURE__ */ new Set([
|
|
1237
|
+
"cron",
|
|
1238
|
+
"hourly",
|
|
1239
|
+
"daily",
|
|
1240
|
+
"weekly",
|
|
1241
|
+
"monthly",
|
|
1242
|
+
"interval"
|
|
1243
|
+
]);
|
|
1244
|
+
/**
|
|
1245
|
+
* `crons.ts`'s scheduled runs, read as written: `const crons = cronJobs()`, then top-level calls
|
|
1246
|
+
* such as `crons.daily("name", { hourUTC: 7, minuteUTC: 0 }, internal.data.reset, args)`, then
|
|
1247
|
+
* `export default crons`. Each names a mutation or an action of the build.
|
|
1248
|
+
*/
|
|
1249
|
+
function cronsOf(file, tree, functions) {
|
|
1250
|
+
const refuse = (why, node) => {
|
|
1251
|
+
throw new Refused(`${file}${node?.loc ? `:${node.loc.start.line}` : ""}: ${why}`);
|
|
1252
|
+
};
|
|
1253
|
+
const shape = "const crons = cronJobs(), each run as crons.<daily|hourly|weekly|monthly|interval|cron>(name, schedule, internal.<file>.<function>, args), then export default crons";
|
|
1254
|
+
const made = tree.body.flatMap((n) => n.type === "VariableDeclaration" ? n.declarations : []).find((d) => d.init?.type === "CallExpression" && d.init.callee.type === "Identifier" && d.init.callee.name === "cronJobs");
|
|
1255
|
+
const name = made?.id?.type === "Identifier" ? made.id.name : void 0;
|
|
1256
|
+
const exported = tree.body.find((n) => n.type === "ExportDefaultDeclaration")?.declaration;
|
|
1257
|
+
if (!name || exported?.type !== "Identifier" || exported.name !== name) return refuse(shape, exported ?? made);
|
|
1258
|
+
const { value } = literalReader(tree, (node) => refuse(`a schedule or its arguments are literals: ${shape}`, node), true);
|
|
1259
|
+
const jobs = [];
|
|
1260
|
+
for (const node of nodes(tree)) {
|
|
1261
|
+
if (node.type !== "Identifier" || node.name !== name || node === made.id || node === exported) continue;
|
|
1262
|
+
const call = tree.body.find((top) => top.type === "ExpressionStatement" && top.expression.type === "CallExpression" && top.expression.callee.type === "MemberExpression" && top.expression.callee.object === node)?.expression;
|
|
1263
|
+
if (!call || call.callee.computed || !CRON_KINDS.has(call.callee.property.name) || call.arguments.length < 3 || call.arguments.length > 4) return refuse(shape, node);
|
|
1264
|
+
const [label, schedule, ref, args] = call.arguments;
|
|
1265
|
+
const path = [];
|
|
1266
|
+
let at = ref;
|
|
1267
|
+
while (at?.type === "MemberExpression" && !at.computed) {
|
|
1268
|
+
path.unshift(at.property.name);
|
|
1269
|
+
at = at.object;
|
|
1270
|
+
}
|
|
1271
|
+
if (at?.type !== "Identifier" || !API_NAMES.has(at.name) || !path.length) return refuse(`a run gives its function as internal.<file>.<function> or api.<file>.<function>: ${shape}`, ref);
|
|
1272
|
+
const fn = functions.find((one) => one.name === path.join("."));
|
|
1273
|
+
if (!fn || !["mutation", "action"].includes(kindOf(fn.kind))) refuse(`${at.name}.${path.join(".")} is not a mutation or an action of this folder`, ref);
|
|
1274
|
+
if (label?.type !== "Literal" || typeof label.value !== "string") return refuse(`a run's name is a string: ${shape}`, label);
|
|
1275
|
+
let when;
|
|
1276
|
+
try {
|
|
1277
|
+
when = scheduleOf(call.callee.property.name, value(schedule));
|
|
1278
|
+
} catch (error) {
|
|
1279
|
+
return refuse(error instanceof Refused ? error.message : error.message, schedule);
|
|
1280
|
+
}
|
|
1281
|
+
if (jobs.some((job) => job.name === label.value)) refuse(`"${label.value}" is scheduled twice`, label);
|
|
1282
|
+
jobs.push(Object.freeze({
|
|
1283
|
+
name: label.value,
|
|
1284
|
+
...when,
|
|
1285
|
+
function: fn.name,
|
|
1286
|
+
args: args ? value(args) : {}
|
|
1287
|
+
}));
|
|
1288
|
+
}
|
|
1289
|
+
return jobs;
|
|
1290
|
+
}
|
|
1291
|
+
/** `auth.config.ts`: its default export, literals and `process.env.NAME`, checked as the Database checks it. */
|
|
1292
|
+
function authConfigFrom(file, tree) {
|
|
1293
|
+
const refuse = (why, node) => {
|
|
1294
|
+
throw new Refused(`${file}${node?.loc ? `:${node.loc.start.line}` : ""}: ${why}`);
|
|
1295
|
+
};
|
|
1296
|
+
const literal = "auth.config is written as literals: export default { providers: [{ domain: \"https://...\", applicationID: \"...\" }] }, each value a string or process.env.NAME";
|
|
1297
|
+
let value;
|
|
1298
|
+
try {
|
|
1299
|
+
({value} = literalReader(tree, (node) => refuse(literal, node), false, true));
|
|
1300
|
+
} catch (error) {
|
|
1301
|
+
if (error instanceof Refused) throw error;
|
|
1302
|
+
return refuse(error.message, null);
|
|
1303
|
+
}
|
|
1304
|
+
const declaration = tree.body.find((n) => n.type === "ExportDefaultDeclaration")?.declaration;
|
|
1305
|
+
if (!declaration || /Declaration$/u.test(declaration.type)) return refuse("auth.config is `export default { providers: [...] }`", declaration ?? null);
|
|
1306
|
+
const read = value(declaration);
|
|
1307
|
+
try {
|
|
1308
|
+
return authConfigOf(read);
|
|
1309
|
+
} catch (error) {
|
|
1310
|
+
return refuse(error.message, declaration);
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
/**
|
|
1314
|
+
* Builds a `db/` folder's sources: `{ <path>: text }`, every source at any depth, by its path in the
|
|
1315
|
+
* folder. Without `packages` an import of a package or of a file outside the folder is refused.
|
|
1316
|
+
*
|
|
1317
|
+
* A build's own `files` build again to the same files: what a deploy uploads, and what the Database
|
|
1318
|
+
* checks, is the build. Throws `Refused`.
|
|
1319
|
+
*/
|
|
1320
|
+
function buildDatabase(sources, strip, options = {}) {
|
|
1321
|
+
const { files, from, inputs } = linkAll(stripSources(sources, strip), options.packages, strip);
|
|
315
1322
|
const functions = [];
|
|
316
1323
|
const defined = /* @__PURE__ */ new Map();
|
|
317
|
-
let tables = null, indexes = null;
|
|
318
|
-
|
|
1324
|
+
let tables = null, indexes = null, search = null, vector = null, http = null, auth = null;
|
|
1325
|
+
let cronTree = null;
|
|
1326
|
+
for (const file of Object.keys(files)) {
|
|
319
1327
|
const author = from[file];
|
|
320
|
-
const tree = inspect(author, files[file],
|
|
321
|
-
|
|
322
|
-
|
|
1328
|
+
const tree = inspect(author, file, files[file], files);
|
|
1329
|
+
if (file.startsWith("node_modules/") && !file.startsWith(`${PROJECT}/`)) continue;
|
|
1330
|
+
const { defs, calls, routed } = definersOf(tree, file.replace(/\.mjs$/u, "").replaceAll("/", "."));
|
|
1331
|
+
if (file.startsWith(`${PROJECT}/`)) {
|
|
1332
|
+
if (calls) throw new Refused(`${author}: a function is defined in db/, never in a file outside it`);
|
|
1333
|
+
continue;
|
|
1334
|
+
}
|
|
1335
|
+
if (calls !== defs.length + routed) throw new Refused(`${author}: a function defined outside a top-level export (\`export const send = mutation({ ... })\`) or a route's handler`);
|
|
323
1336
|
for (const def of defs) {
|
|
1337
|
+
if (def.name && def.name.split(".").length > FUNCTION_DEPTH) throw new Refused(`${author}: a function's name has at most ${FUNCTION_DEPTH} parts, its folders, its file and its export (${def.name})`);
|
|
324
1338
|
if (def.named) throw new Refused(`${author}: export const ${def.export} = ${def.kind}({ ... }): its name is the export's (${def.name}), so the definer takes none`);
|
|
325
|
-
if (!def.name || !def.name.split(".").every((part) => FUNCTION_NAME.test(part))) throw new Refused(`${author}: a function's name: [A-Za-z][A-Za-z0-9_]{0,63}, or <file>.<export> with
|
|
1339
|
+
if (!def.name || !def.name.split(".").every((part) => FUNCTION_NAME.test(part))) throw new Refused(`${author}: a function's name: [A-Za-z][A-Za-z0-9_]{0,63}, or <folder>.<file>.<export> with each so (${JSON.stringify(def.name)})`);
|
|
326
1340
|
if (defined.has(def.name)) throw new Refused(`${author}: the name "${def.name}" is also defined by ${defined.get(def.name)}`);
|
|
327
1341
|
defined.set(def.name, author);
|
|
328
1342
|
}
|
|
329
|
-
|
|
330
|
-
if (
|
|
331
|
-
|
|
332
|
-
|
|
1343
|
+
if (file === SCHEMA_FILE) ({tables, indexes, search, vector} = schemaOf(author, tree, file, files));
|
|
1344
|
+
if (file === CRONS_FILE) cronTree = {
|
|
1345
|
+
author,
|
|
1346
|
+
tree
|
|
1347
|
+
};
|
|
1348
|
+
if (file === HTTP_FILE) {
|
|
1349
|
+
if (!tree.body.some((n) => n.type === "ExportDefaultDeclaration")) throw new Refused(`${author}: its default export is the HTTP router (\`const http = httpRouter()\`, its routes, \`export default http\`)`);
|
|
1350
|
+
http = file;
|
|
1351
|
+
}
|
|
1352
|
+
if (file === AUTH_FILE) {
|
|
1353
|
+
if (defs.length) throw new Refused(`${author}: defines functions; auth.config.ts says only whom the Database trusts`);
|
|
1354
|
+
auth = authConfigFrom(author, tree);
|
|
1355
|
+
}
|
|
1356
|
+
for (const def of defs) if (def.kind !== "httpAction") functions.push({
|
|
333
1357
|
name: def.name,
|
|
334
1358
|
kind: def.kind,
|
|
335
1359
|
file,
|
|
@@ -337,37 +1361,69 @@ function buildDatabase(sources, strip) {
|
|
|
337
1361
|
...signatureOf(tree, def.call)
|
|
338
1362
|
});
|
|
339
1363
|
}
|
|
1364
|
+
const ahead = options.ahead ? null : aheadOfTheDatabase(tables, search, vector);
|
|
1365
|
+
if (ahead) throw new Refused(`${from[SCHEMA_FILE] ?? "schema.ts"}: ${ahead}`);
|
|
1366
|
+
const crons = cronTree ? cronsOf(cronTree.author, cronTree.tree, functions) : [];
|
|
340
1367
|
return {
|
|
341
1368
|
files,
|
|
342
1369
|
from,
|
|
1370
|
+
inputs,
|
|
343
1371
|
functions,
|
|
344
1372
|
tables,
|
|
345
1373
|
indexes,
|
|
346
|
-
|
|
1374
|
+
search,
|
|
1375
|
+
vector,
|
|
1376
|
+
http,
|
|
1377
|
+
auth,
|
|
1378
|
+
crons,
|
|
1379
|
+
generated: generatedOf(functions, tables, indexes, search, vector, from)
|
|
347
1380
|
};
|
|
348
1381
|
}
|
|
1382
|
+
/**
|
|
1383
|
+
* What a schema declares that the Database doesn't serve yet, or null: a vector index, a search field
|
|
1384
|
+
* inside an object, a filter field other than a top-level string, number or boolean field, and a staged
|
|
1385
|
+
* search index. A build for `db dev` or a deploy refuses these,
|
|
1386
|
+
* so a schema that builds is one the Database takes. The Stand-in serves them for the engine's work to
|
|
1387
|
+
* come, only when built with `ahead`.
|
|
1388
|
+
*/
|
|
1389
|
+
function aheadOfTheDatabase(tables, search, vector) {
|
|
1390
|
+
for (const [table, declared] of Object.entries(vector ?? {})) for (const name of Object.keys(declared)) return `${table}.vectorIndex("${name}"): the Database doesn't serve vector indexes yet`;
|
|
1391
|
+
for (const [table, declared] of Object.entries(search ?? {})) for (const [name, index] of Object.entries(declared)) {
|
|
1392
|
+
if (index.staged) return `${table}.searchIndex("${name}"): the Database doesn't take staged search indexes yet`;
|
|
1393
|
+
if (index.field.includes(".")) return `${table}.searchIndex("${name}"): the Database searches a top-level field for now, not ${index.field}`;
|
|
1394
|
+
for (const field of index.filters) if (field.includes(".") || !orderable(tables?.[table]?.[field])) return `${table}.searchIndex("${name}"): the Database filters on top-level string, number or boolean fields for now, not ${field}`;
|
|
1395
|
+
}
|
|
1396
|
+
return null;
|
|
1397
|
+
}
|
|
349
1398
|
const HEAD = "// Generated by `midsummer db dev` from this folder. Do not edit.";
|
|
350
1399
|
const kindOf = (kind) => kind.replace(/^internal/u, "").toLowerCase();
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
const
|
|
354
|
-
const
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
const
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
if (
|
|
364
|
-
|
|
1400
|
+
function nestOf(functions, refOf) {
|
|
1401
|
+
const top = /* @__PURE__ */ new Map();
|
|
1402
|
+
for (const fn of functions) {
|
|
1403
|
+
const parts = fn.name.split(".");
|
|
1404
|
+
let level = top;
|
|
1405
|
+
for (const [i, part] of parts.entries()) {
|
|
1406
|
+
const had = level.get(part);
|
|
1407
|
+
if (i === parts.length - 1 ? had : had?.ref) throw new Refused(`${fn.file}: "${parts.slice(0, i + 1).join(".")}" names both a function and a file or folder of functions`);
|
|
1408
|
+
if (i === parts.length - 1) {
|
|
1409
|
+
level.set(part, { ref: refOf(fn) });
|
|
1410
|
+
break;
|
|
1411
|
+
}
|
|
1412
|
+
if (!had) level.set(part, { group: /* @__PURE__ */ new Map() });
|
|
1413
|
+
level = level.get(part).group;
|
|
365
1414
|
}
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
1415
|
+
}
|
|
1416
|
+
return top;
|
|
1417
|
+
}
|
|
1418
|
+
/** The function references, nested by folder and file: `api.messages.send`; `internal` has the internal functions alike. */
|
|
1419
|
+
function referencesOf(functions) {
|
|
1420
|
+
const refOf = (fn) => ({
|
|
1421
|
+
name: fn.name,
|
|
1422
|
+
kind: kindOf(fn.kind)
|
|
1423
|
+
});
|
|
1424
|
+
nestOf(functions, refOf);
|
|
1425
|
+
const js = (level) => `Object.freeze({ ${[...level].map(([key, x]) => `${key}: ${x.ref ? `Object.freeze(${JSON.stringify(x.ref)})` : js(x.group)}`).join(", ")} })`;
|
|
1426
|
+
return [`export const api = ${js(nestOf(functions.filter((fn) => !fn.kind.startsWith("internal")), refOf))};`, `export const internal = ${js(nestOf(functions.filter((fn) => fn.kind.startsWith("internal")), refOf))};`];
|
|
371
1427
|
}
|
|
372
1428
|
/** A shape as a TypeScript type. */
|
|
373
1429
|
function typeOf(shape) {
|
|
@@ -378,7 +1434,7 @@ function typeOf(shape) {
|
|
|
378
1434
|
boolean: "boolean",
|
|
379
1435
|
document: "unknown",
|
|
380
1436
|
int64: "number | string",
|
|
381
|
-
bytes: "
|
|
1437
|
+
bytes: "ArrayBuffer",
|
|
382
1438
|
timestamp: "number",
|
|
383
1439
|
decimal: "string"
|
|
384
1440
|
}[shape] ?? "unknown";
|
|
@@ -392,58 +1448,79 @@ function typeOf(shape) {
|
|
|
392
1448
|
return "unknown";
|
|
393
1449
|
}
|
|
394
1450
|
const fieldsType = (fields) => typeOf({ object: fields ?? {} });
|
|
395
|
-
|
|
1451
|
+
const unionOf = (names) => names.map((name) => JSON.stringify(name)).join(" | ") || "never";
|
|
1452
|
+
function dataModelOf(tables, indexes, search, vector) {
|
|
396
1453
|
const names = Object.keys(tables ?? {});
|
|
1454
|
+
const searchOf = (name) => Object.entries(search?.[name] ?? {}).map(([index, declared]) => `${JSON.stringify(index)}: { searchField: ${JSON.stringify(declared.field)}; filterFields: ${unionOf(declared.filters)} }`).join("; ");
|
|
1455
|
+
const vectorOf = (name) => Object.entries(vector?.[name] ?? {}).map(([index, declared]) => `${JSON.stringify(index)}: { vectorField: ${JSON.stringify(declared.field)}; dimensions: ${declared.dimensions}; filterFields: ${unionOf(declared.filters)} }`).join("; ");
|
|
397
1456
|
if (!names.length) return [
|
|
398
1457
|
HEAD,
|
|
399
1458
|
"export type TableNames = string;",
|
|
400
1459
|
"export type Id<T extends TableNames = TableNames> = string & { readonly __table?: T };",
|
|
401
|
-
"export interface DataModel { [table: string]: { document: { _id: Id; _version: number; [field: string]: any }; indexes: Record<string, string[]> } }",
|
|
1460
|
+
"export interface DataModel { [table: string]: { document: { _id: Id; _version: number; _creationTime: number; [field: string]: any }; indexes: Record<string, string[]>; searchIndexes: Record<string, { searchField: string; filterFields: string }>; vectorIndexes: Record<string, { vectorField: string; dimensions: number; filterFields: string }> } }",
|
|
402
1461
|
"export type Doc<T extends TableNames> = DataModel[T][\"document\"];",
|
|
403
1462
|
""
|
|
404
1463
|
].join("\n");
|
|
405
1464
|
return [
|
|
406
1465
|
HEAD,
|
|
407
1466
|
`export type TableNames = ${names.map((name) => JSON.stringify(name)).join(" | ")};`,
|
|
408
|
-
"/** A document's id: a string that identifies its table. */",
|
|
409
|
-
"export type Id<T extends TableNames> = string & { readonly __table: T };",
|
|
1467
|
+
"/** A document's id: a string that identifies its table; `Id<\"_storage\">` is a stored file's. */",
|
|
1468
|
+
"export type Id<T extends TableNames | \"_storage\"> = string & { readonly __table: T };",
|
|
410
1469
|
"export interface DataModel {",
|
|
411
|
-
...names.map((name) => ` ${JSON.stringify(name)}: { document: { _id: Id<${JSON.stringify(name)}>; _version: number } & ${typeOf({ object: tables[name] })}; indexes: { ${Object.entries(indexes?.[name] ?? {}).map(([index, fields]) => `${JSON.stringify(index)}: ${JSON.stringify(indexFields(fields))}`).join("; ")} } };`),
|
|
1470
|
+
...names.map((name) => ` ${JSON.stringify(name)}: { document: { _id: Id<${JSON.stringify(name)}>; _version: number; _creationTime: number } & ${typeOf({ object: tables[name] })}; indexes: { ${Object.entries(indexes?.[name] ?? {}).map(([index, fields]) => `${JSON.stringify(index)}: ${JSON.stringify(indexFields(fields))}`).join("; ")} }; searchIndexes: { ${searchOf(name)} }; vectorIndexes: { ${vectorOf(name)} } };`),
|
|
412
1471
|
"}",
|
|
413
1472
|
"/** A document of a table, as a read returns it. */",
|
|
414
1473
|
"export type Doc<T extends TableNames> = DataModel[T][\"document\"];",
|
|
415
1474
|
""
|
|
416
1475
|
].join("\n");
|
|
417
1476
|
}
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
1477
|
+
/**
|
|
1478
|
+
* `api.d.ts`: each reference typed by its function as TypeScript infers it, from the module that
|
|
1479
|
+
* exports it (`typeof tasks.list`), so arguments built from shared validators and answers inferred
|
|
1480
|
+
* from handlers keep their types, and a function with no `args` takes `{}`. A module written in
|
|
1481
|
+
* JavaScript, or a function typed by `@midsummer-ai/sdk/server` itself, is typed from its `args`
|
|
1482
|
+
* and `returns` as written.
|
|
1483
|
+
*/
|
|
1484
|
+
function apiTypesOf(functions, from) {
|
|
1485
|
+
const modules = /* @__PURE__ */ new Map();
|
|
1486
|
+
for (const fn of functions) {
|
|
1487
|
+
const author = from[fn.file] ?? "";
|
|
1488
|
+
if (!/\.m?ts$/u.test(author) || modules.has(fn.file)) continue;
|
|
1489
|
+
modules.set(fn.file, `m${modules.size}`);
|
|
1490
|
+
}
|
|
1491
|
+
const refOf = (fn) => {
|
|
1492
|
+
const written = `FunctionReference<${JSON.stringify(kindOf(fn.kind))}, ${fn.args ? fieldsType(fn.args) : "any"}, ${fn.returns ? typeOf(fn.returns) : "any"}>`;
|
|
1493
|
+
const module = modules.get(fn.file);
|
|
1494
|
+
return module ? `Inferred<${JSON.stringify(kindOf(fn.kind))}, typeof ${module}${/^[A-Za-z_$][\w$]*$/u.test(fn.export) ? `.${fn.export}` : `[${JSON.stringify(fn.export)}]`}, ${written}>` : written;
|
|
428
1495
|
};
|
|
1496
|
+
const types = (level) => `{ ${[...level].map(([key, x]) => `readonly ${key}: ${x.ref ?? types(x.group)};`).join(" ")} }`;
|
|
1497
|
+
const tree = (list) => types(nestOf(list, refOf));
|
|
1498
|
+
const imports = [...modules].map(([file, name]) => {
|
|
1499
|
+
const author = from[file];
|
|
1500
|
+
return `import type * as ${name} from ${JSON.stringify(`../${author.endsWith(".mts") ? author.replace(/\.mts$/u, ".mjs") : author.replace(/\.ts$/u, "")}`)};`;
|
|
1501
|
+
});
|
|
429
1502
|
return [
|
|
430
1503
|
HEAD,
|
|
431
|
-
"import type { FunctionReference } from \"./server\";",
|
|
1504
|
+
"import type { FunctionReference, RegisteredFunction } from \"./server\";",
|
|
1505
|
+
"import type { Id } from \"./dataModel\";",
|
|
432
1506
|
"export type { FunctionReference } from \"./server\";",
|
|
1507
|
+
...imports,
|
|
1508
|
+
"/** A function's reference as its definition types it; `W`, typed from its `args` and `returns` as written, when its definition says nothing. */",
|
|
1509
|
+
"type Inferred<K extends \"query\" | \"mutation\" | \"action\", F, W> = F extends RegisteredFunction<any, infer A, infer R> ? (unknown extends A ? W : FunctionReference<K, A, Awaited<R>>) : W;",
|
|
433
1510
|
`export declare const api: ${tree(functions.filter((fn) => !fn.kind.startsWith("internal")))};`,
|
|
434
1511
|
`export declare const internal: ${tree(functions.filter((fn) => fn.kind.startsWith("internal")))};`,
|
|
435
1512
|
""
|
|
436
1513
|
].join("\n");
|
|
437
1514
|
}
|
|
438
|
-
function generatedOf(functions, tables, indexes) {
|
|
1515
|
+
function generatedOf(functions, tables, indexes, search, vector, from) {
|
|
439
1516
|
return {
|
|
440
1517
|
"api.mjs": [
|
|
441
1518
|
`${HEAD} A function's reference for the client: \`db.mutation(api.messages.send, args)\`.`,
|
|
442
1519
|
...referencesOf(functions),
|
|
443
1520
|
""
|
|
444
1521
|
].join("\n"),
|
|
445
|
-
"api.d.ts": apiTypesOf(functions),
|
|
446
|
-
"dataModel.d.ts": dataModelOf(tables, indexes),
|
|
1522
|
+
"api.d.ts": apiTypesOf(functions, from),
|
|
1523
|
+
"dataModel.d.ts": dataModelOf(tables, indexes, search, vector),
|
|
447
1524
|
"server.d.ts": SERVER_TYPES
|
|
448
1525
|
};
|
|
449
1526
|
}
|
|
@@ -452,6 +1529,8 @@ const SERVER_TYPES = `${HEAD} What "@midsummer-ai/sdk/server" gives, typed by th
|
|
|
452
1529
|
// Database's schema: its tables, documents and function references.
|
|
453
1530
|
import type { DataModel, Doc, Id, TableNames } from "./dataModel";
|
|
454
1531
|
export type { DataModel, Doc, Id, TableNames } from "./dataModel";
|
|
1532
|
+
/** A stored file's id, as \`ctx.storage\` returns and takes it. */
|
|
1533
|
+
export type StorageId = Id<"_storage">;
|
|
455
1534
|
|
|
456
1535
|
/** A field type. \`T\` is the value's type; \`O\` whether the field may be left out. */
|
|
457
1536
|
export interface Validator<T, O extends boolean = false> {
|
|
@@ -474,13 +1553,19 @@ export declare const v: {
|
|
|
474
1553
|
boolean(): Required<boolean>;
|
|
475
1554
|
/** Any JSON value, at any depth. */
|
|
476
1555
|
document(): Required<unknown>;
|
|
477
|
-
|
|
1556
|
+
/** Any value, as Convex's \`v.any()\`. */
|
|
1557
|
+
any(): Required<any>;
|
|
1558
|
+
/** Only null: \`v.union(v.string(), v.null())\` is a string or null. */
|
|
1559
|
+
null(): Required<null>;
|
|
1560
|
+
/** A row's id, or \`v.id("_storage")\`: a stored file's. */
|
|
1561
|
+
id<T extends TableNames | "_storage">(table: T): Required<Id<T>>;
|
|
478
1562
|
array<V extends Validator<any, boolean>>(of: V): Required<Infer<V>[]>;
|
|
479
1563
|
object<F extends Fields>(fields: F): Required<DocOf<F>>;
|
|
480
1564
|
/** May be left out or null. */
|
|
481
1565
|
optional<V extends Validator<any, boolean>>(inner: V): Validator<Infer<V> | null, true>;
|
|
482
1566
|
int64(): Validator<number | string>;
|
|
483
|
-
|
|
1567
|
+
/** Bytes: an ArrayBuffer to every caller and in every function, as an argument or a document's field. */
|
|
1568
|
+
bytes(): Validator<ArrayBuffer>;
|
|
484
1569
|
timestamp(): Validator<number>;
|
|
485
1570
|
decimal(): Validator<string>;
|
|
486
1571
|
literal<L extends string | number | boolean>(value: L): Validator<L>;
|
|
@@ -501,13 +1586,13 @@ export type Patch<D> = { [K in keyof D]?: D[K] | (D[K] extends number ? Operator
|
|
|
501
1586
|
|
|
502
1587
|
// ---- The tables a function reads and writes: \`ctx.db.<table>\` ----
|
|
503
1588
|
|
|
504
|
-
type Value<T extends TableNames> = Omit<Doc<T>, "_id" | "_version">;
|
|
505
|
-
/**
|
|
1589
|
+
type Value<T extends TableNames> = Omit<Doc<T>, "_id" | "_version" | "_creationTime">;
|
|
1590
|
+
/** Equality accepts a scalar or a list of prefix values. Bounds apply to the next field; order and limit apply to the result. */
|
|
506
1591
|
export interface RangeOptions { eq?: unknown; gte?: unknown; gt?: unknown; lte?: unknown; lt?: unknown; order?: "asc" | "desc"; limit?: number }
|
|
507
1592
|
export interface Reader<T extends TableNames> {
|
|
508
1593
|
get(id: Id<T>): Doc<T> | null;
|
|
509
1594
|
/** The rows of an index (\`""\`: by id) within the bounds, in its order. */
|
|
510
|
-
range(index: keyof DataModel[T]["indexes"] | "", field: string, options?: RangeOptions): { ok: true; rows: Doc<T>[] };
|
|
1595
|
+
range(index: keyof DataModel[T]["indexes"] | "" | "by_id" | "by_creation_time", field: string, options?: RangeOptions): { ok: true; rows: Doc<T>[] };
|
|
511
1596
|
}
|
|
512
1597
|
export interface Writer<T extends TableNames> extends Reader<T> {
|
|
513
1598
|
/** Its id at once, usable anywhere in the same mutation. */
|
|
@@ -516,35 +1601,196 @@ export interface Writer<T extends TableNames> extends Reader<T> {
|
|
|
516
1601
|
replace(id: Id<T>, doc: Value<T>): void;
|
|
517
1602
|
delete(id: Id<T>): void;
|
|
518
1603
|
}
|
|
519
|
-
|
|
520
|
-
|
|
1604
|
+
/** The number of documents to read and the cursor from the previous page, or null to start. With \`endCursor\`, every document up to where that cursor ended instead, as reactive pagination keeps a loaded page. */
|
|
1605
|
+
export interface PaginationOptions { numItems: number; cursor: string | null; endCursor?: string | null; id?: number; maximumRowsRead?: number; maximumBytesRead?: number }
|
|
1606
|
+
/** Convex's \`paginationOptsValidator\`: a paginated query's \`paginationOpts\` argument. */
|
|
1607
|
+
export declare const paginationOptsValidator: Required<PaginationOptions>;
|
|
1608
|
+
/** A page in index order, with a cursor that can be passed to the same query. */
|
|
1609
|
+
export interface PaginationResult<D> { page: D[]; isDone: boolean; continueCursor: string }
|
|
1610
|
+
type IndexName<T extends TableNames> = keyof DataModel[T]["indexes"] & string | "by_id" | "by_creation_time";
|
|
1611
|
+
type IndexFields<T extends TableNames, I extends IndexName<T>> = I extends "by_id" ? ["_id"] : I extends "by_creation_time" ? ["_creationTime", "_id"] : I extends keyof DataModel[T]["indexes"] ? DataModel[T]["indexes"][I] extends infer F extends string[] ? [...F, "_creationTime", "_id"] : never : never;
|
|
1612
|
+
declare const indexRange: unique symbol;
|
|
1613
|
+
interface IndexRangeResult { readonly [indexRange]: true }
|
|
1614
|
+
/** Lower and upper bounds on the next field of an index. */
|
|
1615
|
+
export interface IndexBounds<T extends TableNames, F extends keyof Doc<T> & string> extends IndexRangeResult {
|
|
1616
|
+
gt(field: F, value: Doc<T>[F]): IndexBounds<T, F>;
|
|
1617
|
+
gte(field: F, value: Doc<T>[F]): IndexBounds<T, F>;
|
|
1618
|
+
lt(field: F, value: Doc<T>[F]): IndexBounds<T, F>;
|
|
1619
|
+
lte(field: F, value: Doc<T>[F]): IndexBounds<T, F>;
|
|
1620
|
+
}
|
|
1621
|
+
/** Equality consumes index fields in their declared order. */
|
|
1622
|
+
export type IndexRange<T extends TableNames, F extends string[]> = F extends [infer K extends keyof Doc<T> & string, ...infer Rest extends string[]] ? IndexBounds<T, K> & { eq(field: K, value: Doc<T>[K]): IndexRange<T, Rest> } : IndexRangeResult;
|
|
1623
|
+
/** A query in index order. Terminals read only the documents they need; \`for await\` reads it a chunk at a time. */
|
|
1624
|
+
export interface QueryBuilder<T extends TableNames> extends AsyncIterable<Doc<T>> {
|
|
1625
|
+
withIndex<I extends IndexName<T>>(index: I, range?: (q: IndexRange<T, IndexFields<T, I>>) => IndexRangeResult): QueryBuilder<T>;
|
|
1626
|
+
order(order: "asc" | "desc"): QueryBuilder<T>;
|
|
1627
|
+
/** Only the documents the predicate is true for, applied before a terminal counts them: a page has \`numItems\` that pass. */
|
|
1628
|
+
filter(predicate: (q: FilterBuilder<T>) => ExpressionOrValue<boolean>): QueryBuilder<T>;
|
|
1629
|
+
take(n: number): Promise<Doc<T>[]>;
|
|
1630
|
+
collect(): Promise<Doc<T>[]>;
|
|
1631
|
+
first(): Promise<Doc<T> | null>;
|
|
1632
|
+
unique(): Promise<Doc<T> | null>;
|
|
1633
|
+
paginate(options: PaginationOptions): Promise<PaginationResult<Doc<T>>>;
|
|
1634
|
+
}
|
|
1635
|
+
/** A stored file as Convex's \`_storage\` system table gives it. */
|
|
1636
|
+
export interface StorageDocument { readonly _id: StorageId; readonly _creationTime: number; readonly sha256: string; readonly size: number; readonly contentType?: string }
|
|
1637
|
+
/** Convex's reads by id: the table is found from the id. Each returns a promise, as Convex's do. */
|
|
1638
|
+
export interface ConvexReader {
|
|
1639
|
+
get<T extends TableNames>(id: Id<T>): Promise<Doc<T> | null>;
|
|
1640
|
+
get<T extends TableNames>(table: T, id: Id<T>): Promise<Doc<T> | null>;
|
|
1641
|
+
/** \`id\` as an id of \`table\`, or null when it is none; for \`"_storage"\`, when no file has it. */
|
|
1642
|
+
normalizeId<T extends TableNames | "_storage">(table: T, id: string): Id<T> | null;
|
|
1643
|
+
readonly system: { get(id: StorageId): Promise<StorageDocument | null> };
|
|
1644
|
+
}
|
|
1645
|
+
/** Convex's writes: the table named first for an insert, and by the id for the rest. Each runs at once and returns a promise. */
|
|
1646
|
+
export interface ConvexWriter extends ConvexReader {
|
|
1647
|
+
insert<T extends TableNames>(table: T, doc: Value<T>): Promise<Id<T>>;
|
|
1648
|
+
patch<T extends TableNames>(id: Id<T>, fields: Patch<Value<T>>): Promise<void>;
|
|
1649
|
+
patch<T extends TableNames>(table: T, id: Id<T>, fields: Patch<Value<T>>): Promise<void>;
|
|
1650
|
+
replace<T extends TableNames>(id: Id<T>, doc: Value<T>): Promise<void>;
|
|
1651
|
+
replace<T extends TableNames>(table: T, id: Id<T>, doc: Value<T>): Promise<void>;
|
|
1652
|
+
delete<T extends TableNames>(id: Id<T>): Promise<void>;
|
|
1653
|
+
delete<T extends TableNames>(table: T, id: Id<T>): Promise<void>;
|
|
1654
|
+
}
|
|
1655
|
+
type Tables<R> = { readonly [T in TableNames]: R extends "write" ? Writer<T> : Reader<T> } & (R extends "write" ? ConvexWriter : ConvexReader) & { table<T extends TableNames>(name: T): R extends "write" ? Writer<T> : Reader<T>; query<T extends TableNames>(name: T): QueryBuilder<T> & QueryStart<T> };
|
|
1656
|
+
/** \`ctx.db\` of a query, as Convex names it. */
|
|
1657
|
+
export type DatabaseReader = Tables<"read">;
|
|
1658
|
+
/** \`ctx.db\` of a mutation, as Convex names it. */
|
|
1659
|
+
export type DatabaseWriter = Tables<"write">;
|
|
1660
|
+
|
|
1661
|
+
// ---- Search: \`ctx.db.query(table).withSearchIndex(...)\` and \`ctx.vectorSearch(...)\` ----
|
|
1662
|
+
|
|
1663
|
+
type SearchIndexes<T extends TableNames> = DataModel[T]["searchIndexes"];
|
|
1664
|
+
type VectorIndexes<T extends TableNames> = DataModel[T]["vectorIndexes"];
|
|
1665
|
+
/** A filter field's value: a top-level field's type, or any value for a path into an object. */
|
|
1666
|
+
type FieldValue<T extends TableNames, F> = F extends keyof Doc<T> ? Doc<T>[F] : unknown;
|
|
1667
|
+
export interface SearchFilter<T extends TableNames, I extends keyof SearchIndexes<T>> {
|
|
1668
|
+
/** The words to find in the index's search field; the last also matches the words it begins. */
|
|
1669
|
+
search(field: SearchIndexes<T>[I]["searchField"], text: string): SearchFilterEq<T, I>;
|
|
1670
|
+
}
|
|
1671
|
+
export interface SearchFilterEq<T extends TableNames, I extends keyof SearchIndexes<T>> {
|
|
1672
|
+
/** Only rows whose filter field holds \`value\` (\`undefined\`: rows without it); every one holds; up to 8. */
|
|
1673
|
+
eq<F extends SearchIndexes<T>[I]["filterFields"]>(field: F, value: FieldValue<T, F>): SearchFilterEq<T, I>;
|
|
1674
|
+
}
|
|
1675
|
+
/** A value, a document's field, or what Convex's filter builder makes of them. */
|
|
1676
|
+
export interface FilterExpression<T> { readonly __filter?: T }
|
|
1677
|
+
type ExpressionOrValue<T> = FilterExpression<T> | T;
|
|
1678
|
+
export interface FilterBuilder<T extends TableNames> {
|
|
1679
|
+
field<F extends keyof Doc<T> & string>(name: F): FilterExpression<Doc<T>[F]>;
|
|
1680
|
+
field(name: string): FilterExpression<unknown>;
|
|
1681
|
+
eq<V>(a: ExpressionOrValue<V>, b: ExpressionOrValue<V>): FilterExpression<boolean>;
|
|
1682
|
+
neq<V>(a: ExpressionOrValue<V>, b: ExpressionOrValue<V>): FilterExpression<boolean>;
|
|
1683
|
+
lt<V>(a: ExpressionOrValue<V>, b: ExpressionOrValue<V>): FilterExpression<boolean>;
|
|
1684
|
+
lte<V>(a: ExpressionOrValue<V>, b: ExpressionOrValue<V>): FilterExpression<boolean>;
|
|
1685
|
+
gt<V>(a: ExpressionOrValue<V>, b: ExpressionOrValue<V>): FilterExpression<boolean>;
|
|
1686
|
+
gte<V>(a: ExpressionOrValue<V>, b: ExpressionOrValue<V>): FilterExpression<boolean>;
|
|
1687
|
+
add(a: ExpressionOrValue<number>, b: ExpressionOrValue<number>): FilterExpression<number>;
|
|
1688
|
+
sub(a: ExpressionOrValue<number>, b: ExpressionOrValue<number>): FilterExpression<number>;
|
|
1689
|
+
mul(a: ExpressionOrValue<number>, b: ExpressionOrValue<number>): FilterExpression<number>;
|
|
1690
|
+
div(a: ExpressionOrValue<number>, b: ExpressionOrValue<number>): FilterExpression<number>;
|
|
1691
|
+
mod(a: ExpressionOrValue<number>, b: ExpressionOrValue<number>): FilterExpression<number>;
|
|
1692
|
+
neg(a: ExpressionOrValue<number>): FilterExpression<number>;
|
|
1693
|
+
and(...all: ExpressionOrValue<boolean>[]): FilterExpression<boolean>;
|
|
1694
|
+
or(...any: ExpressionOrValue<boolean>[]): FilterExpression<boolean>;
|
|
1695
|
+
not(a: ExpressionOrValue<boolean>): FilterExpression<boolean>;
|
|
1696
|
+
}
|
|
1697
|
+
/** A search's rows, best first; a page of it reads at most 1,024. */
|
|
1698
|
+
export interface SearchQuery<T extends TableNames> extends AsyncIterable<Doc<T>> {
|
|
1699
|
+
/** Only the rows the predicate holds for. */
|
|
1700
|
+
filter(predicate: (q: FilterBuilder<T>) => ExpressionOrValue<boolean>): SearchQuery<T>;
|
|
1701
|
+
take(n: number): Promise<Doc<T>[]>;
|
|
1702
|
+
first(): Promise<Doc<T> | null>;
|
|
1703
|
+
unique(): Promise<Doc<T> | null>;
|
|
1704
|
+
/** Refused past 1,024 rows: take or paginate. */
|
|
1705
|
+
collect(): Promise<Doc<T>[]>;
|
|
1706
|
+
paginate(options: PaginationOptions): Promise<{ page: Doc<T>[]; isDone: boolean; continueCursor: string }>;
|
|
1707
|
+
}
|
|
1708
|
+
export interface QueryStart<T extends TableNames> {
|
|
1709
|
+
withSearchIndex<I extends keyof SearchIndexes<T> & string>(index: I, search: (q: SearchFilter<T, I>) => SearchFilterEq<T, I>): SearchQuery<T>;
|
|
1710
|
+
}
|
|
1711
|
+
export interface VectorFilterExpression { readonly __vectorFilter?: true }
|
|
1712
|
+
export interface VectorFilterBuilder<T extends TableNames, I extends keyof VectorIndexes<T>> {
|
|
1713
|
+
/** Rows whose filter field holds \`value\` (\`undefined\`: rows without it). */
|
|
1714
|
+
eq<F extends VectorIndexes<T>[I]["filterFields"]>(field: F, value: FieldValue<T, F>): VectorFilterExpression;
|
|
1715
|
+
/** Rows matching any of them, up to 64 in all; none: no row. */
|
|
1716
|
+
or(...any: VectorFilterExpression[]): VectorFilterExpression;
|
|
1717
|
+
}
|
|
1718
|
+
type AsyncReader<T extends TableNames> = { get(id: Id<T>): Promise<Doc<T> | null>; range(index: keyof DataModel[T]["indexes"] | "" | "by_id" | "by_creation_time", field: string, options?: RangeOptions): Promise<{ ok: true; rows: Doc<T>[] }> };
|
|
521
1719
|
|
|
522
1720
|
// ---- Functions ----
|
|
523
1721
|
|
|
524
1722
|
/** A function's reference (\`api.messages.send\`): its name, kind, arguments and answer. */
|
|
525
1723
|
export interface FunctionReference<Kind extends "query" | "mutation" | "action", Args = any, Returns = any> { readonly name: string; readonly kind: Kind; readonly __args?: Args; readonly __returns?: Returns }
|
|
526
1724
|
type ArgsOf<F> = F extends FunctionReference<any, infer A, any> ? A : never;
|
|
1725
|
+
type ReturnsOf<F> = F extends FunctionReference<any, any, infer R> ? R : never;
|
|
1726
|
+
/** A runner's arguments: left out for a function that needs none, as \`ctx.runQuery(api.notes.mine)\`. */
|
|
1727
|
+
type ArgsFor<F> = {} extends ArgsOf<F> ? [args?: ArgsOf<F>] : [args: ArgsOf<F>];
|
|
527
1728
|
export interface Identity { readonly user: string | null; readonly server: boolean }
|
|
528
|
-
/**
|
|
529
|
-
export
|
|
1729
|
+
/** A signed-in caller, as their sign-in provider's verified token says: the profile claims by these names, and every other claim by its own. */
|
|
1730
|
+
export interface UserIdentity {
|
|
1731
|
+
readonly tokenIdentifier: string; readonly subject: string; readonly issuer: string;
|
|
1732
|
+
readonly name?: string; readonly givenName?: string; readonly familyName?: string; readonly nickname?: string; readonly preferredUsername?: string;
|
|
1733
|
+
readonly profileUrl?: string; readonly pictureUrl?: string; readonly email?: string; readonly emailVerified?: boolean; readonly gender?: string;
|
|
1734
|
+
readonly birthday?: string; readonly timezone?: string; readonly language?: string; readonly phoneNumber?: string; readonly phoneNumberVerified?: boolean;
|
|
1735
|
+
readonly address?: string; readonly updatedAt?: string;
|
|
1736
|
+
readonly [claim: string]: unknown;
|
|
1737
|
+
}
|
|
1738
|
+
/** The caller: \`getUserIdentity()\` gives the signed-in caller, or null for none; \`subject\` and \`issuer\` are a signed-in caller's. */
|
|
1739
|
+
export interface Auth { getUserIdentity(): Promise<UserIdentity | null>; readonly subject?: string; readonly issuer?: string | null }
|
|
530
1740
|
export interface Scheduler {
|
|
531
1741
|
runAfter<F extends FunctionReference<"mutation" | "action">>(ms: number, fn: F, args: ArgsOf<F>): string;
|
|
532
1742
|
runAt<F extends FunctionReference<"mutation" | "action">>(at: number, fn: F, args: ArgsOf<F>): string;
|
|
533
1743
|
status(id: string): { name: string; args: unknown; at: number; state: string; error?: string } | null;
|
|
534
1744
|
cancel(id: string): boolean;
|
|
535
1745
|
}
|
|
1746
|
+
/** What \`ctx.storage.getMetadata\` returns for a stored file. */
|
|
1747
|
+
export interface FileMetadata { storageId: StorageId; sha256: string; size: number; contentType: string | null }
|
|
1748
|
+
/** A query's files: a stored file's URL, which anyone holding it may read, and its metadata; null when there is no such file. */
|
|
1749
|
+
export interface StorageReader { getUrl(id: StorageId): Promise<string | null>; getMetadata(id: StorageId): Promise<FileMetadata | null> }
|
|
1750
|
+
/** A mutation's files: an upload URL and a delete, both made only if the mutation commits. */
|
|
1751
|
+
export interface StorageWriter extends StorageReader {
|
|
1752
|
+
/** A URL that takes one upload within an hour: POST the file with its content type, and it returns \`{ storageId }\`. */
|
|
1753
|
+
generateUploadUrl(): Promise<string>;
|
|
1754
|
+
delete(id: StorageId): Promise<void>;
|
|
1755
|
+
}
|
|
1756
|
+
/** An action's files: stored and read as Blobs, the Blob's type kept as the file's content type. */
|
|
1757
|
+
export interface StorageActionWriter extends StorageWriter {
|
|
1758
|
+
/** \`sha256\`: the bytes' SHA-256 in hex; other bytes are refused and nothing is stored. */
|
|
1759
|
+
store(blob: Blob | ArrayBuffer | Uint8Array, options?: { sha256?: string }): Promise<StorageId>;
|
|
1760
|
+
get(id: StorageId): Promise<Blob | null>;
|
|
1761
|
+
}
|
|
536
1762
|
/** Reads only; run again when anything it read changes. */
|
|
537
|
-
export interface QueryCtx {
|
|
1763
|
+
export interface QueryCtx {
|
|
1764
|
+
readonly db: Tables<"read">; readonly storage: StorageReader; readonly identity: Identity; readonly auth: Auth; readonly now: number;
|
|
1765
|
+
/** Runs a query, internal ones too, in this query's reads. */
|
|
1766
|
+
runQuery<F extends FunctionReference<"query">>(fn: F, ...args: ArgsFor<F>): Promise<ReturnsOf<F>>;
|
|
1767
|
+
}
|
|
538
1768
|
/** One serializable transaction; run again when a row it read changed. */
|
|
539
|
-
export interface MutationCtx {
|
|
1769
|
+
export interface MutationCtx {
|
|
1770
|
+
readonly db: Tables<"write">; readonly storage: StorageWriter; readonly identity: Identity; readonly auth: Auth; readonly now: number; readonly scheduler: Scheduler;
|
|
1771
|
+
/** Runs a query, internal ones too, in this transaction: it sees what this mutation wrote so far. */
|
|
1772
|
+
runQuery<F extends FunctionReference<"query">>(fn: F, ...args: ArgsFor<F>): Promise<ReturnsOf<F>>;
|
|
1773
|
+
/** Runs a mutation, internal ones too, in this transaction: its writes are this mutation's, and a throw undoes only its own. */
|
|
1774
|
+
runMutation<F extends FunctionReference<"mutation">>(fn: F, ...args: ArgsFor<F>): Promise<ReturnsOf<F>>;
|
|
1775
|
+
}
|
|
540
1776
|
/** May wait on the network; its writes are the mutations it runs. */
|
|
541
1777
|
export interface ActionCtx {
|
|
542
1778
|
readonly db: { readonly [T in TableNames]: AsyncReader<T> };
|
|
1779
|
+
readonly storage: StorageActionWriter;
|
|
543
1780
|
readonly identity: Identity;
|
|
544
1781
|
readonly auth: Auth;
|
|
545
|
-
|
|
1782
|
+
/** The whole response: status, headers, \`arrayBuffer()\`, \`body\` as a stream. https only. */
|
|
1783
|
+
fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
|
|
546
1784
|
now(): number; random(bytes?: number): Uint8Array;
|
|
547
|
-
run<F extends FunctionReference<any>>(fn: F, args:
|
|
1785
|
+
run<F extends FunctionReference<any>>(fn: F, ...args: ArgsFor<F>): Promise<ReturnsOf<F>>;
|
|
1786
|
+
/** Runs a query, internal ones too, as a call of its own. */
|
|
1787
|
+
runQuery<F extends FunctionReference<"query">>(fn: F, ...args: ArgsFor<F>): Promise<ReturnsOf<F>>;
|
|
1788
|
+
/** Runs a mutation, internal ones too, as a transaction of its own: kept whatever this action does after. */
|
|
1789
|
+
runMutation<F extends FunctionReference<"mutation">>(fn: F, ...args: ArgsFor<F>): Promise<ReturnsOf<F>>;
|
|
1790
|
+
/** Runs an action, internal ones too, as a call of its own. */
|
|
1791
|
+
runAction<F extends FunctionReference<"action">>(fn: F, ...args: ArgsFor<F>): Promise<ReturnsOf<F>>;
|
|
1792
|
+
/** A vector index's nearest rows, best first: each its id and the cosine of its vector and \`vector\` (1 the closest). \`limit\` 1 to 256, 10 when not given. */
|
|
1793
|
+
vectorSearch<T extends TableNames, I extends keyof VectorIndexes<T> & string>(table: T, index: I, query: { vector: number[]; limit?: number; filter?: (q: VectorFilterBuilder<T, I>) => VectorFilterExpression }): Promise<Array<{ _id: Id<T>; _score: number }>>;
|
|
548
1794
|
readonly scheduler: { runAfter<F extends FunctionReference<"mutation" | "action">>(ms: number, fn: F, args: ArgsOf<F>): Promise<string>; runAt<F extends FunctionReference<"mutation" | "action">>(at: number, fn: F, args: ArgsOf<F>): Promise<string>; status(id: string): Promise<unknown>; cancel(id: string): Promise<boolean> };
|
|
549
1795
|
}
|
|
550
1796
|
type ArgsFrom<A> = A extends Fields ? DocOf<A> : Record<string, never>;
|
|
@@ -559,6 +1805,41 @@ export declare function internalMutation<A extends Fields = {}, R = any>(definit
|
|
|
559
1805
|
export declare function action<A extends Fields = {}, R = any>(definition: Definition<ActionCtx, A, R> & Scheduled): RegisteredFunction<"action", ArgsFrom<A>, R>;
|
|
560
1806
|
export declare function internalAction<A extends Fields = {}, R = any>(definition: Definition<ActionCtx, A, R> & Scheduled): RegisteredFunction<"action", ArgsFrom<A>, R>;
|
|
561
1807
|
|
|
1808
|
+
// ---- HTTP actions: \`http.ts\`'s router ----
|
|
1809
|
+
|
|
1810
|
+
export interface HttpAction { readonly __http?: true }
|
|
1811
|
+
/** Reached through a route; anyone may call it, so it checks its own callers. */
|
|
1812
|
+
export declare function httpAction(handler: (ctx: ActionCtx, request: Request) => Response | Promise<Response>): HttpAction;
|
|
1813
|
+
/** A HEAD request takes a GET route. */
|
|
1814
|
+
export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS";
|
|
1815
|
+
/** An exact \`path\`, or every path under a \`pathPrefix\` that ends in "/". */
|
|
1816
|
+
export type HttpRoute = ({ path: string; pathPrefix?: never } | { pathPrefix: string; path?: never }) & { method: HttpMethod; handler: HttpAction };
|
|
1817
|
+
export interface HttpRouter {
|
|
1818
|
+
readonly isRouter: true;
|
|
1819
|
+
route(route: HttpRoute): void;
|
|
1820
|
+
/** Each route as \`[path, method, handler]\`, a prefix's path ending in \`*\`. */
|
|
1821
|
+
getRoutes(): ReadonlyArray<readonly [string, HttpMethod, HttpAction]>;
|
|
1822
|
+
/** \`[handler, method, path]\`: an exact path first, then the longest prefix; HEAD takes a GET route. */
|
|
1823
|
+
lookup(path: string, method: HttpMethod | "HEAD"): readonly [HttpAction, HttpMethod, string] | null;
|
|
1824
|
+
}
|
|
1825
|
+
/** \`const http = httpRouter()\`, its routes, then \`export default http\` in \`http.ts\`. */
|
|
1826
|
+
export declare function httpRouter(): HttpRouter;
|
|
1827
|
+
|
|
1828
|
+
// ---- Scheduled runs: \`crons.ts\` ----
|
|
1829
|
+
|
|
1830
|
+
type Scheduling = FunctionReference<"mutation" | "action">;
|
|
1831
|
+
/** \`crons.ts\`'s default export. Times are UTC; an interval divides an hour in minutes or a day in hours. */
|
|
1832
|
+
export interface Crons {
|
|
1833
|
+
cron<F extends Scheduling>(name: string, cron: string, fn: F, ...args: ArgsFor<F>): void;
|
|
1834
|
+
hourly<F extends Scheduling>(name: string, schedule: { minuteUTC: number }, fn: F, ...args: ArgsFor<F>): void;
|
|
1835
|
+
daily<F extends Scheduling>(name: string, schedule: { hourUTC: number; minuteUTC: number }, fn: F, ...args: ArgsFor<F>): void;
|
|
1836
|
+
weekly<F extends Scheduling>(name: string, schedule: { dayOfWeek: "sunday" | "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday"; hourUTC: number; minuteUTC: number }, fn: F, ...args: ArgsFor<F>): void;
|
|
1837
|
+
monthly<F extends Scheduling>(name: string, schedule: { day: number; hourUTC: number; minuteUTC: number }, fn: F, ...args: ArgsFor<F>): void;
|
|
1838
|
+
interval<F extends Scheduling>(name: string, schedule: { seconds: number } | { minutes: number } | { hours: number }, fn: F, ...args: ArgsFor<F>): void;
|
|
1839
|
+
}
|
|
1840
|
+
/** \`const crons = cronJobs()\`, its runs, then \`export default crons\` in \`crons.ts\`. */
|
|
1841
|
+
export declare function cronJobs(): Crons;
|
|
1842
|
+
|
|
562
1843
|
// ---- Errors ----
|
|
563
1844
|
|
|
564
1845
|
/** A \`take\` asked for more than the field holds: the mutation wrote nothing. */
|
|
@@ -571,9 +1852,15 @@ export declare class NotFoundError extends Error { readonly detail: { table: str
|
|
|
571
1852
|
export interface TableDefinition<F extends Fields> {
|
|
572
1853
|
/** One field, or a list for a compound index; \`{ unique: true }\`: no two rows may share its key. */
|
|
573
1854
|
index(name: string, field: (keyof F & string) | ReadonlyArray<keyof F & string>, options?: { unique?: boolean }): TableDefinition<F>;
|
|
1855
|
+
/** Up to 4 a table: a string field's words, best first, with up to 16 fields a search may match exactly; \`staged\`: serving no search yet. */
|
|
1856
|
+
searchIndex(name: string, options: { searchField: FieldPath<F>; filterFields?: ReadonlyArray<FieldPath<F>>; staged?: boolean }): TableDefinition<F>;
|
|
1857
|
+
/** Up to 4 a table: a \`v.array(v.number())\` field of \`dimensions\` numbers (2 to 4,096), with up to 16 filter fields; \`staged\`: serving no search yet. */
|
|
1858
|
+
vectorIndex(name: string, options: { vectorField: FieldPath<F>; dimensions: number; filterFields?: ReadonlyArray<FieldPath<F>>; staged?: boolean }): TableDefinition<F>;
|
|
574
1859
|
}
|
|
1860
|
+
/** A field, or a path into an object field (\`"author.id"\`). */
|
|
1861
|
+
type FieldPath<F extends Fields> = (keyof F & string) | \`\${keyof F & string}.\${string}\`;
|
|
575
1862
|
export declare function defineTable<F extends Fields>(fields: F): TableDefinition<F>;
|
|
576
1863
|
export declare function defineSchema<T extends Record<string, TableDefinition<any>>>(tables: T): { tables: T };
|
|
577
1864
|
`;
|
|
578
1865
|
//#endregion
|
|
579
|
-
export { Refused, buildDatabase, isSource, typeOf };
|
|
1866
|
+
export { BUILD_BYTES, BUILD_FILES, MODULE_BYTES, Refused, blockNames, buildDatabase, enumAsObject, exported, isSource, typeOf, unboundCalls };
|