@dapplelight/signet-db 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/README.md +1556 -2
- package/dist/admin.d.ts +266 -0
- package/dist/admin.d.ts.map +1 -0
- package/dist/admin.js +671 -0
- package/dist/admin.js.map +1 -0
- package/dist/agent.d.ts +27 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +117 -0
- package/dist/agent.js.map +1 -0
- package/dist/ai-cache.d.ts +9 -0
- package/dist/ai-cache.d.ts.map +1 -0
- package/dist/ai-cache.js +42 -0
- package/dist/ai-cache.js.map +1 -0
- package/dist/ai-spend.d.ts +91 -0
- package/dist/ai-spend.d.ts.map +1 -0
- package/dist/ai-spend.js +207 -0
- package/dist/ai-spend.js.map +1 -0
- package/dist/analytics-tools.d.ts +7 -0
- package/dist/analytics-tools.d.ts.map +1 -0
- package/dist/analytics-tools.js +110 -0
- package/dist/analytics-tools.js.map +1 -0
- package/dist/analytics.d.ts +92 -0
- package/dist/analytics.d.ts.map +1 -0
- package/dist/analytics.js +275 -0
- package/dist/analytics.js.map +1 -0
- package/dist/charts.d.ts +96 -0
- package/dist/charts.d.ts.map +1 -0
- package/dist/charts.js +457 -0
- package/dist/charts.js.map +1 -0
- package/dist/cipher.d.ts +24 -0
- package/dist/cipher.d.ts.map +1 -0
- package/dist/cipher.js +69 -0
- package/dist/cipher.js.map +1 -0
- package/dist/collab.d.ts +159 -0
- package/dist/collab.d.ts.map +1 -0
- package/dist/collab.js +492 -0
- package/dist/collab.js.map +1 -0
- package/dist/columns/pg.d.ts +6254 -0
- package/dist/columns/pg.d.ts.map +1 -0
- package/dist/columns/pg.js +507 -0
- package/dist/columns/pg.js.map +1 -0
- package/dist/columns/shared.d.ts +2 -0
- package/dist/columns/shared.d.ts.map +1 -0
- package/dist/columns/shared.js +2 -0
- package/dist/columns/shared.js.map +1 -0
- package/dist/columns/sqlite.d.ts +6680 -0
- package/dist/columns/sqlite.d.ts.map +1 -0
- package/dist/columns/sqlite.js +507 -0
- package/dist/columns/sqlite.js.map +1 -0
- package/dist/crypt.d.ts +5 -0
- package/dist/crypt.d.ts.map +1 -0
- package/dist/crypt.js +37 -0
- package/dist/crypt.js.map +1 -0
- package/dist/customers.d.ts +339 -0
- package/dist/customers.d.ts.map +1 -0
- package/dist/customers.js +714 -0
- package/dist/customers.js.map +1 -0
- package/dist/d1.d.ts +6 -0
- package/dist/d1.d.ts.map +1 -0
- package/dist/d1.js +11 -0
- package/dist/d1.js.map +1 -0
- package/dist/db.d.ts +33 -0
- package/dist/db.d.ts.map +1 -0
- package/dist/db.js +28 -0
- package/dist/db.js.map +1 -0
- package/dist/describe.d.ts +37 -0
- package/dist/describe.d.ts.map +1 -0
- package/dist/describe.js +79 -0
- package/dist/describe.js.map +1 -0
- package/dist/entitlement-tools.d.ts +17 -0
- package/dist/entitlement-tools.d.ts.map +1 -0
- package/dist/entitlement-tools.js +226 -0
- package/dist/entitlement-tools.js.map +1 -0
- package/dist/entitlements.d.ts +166 -0
- package/dist/entitlements.d.ts.map +1 -0
- package/dist/entitlements.js +493 -0
- package/dist/entitlements.js.map +1 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +12 -0
- package/dist/errors.js.map +1 -0
- package/dist/experiments.d.ts +97 -0
- package/dist/experiments.d.ts.map +1 -0
- package/dist/experiments.js +253 -0
- package/dist/experiments.js.map +1 -0
- package/dist/flags.d.ts +74 -0
- package/dist/flags.d.ts.map +1 -0
- package/dist/flags.js +127 -0
- package/dist/flags.js.map +1 -0
- package/dist/funnels.d.ts +236 -0
- package/dist/funnels.d.ts.map +1 -0
- package/dist/funnels.js +478 -0
- package/dist/funnels.js.map +1 -0
- package/dist/growth-tools.d.ts +10 -0
- package/dist/growth-tools.d.ts.map +1 -0
- package/dist/growth-tools.js +132 -0
- package/dist/growth-tools.js.map +1 -0
- package/dist/growth.d.ts +168 -0
- package/dist/growth.d.ts.map +1 -0
- package/dist/growth.js +406 -0
- package/dist/growth.js.map +1 -0
- package/dist/id.d.ts +3 -0
- package/dist/id.d.ts.map +1 -0
- package/dist/id.js +32 -0
- package/dist/id.js.map +1 -0
- package/dist/idempotency.d.ts +8 -0
- package/dist/idempotency.d.ts.map +1 -0
- package/dist/idempotency.js +66 -0
- package/dist/idempotency.js.map +1 -0
- package/dist/import.d.ts +33 -0
- package/dist/import.d.ts.map +1 -0
- package/dist/import.js +75 -0
- package/dist/import.js.map +1 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +15 -0
- package/dist/index.js.map +1 -0
- package/dist/migrations/check.d.ts +11 -0
- package/dist/migrations/check.d.ts.map +1 -0
- package/dist/migrations/check.js +68 -0
- package/dist/migrations/check.js.map +1 -0
- package/dist/migrations/cli.d.ts +3 -0
- package/dist/migrations/cli.d.ts.map +1 -0
- package/dist/migrations/cli.js +30 -0
- package/dist/migrations/cli.js.map +1 -0
- package/dist/money.d.ts +16 -0
- package/dist/money.d.ts.map +1 -0
- package/dist/money.js +50 -0
- package/dist/money.js.map +1 -0
- package/dist/offerings.d.ts +133 -0
- package/dist/offerings.d.ts.map +1 -0
- package/dist/offerings.js +337 -0
- package/dist/offerings.js.map +1 -0
- package/dist/orgs.d.ts +144 -0
- package/dist/orgs.d.ts.map +1 -0
- package/dist/orgs.js +536 -0
- package/dist/orgs.js.map +1 -0
- package/dist/outbox.d.ts +23 -0
- package/dist/outbox.d.ts.map +1 -0
- package/dist/outbox.js +60 -0
- package/dist/outbox.js.map +1 -0
- package/dist/postgres.d.ts +7 -0
- package/dist/postgres.d.ts.map +1 -0
- package/dist/postgres.js +9 -0
- package/dist/postgres.js.map +1 -0
- package/dist/pricing.d.ts +79 -0
- package/dist/pricing.d.ts.map +1 -0
- package/dist/pricing.js +208 -0
- package/dist/pricing.js.map +1 -0
- package/dist/privacy-tools.d.ts +9 -0
- package/dist/privacy-tools.d.ts.map +1 -0
- package/dist/privacy-tools.js +51 -0
- package/dist/privacy-tools.js.map +1 -0
- package/dist/privacy.d.ts +71 -0
- package/dist/privacy.d.ts.map +1 -0
- package/dist/privacy.js +176 -0
- package/dist/privacy.js.map +1 -0
- package/dist/query.d.ts +6 -0
- package/dist/query.d.ts.map +1 -0
- package/dist/query.js +4 -0
- package/dist/query.js.map +1 -0
- package/dist/scoped.d.ts +51 -0
- package/dist/scoped.d.ts.map +1 -0
- package/dist/scoped.js +148 -0
- package/dist/scoped.js.map +1 -0
- package/dist/seed.d.ts +5 -0
- package/dist/seed.d.ts.map +1 -0
- package/dist/seed.js +195 -0
- package/dist/seed.js.map +1 -0
- package/dist/sequence.d.ts +4 -0
- package/dist/sequence.d.ts.map +1 -0
- package/dist/sequence.js +14 -0
- package/dist/sequence.js.map +1 -0
- package/dist/sqlite.d.ts +7 -0
- package/dist/sqlite.d.ts.map +1 -0
- package/dist/sqlite.js +13 -0
- package/dist/sqlite.js.map +1 -0
- package/dist/status.d.ts +101 -0
- package/dist/status.d.ts.map +1 -0
- package/dist/status.js +198 -0
- package/dist/status.js.map +1 -0
- package/dist/tool-kit.d.ts +44 -0
- package/dist/tool-kit.d.ts.map +1 -0
- package/dist/tool-kit.js +34 -0
- package/dist/tool-kit.js.map +1 -0
- package/dist/user-data.d.ts +9 -0
- package/dist/user-data.d.ts.map +1 -0
- package/dist/user-data.js +50 -0
- package/dist/user-data.js.map +1 -0
- package/dist/versions.d.ts +12 -0
- package/dist/versions.d.ts.map +1 -0
- package/dist/versions.js +44 -0
- package/dist/versions.js.map +1 -0
- package/dist/webhooks.d.ts +95 -0
- package/dist/webhooks.d.ts.map +1 -0
- package/dist/webhooks.js +342 -0
- package/dist/webhooks.js.map +1 -0
- package/dist/workflows.d.ts +186 -0
- package/dist/workflows.d.ts.map +1 -0
- package/dist/workflows.js +563 -0
- package/dist/workflows.js.map +1 -0
- package/dist/zod.d.ts +14 -0
- package/dist/zod.d.ts.map +1 -0
- package/dist/zod.js +48 -0
- package/dist/zod.js.map +1 -0
- package/package.json +205 -4
package/dist/admin.js
ADDED
|
@@ -0,0 +1,671 @@
|
|
|
1
|
+
import { and, asc, desc, eq, getTableName, gt, gte, inArray, is, isNotNull, isNull, lt, lte, ne, or, sql, Table, } from "drizzle-orm";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { jsonSchema } from "./agent.js";
|
|
4
|
+
import { decryptRows } from "./crypt.js";
|
|
5
|
+
import { columnsOf, isEncrypted } from "./db.js";
|
|
6
|
+
import { describeSchema } from "./describe.js";
|
|
7
|
+
import { SignetDbError } from "./errors.js";
|
|
8
|
+
import { audited, scoped } from "./scoped.js";
|
|
9
|
+
import { MANAGED_KEYS, toZod } from "./zod.js";
|
|
10
|
+
export const ADMIN_OPS = ["list", "get", "create", "update", "delete", "action"];
|
|
11
|
+
export class AdminError extends SignetDbError {
|
|
12
|
+
status;
|
|
13
|
+
details;
|
|
14
|
+
constructor(status, code, message, details) {
|
|
15
|
+
super(code, message);
|
|
16
|
+
this.status = status;
|
|
17
|
+
if (details)
|
|
18
|
+
this.details = details;
|
|
19
|
+
}
|
|
20
|
+
getResponse() {
|
|
21
|
+
const body = {
|
|
22
|
+
success: false,
|
|
23
|
+
error: this.message,
|
|
24
|
+
code: this.code,
|
|
25
|
+
...(this.details ? { details: this.details } : {}),
|
|
26
|
+
};
|
|
27
|
+
return Response.json(body, { status: this.status });
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const SECRET = /password|passwd|secret|token|hash|salt|api_?key|private_?key/i;
|
|
31
|
+
const SCALAR = new Set(["string", "number", "bigint", "boolean", "date"]);
|
|
32
|
+
const COMPARABLE = new Set(["string", "number", "bigint", "date"]);
|
|
33
|
+
const has = (o, k) => Object.hasOwn(o, k);
|
|
34
|
+
function bad(field, message) {
|
|
35
|
+
return new AdminError(400, "VALIDATION_FAILED", "Validation failed", {
|
|
36
|
+
formErrors: [],
|
|
37
|
+
fieldErrors: { [field]: [message] },
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
function validate(schema, input, prefix = "") {
|
|
41
|
+
const r = schema.safeParse(input);
|
|
42
|
+
if (r.success)
|
|
43
|
+
return r.data;
|
|
44
|
+
const formErrors = [];
|
|
45
|
+
const fieldErrors = {};
|
|
46
|
+
for (const issue of r.error.issues) {
|
|
47
|
+
const path = [prefix, ...issue.path.map(String)].filter(Boolean).join(".");
|
|
48
|
+
if (!path)
|
|
49
|
+
formErrors.push(issue.message);
|
|
50
|
+
else
|
|
51
|
+
fieldErrors[path] = [...(fieldErrors[path] ?? []), issue.message];
|
|
52
|
+
}
|
|
53
|
+
throw new AdminError(400, "VALIDATION_FAILED", "Validation failed", { formErrors, fieldErrors });
|
|
54
|
+
}
|
|
55
|
+
function isAuditTable(cols) {
|
|
56
|
+
return ["actorType", "actorId", "action", "tableName", "before", "after"].every((k) => k in cols);
|
|
57
|
+
}
|
|
58
|
+
function model(table, config) {
|
|
59
|
+
const name = getTableName(table);
|
|
60
|
+
const cols = columnsOf(table);
|
|
61
|
+
const keys = Object.keys(cols);
|
|
62
|
+
const fail = (m) => new SignetDbError("BAD_CONFIG", `defineAdmin: ${name}: ${m}`);
|
|
63
|
+
const known = (list, what) => {
|
|
64
|
+
for (const k of list ?? [])
|
|
65
|
+
if (!has(cols, k))
|
|
66
|
+
throw fail(`${what} names unknown column ${k}.`);
|
|
67
|
+
return list;
|
|
68
|
+
};
|
|
69
|
+
const col = (k) => cols[k];
|
|
70
|
+
const reveal = new Set(known(config.reveal, "reveal"));
|
|
71
|
+
const hidden = new Set([
|
|
72
|
+
...keys.filter((k) => !reveal.has(k) && (isEncrypted(col(k)) || SECRET.test(k) || SECRET.test(col(k).name))),
|
|
73
|
+
...(known(config.hidden, "hidden") ?? []),
|
|
74
|
+
]);
|
|
75
|
+
const visible = keys.filter((k) => !hidden.has(k));
|
|
76
|
+
const scalar = (k) => SCALAR.has(col(k).dataType) && !isEncrypted(col(k));
|
|
77
|
+
const pick = (list, what, ok, def) => {
|
|
78
|
+
for (const k of known(list, what) ?? []) {
|
|
79
|
+
if (hidden.has(k))
|
|
80
|
+
throw fail(`${what} names hidden column ${k}.`);
|
|
81
|
+
if (!ok(k))
|
|
82
|
+
throw fail(`${what} cannot use column ${k} (see the option's doc).`);
|
|
83
|
+
}
|
|
84
|
+
return list ?? def;
|
|
85
|
+
};
|
|
86
|
+
const sortOk = (k) => scalar(k) && col(k).notNull;
|
|
87
|
+
const filterOk = scalar;
|
|
88
|
+
const searchOk = (k) => col(k).dataType === "string" && !isEncrypted(col(k));
|
|
89
|
+
const sortable = new Set(pick(config.sort, "sort", sortOk, visible.filter(sortOk)));
|
|
90
|
+
const filterable = new Set(pick(config.filter, "filter", filterOk, visible.filter(filterOk)));
|
|
91
|
+
const searchable = pick(config.search, "search", searchOk, visible.filter(searchOk));
|
|
92
|
+
const listCols = new Set(pick(config.list, "list", () => true, visible));
|
|
93
|
+
const readonly = new Set(known(config.readonly, "readonly"));
|
|
94
|
+
const described = describeSchema([table], { format: "json" }).tables[0];
|
|
95
|
+
if (!described)
|
|
96
|
+
throw fail("not a table.");
|
|
97
|
+
const pk = described.primaryKey.map((n) => keys.find((k) => col(k).name === n));
|
|
98
|
+
const id = pk.length === 1 ? pk[0] : undefined;
|
|
99
|
+
const audit = isAuditTable(cols);
|
|
100
|
+
const ops = new Set((config.ops ?? ADMIN_OPS).filter((op) => (id || op === "list") &&
|
|
101
|
+
(!audit || op === "list" || op === "get") &&
|
|
102
|
+
(op !== "action" || Object.keys(config.actions ?? {}).length > 0)));
|
|
103
|
+
const writable = (s) => z
|
|
104
|
+
.object(Object.fromEntries(Object.entries(s.shape).filter(([k]) => !hidden.has(k) && !readonly.has(k))))
|
|
105
|
+
.strict();
|
|
106
|
+
const operators = (k) => {
|
|
107
|
+
if (!filterable.has(k))
|
|
108
|
+
return [];
|
|
109
|
+
const t = col(k).dataType;
|
|
110
|
+
return [
|
|
111
|
+
"eq",
|
|
112
|
+
"ne",
|
|
113
|
+
"in",
|
|
114
|
+
"isNull",
|
|
115
|
+
...(COMPARABLE.has(t) ? ["lt", "lte", "gt", "gte"] : []),
|
|
116
|
+
...(t === "string" ? ["contains", "startsWith"] : []),
|
|
117
|
+
];
|
|
118
|
+
};
|
|
119
|
+
const byName = new Map(keys.map((k) => [col(k).name, k]));
|
|
120
|
+
const info = {
|
|
121
|
+
name,
|
|
122
|
+
primaryKey: pk,
|
|
123
|
+
softDelete: "deletedAt" in cols,
|
|
124
|
+
ops: [],
|
|
125
|
+
actions: [],
|
|
126
|
+
columns: described.columns
|
|
127
|
+
.filter((c) => !hidden.has(c.key))
|
|
128
|
+
.map(({ owner: _o, softDelete: _s, encrypted: _e, ...c }) => ({
|
|
129
|
+
...c,
|
|
130
|
+
readonly: readonly.has(c.key) || MANAGED_KEYS.includes(c.key),
|
|
131
|
+
list: listCols.has(c.key),
|
|
132
|
+
sortable: sortable.has(c.key),
|
|
133
|
+
filterable: filterable.has(c.key),
|
|
134
|
+
searchable: searchable.includes(c.key),
|
|
135
|
+
operators: operators(c.key),
|
|
136
|
+
})),
|
|
137
|
+
relations: described.relations
|
|
138
|
+
.map((r) => ({ ...r, columns: r.columns.map((n) => byName.get(n) ?? n) }))
|
|
139
|
+
.filter((r) => r.columns.every((k) => !hidden.has(k))),
|
|
140
|
+
defaultSort: { sort: id && !hidden.has(id) ? id : (pk[0] ?? keys[0] ?? ""), order: "desc" },
|
|
141
|
+
};
|
|
142
|
+
return {
|
|
143
|
+
name,
|
|
144
|
+
table,
|
|
145
|
+
cols,
|
|
146
|
+
info,
|
|
147
|
+
pk,
|
|
148
|
+
...(id ? { id } : {}),
|
|
149
|
+
visible,
|
|
150
|
+
audit,
|
|
151
|
+
revealedEncrypted: visible.some((k) => isEncrypted(col(k))),
|
|
152
|
+
sortable,
|
|
153
|
+
filterable,
|
|
154
|
+
searchable,
|
|
155
|
+
ops,
|
|
156
|
+
actions: config.actions ?? {},
|
|
157
|
+
insert: writable(toZod(table, { mode: "insert", keep: ["userId"] })),
|
|
158
|
+
update: writable(toZod(table, { mode: "update" })),
|
|
159
|
+
values: toZod(table, { mode: "update", keep: MANAGED_KEYS })
|
|
160
|
+
.shape,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
class Held {
|
|
164
|
+
value;
|
|
165
|
+
constructor(value) {
|
|
166
|
+
this.value = value;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const encodeCursor = (c) => {
|
|
170
|
+
const bytes = new TextEncoder().encode(JSON.stringify(c));
|
|
171
|
+
return btoa(String.fromCharCode(...bytes))
|
|
172
|
+
.replace(/\+/g, "-")
|
|
173
|
+
.replace(/\//g, "_")
|
|
174
|
+
.replace(/=+$/, "");
|
|
175
|
+
};
|
|
176
|
+
const decodeCursor = (s) => {
|
|
177
|
+
try {
|
|
178
|
+
const bin = atob(s.replace(/-/g, "+").replace(/_/g, "/"));
|
|
179
|
+
const v = JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0))));
|
|
180
|
+
return v && typeof v.s === "string" && typeof v.o === "string" && Array.isArray(v.k)
|
|
181
|
+
? v
|
|
182
|
+
: undefined;
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
return undefined;
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
const escapeLike = (s) => s.replace(/[\\%_]/g, (m) => `\\${m}`);
|
|
189
|
+
export function defineAdmin(schema, options) {
|
|
190
|
+
return build(schema, options);
|
|
191
|
+
}
|
|
192
|
+
function build(schema, options) {
|
|
193
|
+
const maxRows = options.maxRows ?? 100;
|
|
194
|
+
const configs = (options.tables ?? {});
|
|
195
|
+
const models = new Map();
|
|
196
|
+
for (const t of Object.values(schema)) {
|
|
197
|
+
if (!is(t, Table))
|
|
198
|
+
continue;
|
|
199
|
+
const name = getTableName(t);
|
|
200
|
+
const config = has(configs, name) ? configs[name] : {};
|
|
201
|
+
if (config === false || config === undefined)
|
|
202
|
+
continue;
|
|
203
|
+
models.set(name, model(t, config));
|
|
204
|
+
}
|
|
205
|
+
for (const name of Object.keys(configs)) {
|
|
206
|
+
if (!models.has(name) && configs[name] !== false)
|
|
207
|
+
throw new SignetDbError("BAD_CONFIG", `defineAdmin: tables names ${name}, which is not in the schema.`);
|
|
208
|
+
}
|
|
209
|
+
const allowed = async (ctx, check) => {
|
|
210
|
+
try {
|
|
211
|
+
return (await options.authorize?.(ctx, check)) === true;
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
const inTenant = (ctx, m) => !ctx?.orgId || "orgId" in m.cols;
|
|
218
|
+
const find = (table, ctx) => {
|
|
219
|
+
if (ctx && options.tenant && !ctx.orgId)
|
|
220
|
+
throw new AdminError(403, "FORBIDDEN", "This admin API needs an organisation.");
|
|
221
|
+
const m = table === undefined ? undefined : models.get(table);
|
|
222
|
+
if (!m || !inTenant(ctx, m))
|
|
223
|
+
throw new AdminError(404, "NOT_FOUND", `No admin table ${String(table)}.`);
|
|
224
|
+
return m;
|
|
225
|
+
};
|
|
226
|
+
const tenantCond = (ctx, m) => ctx.orgId ? eq(m.cols.orgId, ctx.orgId) : undefined;
|
|
227
|
+
const gate = async (ctx, m, op, extra = {}) => {
|
|
228
|
+
if (!m.ops.has(op))
|
|
229
|
+
throw new AdminError(405, "METHOD_NOT_ALLOWED", `${op} is not enabled on ${m.name}.`);
|
|
230
|
+
if (!(await allowed(ctx, { table: m.name, op, ...extra })))
|
|
231
|
+
throw new AdminError(403, "FORBIDDEN", `Not allowed to ${op} ${m.name}.`);
|
|
232
|
+
};
|
|
233
|
+
const pickVisible = (m, row) => Object.fromEntries(m.visible.filter((k) => has(row, k)).map((k) => [k, row[k]]));
|
|
234
|
+
const snapshot = async (ctx, table, v) => {
|
|
235
|
+
if (v === null || typeof v !== "object" || table === "*")
|
|
236
|
+
return v;
|
|
237
|
+
const target = typeof table === "string" ? models.get(table) : undefined;
|
|
238
|
+
if (!target)
|
|
239
|
+
return null;
|
|
240
|
+
const row = pickVisible(target, v);
|
|
241
|
+
return (await allowed(ctx, { table: target.name, op: "get", row })) ? row : null;
|
|
242
|
+
};
|
|
243
|
+
const strip = (m, row) => pickVisible(m, row);
|
|
244
|
+
const view = async (ctx, m, row) => {
|
|
245
|
+
const out = strip(m, row);
|
|
246
|
+
if (!m.audit)
|
|
247
|
+
return out;
|
|
248
|
+
if (has(out, "before"))
|
|
249
|
+
out.before = await snapshot(ctx, row.tableName, row.before);
|
|
250
|
+
if (has(out, "after"))
|
|
251
|
+
out.after = await snapshot(ctx, row.tableName, row.after);
|
|
252
|
+
return out;
|
|
253
|
+
};
|
|
254
|
+
const read = async (db, m, where, extra = {}) => {
|
|
255
|
+
const o = db.orm;
|
|
256
|
+
const fields = Object.fromEntries([...new Set([...m.visible, ...m.pk])].map((k) => [k, m.cols[k]]));
|
|
257
|
+
let q = o.select(fields).from(m.table).where(where);
|
|
258
|
+
if (extra.orderBy)
|
|
259
|
+
q = q.orderBy(...extra.orderBy);
|
|
260
|
+
if (extra.limit !== undefined)
|
|
261
|
+
q = q.limit(extra.limit);
|
|
262
|
+
const rows = await q;
|
|
263
|
+
return m.revealedEncrypted ? decryptRows(db, m.table, rows) : rows;
|
|
264
|
+
};
|
|
265
|
+
const live = (m, withDeleted) => m.cols.deletedAt && !withDeleted ? isNull(m.cols.deletedAt) : undefined;
|
|
266
|
+
const idValue = (m, raw) => {
|
|
267
|
+
const c = m.cols[m.id];
|
|
268
|
+
if (c.dataType === "number") {
|
|
269
|
+
const n = typeof raw === "number" ? raw : Number(raw);
|
|
270
|
+
if (raw === "" || !Number.isSafeInteger(n))
|
|
271
|
+
throw bad("id", "Expected an integer id.");
|
|
272
|
+
return n;
|
|
273
|
+
}
|
|
274
|
+
if (typeof raw !== "string" || raw === "")
|
|
275
|
+
throw bad("id", "Expected an id.");
|
|
276
|
+
return raw;
|
|
277
|
+
};
|
|
278
|
+
const byId = (m, id) => eq(m.cols[m.id], idValue(m, id));
|
|
279
|
+
const one = async (db, ctx, m, id, withDeleted) => {
|
|
280
|
+
const [row] = await read(db, m, and(byId(m, id), live(m, withDeleted), tenantCond(ctx, m)), {
|
|
281
|
+
limit: 1,
|
|
282
|
+
});
|
|
283
|
+
if (!row)
|
|
284
|
+
throw new AdminError(404, "NOT_FOUND", `No ${m.name} row with ${m.id} ${String(id)}.`);
|
|
285
|
+
return row;
|
|
286
|
+
};
|
|
287
|
+
const writer = (db, ctx) => ctx.orgId
|
|
288
|
+
?
|
|
289
|
+
audited(scoped(db, { orgId: ctx.orgId }), { actor: ctx.actor })
|
|
290
|
+
: audited(db, { actor: ctx.actor });
|
|
291
|
+
const likeCond = (col, dialect, pattern) => dialect === "pg"
|
|
292
|
+
? sql `${col}::text ilike ${pattern} escape '\\'`
|
|
293
|
+
: sql `${col} like ${pattern} escape '\\'`;
|
|
294
|
+
const filterCond = (m, filter, dialect) => {
|
|
295
|
+
if (filter === undefined)
|
|
296
|
+
return [];
|
|
297
|
+
if (typeof filter !== "object" || filter === null || Array.isArray(filter))
|
|
298
|
+
throw bad("filter", "Expected an object of { column: { operator: value } }.");
|
|
299
|
+
const conds = [];
|
|
300
|
+
for (const [k, spec] of Object.entries(filter)) {
|
|
301
|
+
if (!m.filterable.has(k))
|
|
302
|
+
throw bad(`filter.${k}`, `Cannot filter ${m.name} on ${k}.`);
|
|
303
|
+
if (typeof spec !== "object" || spec === null || Array.isArray(spec))
|
|
304
|
+
throw bad(`filter.${k}`, "Expected { operator: value }.");
|
|
305
|
+
const col = m.cols[k];
|
|
306
|
+
const allowedOps = m.info.columns.find((c) => c.key === k)?.operators ?? [];
|
|
307
|
+
const value = m.values[k];
|
|
308
|
+
for (const [op, raw] of Object.entries(spec)) {
|
|
309
|
+
const path = `filter.${k}.${op}`;
|
|
310
|
+
if (!allowedOps.includes(op))
|
|
311
|
+
throw bad(path, `Operator ${op} does not apply to ${k}; use one of ${allowedOps.join(", ")}.`);
|
|
312
|
+
const v = (s) => {
|
|
313
|
+
if (raw === undefined || raw === null)
|
|
314
|
+
throw bad(path, "Expected a value; use isNull for nulls.");
|
|
315
|
+
return validate(s, raw, path);
|
|
316
|
+
};
|
|
317
|
+
const like = (pattern) => likeCond(col, dialect, pattern);
|
|
318
|
+
switch (op) {
|
|
319
|
+
case "eq":
|
|
320
|
+
conds.push(eq(col, v(value)));
|
|
321
|
+
break;
|
|
322
|
+
case "ne":
|
|
323
|
+
conds.push(ne(col, v(value)));
|
|
324
|
+
break;
|
|
325
|
+
case "lt":
|
|
326
|
+
conds.push(lt(col, v(value)));
|
|
327
|
+
break;
|
|
328
|
+
case "lte":
|
|
329
|
+
conds.push(lte(col, v(value)));
|
|
330
|
+
break;
|
|
331
|
+
case "gt":
|
|
332
|
+
conds.push(gt(col, v(value)));
|
|
333
|
+
break;
|
|
334
|
+
case "gte":
|
|
335
|
+
conds.push(gte(col, v(value)));
|
|
336
|
+
break;
|
|
337
|
+
case "in": {
|
|
338
|
+
const list = v(z.array(value).min(1).max(maxRows));
|
|
339
|
+
conds.push(inArray(col, list));
|
|
340
|
+
break;
|
|
341
|
+
}
|
|
342
|
+
case "contains":
|
|
343
|
+
conds.push(like(`%${escapeLike(v(z.string()))}%`));
|
|
344
|
+
break;
|
|
345
|
+
case "startsWith":
|
|
346
|
+
conds.push(like(`${escapeLike(v(z.string()))}%`));
|
|
347
|
+
break;
|
|
348
|
+
case "isNull":
|
|
349
|
+
conds.push(v(z.boolean()) ? isNull(col) : isNotNull(col));
|
|
350
|
+
break;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return conds;
|
|
355
|
+
};
|
|
356
|
+
const listShape = (m) => ({
|
|
357
|
+
limit: z.number().int().min(1).max(maxRows).optional(),
|
|
358
|
+
cursor: z.string().max(2000).optional(),
|
|
359
|
+
sort: (m.sortable.size
|
|
360
|
+
? z.enum([...m.sortable])
|
|
361
|
+
: z.never()).optional(),
|
|
362
|
+
order: z.enum(["asc", "desc"]).optional(),
|
|
363
|
+
filter: z.record(z.string(), z.record(z.string(), z.unknown())).optional(),
|
|
364
|
+
q: z.string().max(200).optional(),
|
|
365
|
+
withDeleted: z.boolean().optional(),
|
|
366
|
+
});
|
|
367
|
+
async function list(db, ctx, table, query = {}) {
|
|
368
|
+
const m = find(table, ctx);
|
|
369
|
+
await gate(ctx, m, "list");
|
|
370
|
+
const qv = validate(z.object(listShape(m)).strict(), query);
|
|
371
|
+
const sort = qv.sort ?? m.info.defaultSort.sort;
|
|
372
|
+
const order = qv.order ?? "desc";
|
|
373
|
+
const limit = qv.limit ?? Math.min(50, maxRows);
|
|
374
|
+
const conds = [
|
|
375
|
+
live(m, qv.withDeleted),
|
|
376
|
+
tenantCond(ctx, m),
|
|
377
|
+
...filterCond(m, qv.filter, db.dialect),
|
|
378
|
+
];
|
|
379
|
+
if (qv.q && m.searchable.length) {
|
|
380
|
+
const pattern = `%${escapeLike(qv.q)}%`;
|
|
381
|
+
conds.push(or(...m.searchable.map((k) => likeCond(m.cols[k], db.dialect, pattern))));
|
|
382
|
+
}
|
|
383
|
+
const keys = [sort, ...m.pk.filter((k) => k !== sort)];
|
|
384
|
+
if (qv.cursor !== undefined) {
|
|
385
|
+
const c = decodeCursor(qv.cursor);
|
|
386
|
+
if (!c || c.s !== sort || c.o !== order || c.k.length !== m.pk.length)
|
|
387
|
+
throw bad("cursor", "This cursor is for a different sort, or is not a cursor. Start from the first page.");
|
|
388
|
+
const anchorWhere = and(...m.pk.map((k, i) => eq(m.cols[k], c.k[i])), tenantCond(ctx, m));
|
|
389
|
+
const o = db.orm;
|
|
390
|
+
const [anchor] = await o.select({ x: sql `1` }).from(m.table).where(anchorWhere).limit(1);
|
|
391
|
+
if (!anchor)
|
|
392
|
+
throw bad("cursor", "The row this cursor points at is gone. Start from the first page.");
|
|
393
|
+
const at = (k) => sql `(select ${m.cols[k]} from ${m.table} where ${anchorWhere})`;
|
|
394
|
+
const cmp = order === "desc" ? lt : gt;
|
|
395
|
+
const after = (i) => {
|
|
396
|
+
const col = m.cols[keys[i]];
|
|
397
|
+
const key = keys[i];
|
|
398
|
+
if (i === keys.length - 1)
|
|
399
|
+
return cmp(col, at(key));
|
|
400
|
+
return or(cmp(col, at(key)), and(eq(col, at(key)), after(i + 1)));
|
|
401
|
+
};
|
|
402
|
+
conds.push(after(0));
|
|
403
|
+
}
|
|
404
|
+
const dir = order === "desc" ? desc : asc;
|
|
405
|
+
const rows = await read(db, m, and(...conds), {
|
|
406
|
+
orderBy: keys.map((k) => dir(m.cols[k])),
|
|
407
|
+
limit: limit + 1,
|
|
408
|
+
});
|
|
409
|
+
const more = rows.length > limit;
|
|
410
|
+
const page = rows.slice(0, limit);
|
|
411
|
+
const last = page[page.length - 1];
|
|
412
|
+
const out = [];
|
|
413
|
+
for (const r of page) {
|
|
414
|
+
const row = await view(ctx, m, r);
|
|
415
|
+
if (await allowed(ctx, { table: m.name, op: "list", row }))
|
|
416
|
+
out.push(row);
|
|
417
|
+
}
|
|
418
|
+
return {
|
|
419
|
+
rows: out,
|
|
420
|
+
nextCursor: more && last ? encodeCursor({ s: sort, o: order, k: m.pk.map((k) => last[k]) }) : null,
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
async function get(db, ctx, table, id, options = {}) {
|
|
424
|
+
const m = find(table, ctx);
|
|
425
|
+
await gate(ctx, m, "get");
|
|
426
|
+
const row = await view(ctx, m, await one(db, ctx, m, id, options.withDeleted));
|
|
427
|
+
await gate(ctx, m, "get", { row });
|
|
428
|
+
return row;
|
|
429
|
+
}
|
|
430
|
+
const hold = async (g, summary, details) => {
|
|
431
|
+
if (!g)
|
|
432
|
+
return;
|
|
433
|
+
const v = await g(summary, details);
|
|
434
|
+
if (v !== undefined)
|
|
435
|
+
throw new Held(v);
|
|
436
|
+
};
|
|
437
|
+
async function create(db, ctx, table, body, g) {
|
|
438
|
+
const m = find(table, ctx);
|
|
439
|
+
await gate(ctx, m, "create");
|
|
440
|
+
const input = validate(m.insert, ctx.orgId && body && typeof body === "object" ? { ...body, orgId: ctx.orgId } : body);
|
|
441
|
+
await gate(ctx, m, "create", { row: input, input });
|
|
442
|
+
await hold(g, `Create a ${m.name} row`, input);
|
|
443
|
+
const [row] = await writer(db, ctx).insert(m.table, input);
|
|
444
|
+
return strip(m, row);
|
|
445
|
+
}
|
|
446
|
+
async function update(db, ctx, table, id, body, g) {
|
|
447
|
+
const m = find(table, ctx);
|
|
448
|
+
await gate(ctx, m, "update");
|
|
449
|
+
const input = validate(m.update, body);
|
|
450
|
+
if (Object.keys(input).length === 0)
|
|
451
|
+
throw bad("(body)", "Nothing to change.");
|
|
452
|
+
if (ctx.orgId && has(input, "orgId"))
|
|
453
|
+
throw new AdminError(403, "FORBIDDEN", "Rows cannot be moved to another organisation.");
|
|
454
|
+
const before = strip(m, await one(db, ctx, m, id));
|
|
455
|
+
await gate(ctx, m, "update", { row: before, input });
|
|
456
|
+
await hold(g, `Update ${m.name} ${String(id)}`, { before, changes: input });
|
|
457
|
+
const [row] = await writer(db, ctx).update(m.table, input, byId(m, id));
|
|
458
|
+
if (!row)
|
|
459
|
+
throw new AdminError(404, "NOT_FOUND", `No ${m.name} row with ${m.id} ${String(id)}.`);
|
|
460
|
+
return strip(m, row);
|
|
461
|
+
}
|
|
462
|
+
async function remove(db, ctx, table, id, g) {
|
|
463
|
+
const m = find(table, ctx);
|
|
464
|
+
await gate(ctx, m, "delete");
|
|
465
|
+
const row = strip(m, await one(db, ctx, m, id));
|
|
466
|
+
await gate(ctx, m, "delete", { row });
|
|
467
|
+
const soft = m.info.softDelete;
|
|
468
|
+
await hold(g, `${soft ? "Delete" : "Permanently delete"} ${m.name} ${String(id)}`, { row });
|
|
469
|
+
await writer(db, ctx).delete(m.table, byId(m, id));
|
|
470
|
+
return { id: row[m.id] ?? id, soft };
|
|
471
|
+
}
|
|
472
|
+
async function bulkDelete(db, ctx, table, ids) {
|
|
473
|
+
const m = find(table, ctx);
|
|
474
|
+
await gate(ctx, m, "delete");
|
|
475
|
+
const list = validate(z
|
|
476
|
+
.array(z.union([z.string(), z.number()]))
|
|
477
|
+
.min(1)
|
|
478
|
+
.max(maxRows), ids, "ids");
|
|
479
|
+
const values = list.map((v) => idValue(m, v));
|
|
480
|
+
const pk = m.cols[m.id];
|
|
481
|
+
const rows = await read(db, m, and(inArray(pk, values), live(m), tenantCond(ctx, m)));
|
|
482
|
+
const found = rows.map((r) => r[m.id]);
|
|
483
|
+
for (const [i, row] of rows.map((r) => strip(m, r)).entries()) {
|
|
484
|
+
if (!(await allowed(ctx, { table: m.name, op: "delete", row })))
|
|
485
|
+
throw new AdminError(403, "FORBIDDEN", `Not allowed to delete ${m.name} ${String(found[i])}; nothing was deleted.`);
|
|
486
|
+
}
|
|
487
|
+
if (found.length)
|
|
488
|
+
await writer(db, ctx).delete(m.table, inArray(pk, found));
|
|
489
|
+
return { ids: found, soft: m.info.softDelete };
|
|
490
|
+
}
|
|
491
|
+
async function action(db, ctx, table, id, name, body, g) {
|
|
492
|
+
const m = find(table, ctx);
|
|
493
|
+
const def = has(m.actions, name) ? m.actions[name] : undefined;
|
|
494
|
+
if (!def)
|
|
495
|
+
throw new AdminError(404, "NOT_FOUND", `No action ${name} on ${m.name}.`);
|
|
496
|
+
await gate(ctx, m, "action", { action: name });
|
|
497
|
+
const input = def.input ? validate(def.input, body ?? {}) : {};
|
|
498
|
+
const row = strip(m, await one(db, ctx, m, id));
|
|
499
|
+
await gate(ctx, m, "action", { action: name, row, input });
|
|
500
|
+
await hold(g, `${name} on ${m.name} ${String(id)}`, { row, input });
|
|
501
|
+
return (await def.run({ row, input, ctx, db, ops: writer(db, ctx) })) ?? null;
|
|
502
|
+
}
|
|
503
|
+
async function meta(ctx) {
|
|
504
|
+
const tables = [];
|
|
505
|
+
if (options.tenant && !ctx.orgId)
|
|
506
|
+
return { tables };
|
|
507
|
+
for (const m of models.values()) {
|
|
508
|
+
if (!inTenant(ctx, m))
|
|
509
|
+
continue;
|
|
510
|
+
const ops = [];
|
|
511
|
+
for (const op of m.ops)
|
|
512
|
+
if (op !== "action" && (await allowed(ctx, { table: m.name, op })))
|
|
513
|
+
ops.push(op);
|
|
514
|
+
const actions = [];
|
|
515
|
+
for (const [name, a] of Object.entries(m.actions))
|
|
516
|
+
if (m.ops.has("action") &&
|
|
517
|
+
(await allowed(ctx, { table: m.name, op: "action", action: name })))
|
|
518
|
+
actions.push({ name, description: a.description, destructive: a.destructive ?? false });
|
|
519
|
+
if (actions.length)
|
|
520
|
+
ops.push("action");
|
|
521
|
+
if (ops.length)
|
|
522
|
+
tables.push({ ...m.info, ops, actions });
|
|
523
|
+
}
|
|
524
|
+
return { tables };
|
|
525
|
+
}
|
|
526
|
+
async function handle(db, ctx, req) {
|
|
527
|
+
const method = req.method.toUpperCase();
|
|
528
|
+
const q = req.query ?? {};
|
|
529
|
+
const flag = (v) => v === "true" || v === "1";
|
|
530
|
+
const ok = (body, status = 200) => ({ status, body });
|
|
531
|
+
const nope = () => new AdminError(405, "METHOD_NOT_ALLOWED", `${method} is not an admin route here.`);
|
|
532
|
+
if (req.table === undefined) {
|
|
533
|
+
if (method === "GET")
|
|
534
|
+
return ok(await meta(ctx));
|
|
535
|
+
throw nope();
|
|
536
|
+
}
|
|
537
|
+
if (req.id === undefined) {
|
|
538
|
+
if (method === "POST")
|
|
539
|
+
return ok(await create(db, ctx, req.table, req.body), 201);
|
|
540
|
+
if (method !== "GET")
|
|
541
|
+
throw nope();
|
|
542
|
+
let filter;
|
|
543
|
+
if (q.filter !== undefined) {
|
|
544
|
+
try {
|
|
545
|
+
filter = JSON.parse(q.filter);
|
|
546
|
+
}
|
|
547
|
+
catch {
|
|
548
|
+
throw bad("filter", 'Expected JSON, e.g. {"status":{"eq":"open"}}.');
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
const limit = q.limit === undefined ? undefined : Number(q.limit);
|
|
552
|
+
return ok(await list(db, ctx, req.table, {
|
|
553
|
+
...(limit !== undefined ? { limit } : {}),
|
|
554
|
+
...(q.cursor !== undefined ? { cursor: q.cursor } : {}),
|
|
555
|
+
...(q.sort !== undefined ? { sort: q.sort } : {}),
|
|
556
|
+
...(q.order !== undefined ? { order: q.order } : {}),
|
|
557
|
+
...(q.q !== undefined ? { q: q.q } : {}),
|
|
558
|
+
...(filter !== undefined ? { filter: filter } : {}),
|
|
559
|
+
...(flag(q.withDeleted) ? { withDeleted: true } : {}),
|
|
560
|
+
}));
|
|
561
|
+
}
|
|
562
|
+
if (req.action !== undefined) {
|
|
563
|
+
if (method !== "POST")
|
|
564
|
+
throw nope();
|
|
565
|
+
return ok(await action(db, ctx, req.table, req.id, req.action, req.body));
|
|
566
|
+
}
|
|
567
|
+
if (method === "POST" && req.id === "bulk-delete") {
|
|
568
|
+
const ids = req.body?.ids;
|
|
569
|
+
return ok(await bulkDelete(db, ctx, req.table, ids));
|
|
570
|
+
}
|
|
571
|
+
if (method === "GET")
|
|
572
|
+
return ok(await get(db, ctx, req.table, req.id, { withDeleted: flag(q.withDeleted) }));
|
|
573
|
+
if (method === "PATCH")
|
|
574
|
+
return ok(await update(db, ctx, req.table, req.id, req.body));
|
|
575
|
+
if (method === "DELETE")
|
|
576
|
+
return ok(await remove(db, ctx, req.table, req.id));
|
|
577
|
+
throw nope();
|
|
578
|
+
}
|
|
579
|
+
const gated = async (fn, g) => {
|
|
580
|
+
try {
|
|
581
|
+
return await fn(g);
|
|
582
|
+
}
|
|
583
|
+
catch (e) {
|
|
584
|
+
if (e instanceof Held)
|
|
585
|
+
return e.value;
|
|
586
|
+
throw e;
|
|
587
|
+
}
|
|
588
|
+
};
|
|
589
|
+
return {
|
|
590
|
+
tables: [...models.keys()],
|
|
591
|
+
meta,
|
|
592
|
+
list,
|
|
593
|
+
get,
|
|
594
|
+
create: (db, ctx, table, body) => create(db, ctx, table, body),
|
|
595
|
+
update: (db, ctx, table, id, body) => update(db, ctx, table, id, body),
|
|
596
|
+
delete: (db, ctx, table, id) => remove(db, ctx, table, id),
|
|
597
|
+
bulkDelete,
|
|
598
|
+
action: (db, ctx, table, id, name, body) => action(db, ctx, table, id, name, body),
|
|
599
|
+
handle,
|
|
600
|
+
_tools: { find, listShape, create, update, remove, action, gated, maxRows },
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
export const DEFAULT_ROLES = {
|
|
604
|
+
admin: "*",
|
|
605
|
+
staff: ["list", "get", "create", "update", "action"],
|
|
606
|
+
readonly: ["list", "get"],
|
|
607
|
+
};
|
|
608
|
+
export function roles(map = DEFAULT_ROLES) {
|
|
609
|
+
return (ctx, { op }) => {
|
|
610
|
+
const role = ctx.role;
|
|
611
|
+
if (!role || !has(map, role))
|
|
612
|
+
return false;
|
|
613
|
+
const ops = map[role];
|
|
614
|
+
return ops === "*" || (ops?.includes(op) ?? false);
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
export async function adminTools(admin, options) {
|
|
618
|
+
const { db, approve } = options;
|
|
619
|
+
const ctx = {
|
|
620
|
+
...options.ctx,
|
|
621
|
+
actor: options.actor ?? { type: "agent", id: options.ctx.actor.id },
|
|
622
|
+
};
|
|
623
|
+
const t = admin._tools;
|
|
624
|
+
const meta = await admin.meta(ctx);
|
|
625
|
+
const tools = [];
|
|
626
|
+
const add = (name, description, shape, kind, fn) => {
|
|
627
|
+
const input = z.object(shape).strict();
|
|
628
|
+
const run = async (raw, toolCtx) => fn(validate(input, raw ?? {}), toolCtx);
|
|
629
|
+
tools.push({
|
|
630
|
+
name,
|
|
631
|
+
description,
|
|
632
|
+
annotations: { readOnlyHint: kind === "read", destructiveHint: kind === "destroy" },
|
|
633
|
+
input,
|
|
634
|
+
inputSchema: jsonSchema(input),
|
|
635
|
+
run,
|
|
636
|
+
handler: run,
|
|
637
|
+
});
|
|
638
|
+
};
|
|
639
|
+
const gateFor = (toolCtx, args) => (summary, details) => approve(toolCtx, { summary, details, args });
|
|
640
|
+
const idSchema = z.union([z.string(), z.number()]);
|
|
641
|
+
add("admin_schema", "Describe the admin tables you may use: columns, types, relations, allowed ops, filter operators and actions.", {}, "read", async () => meta);
|
|
642
|
+
for (const tm of meta.tables) {
|
|
643
|
+
const m = t.find(tm.name);
|
|
644
|
+
const can = new Set(tm.ops);
|
|
645
|
+
const n = `admin_${tm.name}`;
|
|
646
|
+
if (can.has("list")) {
|
|
647
|
+
add(`${n}_list`, `List ${tm.name} rows. Page with nextCursor (same sort and order). filter is { column: { operator: value } }; see admin_schema for columns and operators. At most ${t.maxRows} per call.`, t.listShape(m), "read", (i) => admin.list(db, ctx, tm.name, i));
|
|
648
|
+
if (m.searchable.length)
|
|
649
|
+
add(`${n}_search`, `Find ${tm.name} rows whose ${m.searchable.join(", ")} contain the text (case-insensitive).`, {
|
|
650
|
+
q: z.string().min(1).max(200),
|
|
651
|
+
limit: z.number().int().min(1).max(t.maxRows).optional(),
|
|
652
|
+
}, "read", (i) => admin.list(db, ctx, tm.name, i));
|
|
653
|
+
}
|
|
654
|
+
if (can.has("get"))
|
|
655
|
+
add(`${n}_get`, `Get one ${tm.name} row by ${m.id}.`, { id: idSchema }, "read", (i) => admin.get(db, ctx, tm.name, i.id));
|
|
656
|
+
if (!approve)
|
|
657
|
+
continue;
|
|
658
|
+
if (can.has("create"))
|
|
659
|
+
add(`${n}_create`, `Create a ${tm.name} row. Asks the person to approve first; nothing is written without it.`, { values: m.insert }, "write", (i, tc) => t.gated((g) => t.create(db, ctx, tm.name, i.values, g), gateFor(tc, i)));
|
|
660
|
+
if (can.has("update"))
|
|
661
|
+
add(`${n}_update`, `Change fields of one ${tm.name} row. Asks the person to approve first.`, { id: idSchema, set: m.update.partial() }, "write", (i, tc) => t.gated((g) => t.update(db, ctx, tm.name, i.id, i.set, g), gateFor(tc, i)));
|
|
662
|
+
if (can.has("delete"))
|
|
663
|
+
add(`${n}_delete`, `${tm.softDelete ? "Soft-delete" : "Permanently delete"} one ${tm.name} row. Asks the person to approve first.`, { id: idSchema }, "destroy", (i, tc) => t.gated((g) => t.remove(db, ctx, tm.name, i.id, g), gateFor(tc, i)));
|
|
664
|
+
for (const a of tm.actions) {
|
|
665
|
+
const def = m.actions[a.name];
|
|
666
|
+
add(`${n}_${a.name}`, `${a.description} Runs on one ${tm.name} row. Asks the person to approve first.`, { id: idSchema, ...(def.input ? { input: def.input } : {}) }, a.destructive ? "destroy" : "write", (i, tc) => t.gated((g) => t.action(db, ctx, tm.name, i.id, a.name, i.input, g), gateFor(tc, i)));
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
return tools;
|
|
670
|
+
}
|
|
671
|
+
//# sourceMappingURL=admin.js.map
|