kizunacms 0.0.0 → 0.1.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.MD +9 -0
- package/README.md +208 -0
- package/dist/access-4YiqVHXB.d.mts +1251 -0
- package/dist/access-CrrWP0hv.d.cts +1251 -0
- package/dist/db-Cnv0aXba.cjs +1603 -0
- package/dist/db-wUR_ude-.mjs +1274 -0
- package/dist/index.cjs +2716 -0
- package/dist/index.d.cts +545 -0
- package/dist/index.d.mts +545 -0
- package/dist/index.mjs +2701 -0
- package/dist/postgres.cjs +1152 -0
- package/dist/postgres.d.cts +99 -0
- package/dist/postgres.d.mts +99 -0
- package/dist/postgres.mjs +1151 -0
- package/package.json +96 -3
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,2701 @@
|
|
|
1
|
+
import { A as schemaOf, B as FocalPointSchema, C as setEditorsCollection, D as SlugSchema, E as writtenMetaOf, F as LOGIN_WINDOW, G as diskStorage, H as isFileField, I as MAX_IMAGE_PIXELS, J as newFileKey, K as fileCollectionOf, L as PASSWORD_RESET_LIFETIME, M as wrappedSchemaOf, O as TextSchema, P as INVITE_LIFETIME, R as PASSWORD_RESET_WINDOW, S as resolveDocuments, T as withoutEditorReferences, U as acceptsType, V as fileProblemOf, W as defineStorage, X as storeFieldTypesOf, Y as registerStores, _ as WrittenMetaSchema, b as metaImageProblemOf, c as createSchemaOf, d as labelsOf, f as modelNameOf, g as withGeneratedSlugs, h as setSlugOptions, j as setReadSchema, k as columnOf, l as defineCollection, m as isGeneratedSlug, n as GLOBALS_COLLECTION, o as EditorReferenceSchema, p as updateSchemaOf, q as memoryStorage, r as memoryAdapter, s as checkDefinition, t as ConflictError, u as documentSchemaOf, v as editorReferencesOf, w as setTitleSuffix, x as metaImageStoreOf, y as mergeMetaChange, z as SESSION_LIFETIME } from "./db-wUR_ude-.mjs";
|
|
2
|
+
import { Kizuna as Kizuna$1, defineConfig as defineConfig$1, isRoles } from "kizunajs";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import pluralize from "pluralize";
|
|
5
|
+
import { scrypt, timingSafeEqual } from "node:crypto";
|
|
6
|
+
import { ProblemDetailsSchema } from "kizunajs/schemas";
|
|
7
|
+
import { crc32 } from "node:zlib";
|
|
8
|
+
import { imageDimensionsFromData } from "image-dimensions";
|
|
9
|
+
//#region src/access.ts
|
|
10
|
+
/**
|
|
11
|
+
* The identity editors log in as.
|
|
12
|
+
*/
|
|
13
|
+
const EDITOR_IDENTITY = "editor";
|
|
14
|
+
/**
|
|
15
|
+
* The role every CMS has built in. Admins pass every collection's, global's and store's `auth`, and may set other
|
|
16
|
+
* users' roles.
|
|
17
|
+
*/
|
|
18
|
+
const ADMIN_ROLE = "admin";
|
|
19
|
+
/**
|
|
20
|
+
* The role name that lets anyone in without logging in.
|
|
21
|
+
*/
|
|
22
|
+
const PUBLIC = "public";
|
|
23
|
+
/**
|
|
24
|
+
* Each action's tool hints, which a `tools` entry overrides.
|
|
25
|
+
*/
|
|
26
|
+
const TOOL_DEFAULTS = {
|
|
27
|
+
read: { openWorldHint: false },
|
|
28
|
+
create: {
|
|
29
|
+
destructiveHint: false,
|
|
30
|
+
openWorldHint: false
|
|
31
|
+
},
|
|
32
|
+
update: { openWorldHint: false },
|
|
33
|
+
delete: {
|
|
34
|
+
needsApproval: true,
|
|
35
|
+
openWorldHint: false
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* The `tool` a CMS route declares for one action.
|
|
40
|
+
*/
|
|
41
|
+
const toolOf = (tools, operation) => {
|
|
42
|
+
const option = tools === true ? true : tools?.[operation];
|
|
43
|
+
if (option === void 0 || option === false) return false;
|
|
44
|
+
return {
|
|
45
|
+
...TOOL_DEFAULTS[operation],
|
|
46
|
+
...option === true ? {} : option
|
|
47
|
+
};
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* The role names `roles` declares, from a list or from `Kizuna.roles`.
|
|
51
|
+
*/
|
|
52
|
+
const roleNamesOf = (roles) => isRoles(roles) ? roles.names : roles;
|
|
53
|
+
/**
|
|
54
|
+
* The permission catalog `roles` is built from, or `undefined` for plain names.
|
|
55
|
+
*/
|
|
56
|
+
const permissionCatalogOf = (roles) => isRoles(roles) ? roles.permissions?.catalog : void 0;
|
|
57
|
+
/**
|
|
58
|
+
* The config's `roles` with the built-in `admin` first, which holds every permission when the roles come from a
|
|
59
|
+
* catalog.
|
|
60
|
+
*/
|
|
61
|
+
const withAdminRole = (roles) => {
|
|
62
|
+
const declared = roleNamesOf(roles);
|
|
63
|
+
if (declared.includes("admin")) throw new Error(`\`roles\` lists '${ADMIN_ROLE}', which every CMS has built in. Leave it out.`);
|
|
64
|
+
if (declared.includes("public")) throw new Error(`\`roles\` names '${PUBLIC}', which a collection's \`auth\` keeps for no login. Rename it.`);
|
|
65
|
+
if (!isRoles(roles) || roles.permissions === void 0) return [ADMIN_ROLE, ...declared];
|
|
66
|
+
return Kizuna$1.roles(roles.permissions, {
|
|
67
|
+
[ADMIN_ROLE]: "all",
|
|
68
|
+
...roles.definitions
|
|
69
|
+
});
|
|
70
|
+
};
|
|
71
|
+
const unique = (roles) => [...new Set(roles)];
|
|
72
|
+
const OPERATIONS = [
|
|
73
|
+
"read",
|
|
74
|
+
"create",
|
|
75
|
+
"update",
|
|
76
|
+
"delete"
|
|
77
|
+
];
|
|
78
|
+
const GLOBAL_OPERATIONS = ["read", "update"];
|
|
79
|
+
/**
|
|
80
|
+
* Checks every role the options name and returns the access each collection's and global's routes take.
|
|
81
|
+
*/
|
|
82
|
+
const accessOf = (options) => {
|
|
83
|
+
const { collections, globals } = options;
|
|
84
|
+
const identityName = EDITOR_IDENTITY;
|
|
85
|
+
const declared = roleNamesOf(options.roles);
|
|
86
|
+
const documentRoles = options.documentRoles ?? {};
|
|
87
|
+
const notDeclared = (where, role) => /* @__PURE__ */ new Error(`${where} names the role '${role}', which nobody declares. Add it to \`roles\`, or under \`documentRoles\`.`);
|
|
88
|
+
for (const name of Object.keys(documentRoles)) if (name === "public" || declared.includes(name)) throw new Error(`\`documentRoles\` declares '${name}', which is already ${name === "public" ? "the value for no login" : name === "admin" ? "the built-in admin role" : "one of `roles`"}. Give it a name of its own.`);
|
|
89
|
+
const admins = [ADMIN_ROLE];
|
|
90
|
+
const operationsOf = (target) => target.kind === "global" ? GLOBAL_OPERATIONS : OPERATIONS;
|
|
91
|
+
const labelOf = (target) => `${target.kind === "collection" ? "Collection" : target.kind === "store" ? "Store" : "Global"} '${target.name}'`;
|
|
92
|
+
const accessFor = (target, operation) => {
|
|
93
|
+
const operations = operationsOf(target);
|
|
94
|
+
if (target.auth === void 0 || target.auth === null || typeof target.auth !== "object") throw new Error(`${labelOf(target)} ${target.auth === void 0 ? "states no `auth`" : `has \`auth: ${String(target.auth)}\``}. Say who may ${operations.join(", ")}, each on its own, with \`['public']\` for no login.`);
|
|
95
|
+
const named = target.auth[operation];
|
|
96
|
+
const where = `${labelOf(target)} \`auth.${operation}\``;
|
|
97
|
+
if (named === void 0) throw new Error(`${labelOf(target)} \`auth\` leaves out \`${operation}\`. Say who may, with \`['public']\` for no login.`);
|
|
98
|
+
if (!Array.isArray(named)) {
|
|
99
|
+
if (named === null || typeof named !== "object" || !("identity" in named)) throw new Error(`${where} is \`${JSON.stringify(named)}\`. Write \`['public']\` for no login, a list of roles, or a rule with an \`identity\`.`);
|
|
100
|
+
return {
|
|
101
|
+
kind: "rule",
|
|
102
|
+
rule: named
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
const roles = [];
|
|
106
|
+
const documentFields = [];
|
|
107
|
+
if (named.includes("public")) {
|
|
108
|
+
if (named.length > 1) throw new Error(`${where} lists '${PUBLIC}' beside roles. '${PUBLIC}' already lets everyone in, so write \`['${PUBLIC}']\` alone.`);
|
|
109
|
+
return { kind: "public" };
|
|
110
|
+
}
|
|
111
|
+
for (const role of named) {
|
|
112
|
+
const documentRole = documentRoles[role];
|
|
113
|
+
if (documentRole !== void 0) {
|
|
114
|
+
if (target.kind === "global") throw new Error(`${where} names the document role '${role}'. A ${target.kind} is no user's own, so name roles from \`roles\`.`);
|
|
115
|
+
if (operation === "read" || operation === "create") throw new Error(`${where} names the document role '${role}'. A document role can change or delete a document, not ${operation} one.`);
|
|
116
|
+
if (!target.fields.some((field) => field.name === documentRole.field)) throw new Error(`${where} names the document role '${role}', and the collection has no field '${documentRole.field}' to hold its id.`);
|
|
117
|
+
documentFields.push(documentRole.field);
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (!declared.includes(role)) throw notDeclared(where, role);
|
|
121
|
+
roles.push(role);
|
|
122
|
+
}
|
|
123
|
+
const passing = unique([...admins, ...roles]);
|
|
124
|
+
if (passing.length === 0 && documentFields.length === 0) return { kind: "nobody" };
|
|
125
|
+
return {
|
|
126
|
+
kind: "editors",
|
|
127
|
+
identity: identityName,
|
|
128
|
+
roles: passing,
|
|
129
|
+
documentFields: unique(documentFields)
|
|
130
|
+
};
|
|
131
|
+
};
|
|
132
|
+
for (const target of [...collections, ...globals]) for (const operation of operationsOf(target)) accessFor(target, operation);
|
|
133
|
+
return {
|
|
134
|
+
ofCollection: (collection) => ({
|
|
135
|
+
read: accessFor(collection, "read"),
|
|
136
|
+
create: accessFor(collection, "create"),
|
|
137
|
+
update: accessFor(collection, "update"),
|
|
138
|
+
delete: accessFor(collection, "delete")
|
|
139
|
+
}),
|
|
140
|
+
ofGlobal: (global) => ({
|
|
141
|
+
read: accessFor(global, "read"),
|
|
142
|
+
update: accessFor(global, "update")
|
|
143
|
+
})
|
|
144
|
+
};
|
|
145
|
+
};
|
|
146
|
+
/**
|
|
147
|
+
* The `auth` a route with this access declares, which lets every editor through when the handler checks a document role.
|
|
148
|
+
*/
|
|
149
|
+
const routeAuthOf = (access) => {
|
|
150
|
+
if (access.kind === "rule") return access.rule;
|
|
151
|
+
if (access.kind !== "editors") return false;
|
|
152
|
+
if (access.roles === void 0 || access.documentFields.length > 0) return access.identity;
|
|
153
|
+
return {
|
|
154
|
+
identity: access.identity,
|
|
155
|
+
roles: access.roles
|
|
156
|
+
};
|
|
157
|
+
};
|
|
158
|
+
/**
|
|
159
|
+
* The cache policy for a read with this access, which keeps a read behind a login out of shared caches.
|
|
160
|
+
*/
|
|
161
|
+
const readCacheOf = (access) => access.kind === "public" ? {
|
|
162
|
+
scope: "public",
|
|
163
|
+
maxAge: 0,
|
|
164
|
+
sharedMaxAge: 60
|
|
165
|
+
} : {
|
|
166
|
+
scope: "private",
|
|
167
|
+
noCache: true
|
|
168
|
+
};
|
|
169
|
+
const holdsAnyRole = (role, roles) => typeof role === "string" ? roles.includes(role) : Array.isArray(role) && role.some((each) => roles.includes(each));
|
|
170
|
+
const holdsId = (value, id) => value === id || Array.isArray(value) && value.includes(id);
|
|
171
|
+
const callerOf = (access, auth) => access.kind === "editors" ? auth?.[access.identity] : void 0;
|
|
172
|
+
/**
|
|
173
|
+
* How the caller may change one document, checking the document roles that Kizuna.js leaves to the handler.
|
|
174
|
+
*/
|
|
175
|
+
const writeGrantOf = async (access, auth, load) => {
|
|
176
|
+
if (access.kind !== "editors") return "role";
|
|
177
|
+
if (access.documentFields.length === 0) return "role";
|
|
178
|
+
const caller = callerOf(access, auth);
|
|
179
|
+
if (caller === void 0) return "none";
|
|
180
|
+
if (access.roles !== void 0 && holdsAnyRole(caller.role, access.roles)) return "role";
|
|
181
|
+
if (typeof caller.id !== "string") return "none";
|
|
182
|
+
const document = await load();
|
|
183
|
+
if (document === void 0) return "none";
|
|
184
|
+
const id = caller.id;
|
|
185
|
+
return access.documentFields.some((field) => holdsId(document[field], id)) ? "document" : "none";
|
|
186
|
+
};
|
|
187
|
+
/**
|
|
188
|
+
* Whether the caller may change one document, through a listed role, as an admin or through a document role.
|
|
189
|
+
*/
|
|
190
|
+
const mayWriteDocument = async (access, auth, load) => await writeGrantOf(access, auth, load) !== "none";
|
|
191
|
+
/**
|
|
192
|
+
* The first document-role field a write changes, or `undefined` when it changes none. A missing value and `null` count
|
|
193
|
+
* as the same.
|
|
194
|
+
*/
|
|
195
|
+
const changedDocumentFieldOf = (access, body, stored) => {
|
|
196
|
+
if (access.kind !== "editors") return void 0;
|
|
197
|
+
return access.documentFields.find((field) => body[field] !== void 0 && JSON.stringify(body[field] ?? null) !== JSON.stringify(stored?.[field] ?? null));
|
|
198
|
+
};
|
|
199
|
+
//#endregion
|
|
200
|
+
//#region src/accounts.ts
|
|
201
|
+
const PasswordSchema = z.string().min(12, "Use at least 12 characters.").max(256, `Use at most 256 characters.`);
|
|
202
|
+
const KEY_LENGTH = 64;
|
|
203
|
+
const derivedKey = (password, salt, keyLength) => new Promise((resolve, reject) => {
|
|
204
|
+
scrypt(password, salt, keyLength, (error, key) => error === null ? resolve(key) : reject(error));
|
|
205
|
+
});
|
|
206
|
+
const randomBytes = (size) => crypto.getRandomValues(new Uint8Array(size));
|
|
207
|
+
const toBase64Url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
208
|
+
const fromBase64Url = (text) => Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (character) => character.charCodeAt(0));
|
|
209
|
+
/**
|
|
210
|
+
* Hashes a password with scrypt and a random salt.
|
|
211
|
+
*/
|
|
212
|
+
const hashPassword = async (password) => {
|
|
213
|
+
const salt = randomBytes(16);
|
|
214
|
+
const key = await derivedKey(password, salt, KEY_LENGTH);
|
|
215
|
+
return `scrypt:${toBase64Url(salt)}:${toBase64Url(key)}`;
|
|
216
|
+
};
|
|
217
|
+
/**
|
|
218
|
+
* Returns whether a password matches a hash from `hashPassword`.
|
|
219
|
+
*/
|
|
220
|
+
const verifyPassword = async (password, hash) => {
|
|
221
|
+
const [scheme, salt, key] = hash.split(":");
|
|
222
|
+
if (scheme !== "scrypt" || salt === void 0 || key === void 0) return false;
|
|
223
|
+
const expected = fromBase64Url(key);
|
|
224
|
+
if (expected.length === 0) return false;
|
|
225
|
+
return timingSafeEqual(await derivedKey(password, fromBase64Url(salt), expected.length), expected);
|
|
226
|
+
};
|
|
227
|
+
/**
|
|
228
|
+
* A hash to check against when no editor has the email. A wrong email then takes as long as a wrong password.
|
|
229
|
+
*/
|
|
230
|
+
let standIn;
|
|
231
|
+
const standInHash = () => standIn ??= hashPassword(toBase64Url(randomBytes(16)));
|
|
232
|
+
/**
|
|
233
|
+
* The SHA-256 of a session token. The database keeps only this.
|
|
234
|
+
*/
|
|
235
|
+
const tokenHashOf = async (token) => toBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token))));
|
|
236
|
+
/**
|
|
237
|
+
* A hash to check a password against when no account has the email, or the account has no password yet.
|
|
238
|
+
*/
|
|
239
|
+
const hashToCheck = (hash) => hash === void 0 ? standInHash() : Promise.resolve(hash);
|
|
240
|
+
const normalizeEmail = (email) => email.toLowerCase();
|
|
241
|
+
/**
|
|
242
|
+
* Starts a session for an account and returns its token. Only the token's hash is stored.
|
|
243
|
+
*/
|
|
244
|
+
const startSession = async (store, collection, accountId) => {
|
|
245
|
+
const token = toBase64Url(randomBytes(32));
|
|
246
|
+
await store.createSession({
|
|
247
|
+
tokenHash: await tokenHashOf(token),
|
|
248
|
+
collection,
|
|
249
|
+
accountId,
|
|
250
|
+
expiresAt: new Date(Date.now() + SESSION_LIFETIME).toISOString()
|
|
251
|
+
});
|
|
252
|
+
return token;
|
|
253
|
+
};
|
|
254
|
+
/**
|
|
255
|
+
* Counts a login for the email before its password is checked, and answers whether it is over the limit.
|
|
256
|
+
*/
|
|
257
|
+
const isOverLoginLimit = async (store, collection, email) => {
|
|
258
|
+
await store.recordFailedLogin(collection, email);
|
|
259
|
+
return await store.failedLoginsSince(collection, email, new Date(Date.now() - LOGIN_WINDOW).toISOString()) > 5;
|
|
260
|
+
};
|
|
261
|
+
/**
|
|
262
|
+
* Counts a password reset request for the email, whether or not it has an account, and answers whether it is over
|
|
263
|
+
* the limit.
|
|
264
|
+
*/
|
|
265
|
+
const isOverResetLimit = async (store, collection, email) => {
|
|
266
|
+
await store.recordPasswordResetRequest(collection, email);
|
|
267
|
+
const since = new Date(Date.now() - PASSWORD_RESET_WINDOW).toISOString();
|
|
268
|
+
return await store.passwordResetRequestsSince(collection, email, since) > 5;
|
|
269
|
+
};
|
|
270
|
+
/**
|
|
271
|
+
* Creates a one-time token for setting a password, which works an hour for a reset and 7 days for an invite.
|
|
272
|
+
*/
|
|
273
|
+
const createPasswordLink = async (store, collection, accountId, reason) => {
|
|
274
|
+
const token = toBase64Url(randomBytes(32));
|
|
275
|
+
await store.createPasswordToken({
|
|
276
|
+
tokenHash: await tokenHashOf(token),
|
|
277
|
+
collection,
|
|
278
|
+
accountId,
|
|
279
|
+
expiresAt: new Date(Date.now() + (reason === "reset" ? PASSWORD_RESET_LIFETIME : INVITE_LIFETIME)).toISOString()
|
|
280
|
+
});
|
|
281
|
+
return token;
|
|
282
|
+
};
|
|
283
|
+
/**
|
|
284
|
+
* Uses up a password link and answers whose it was, or `undefined` when it expired, was used or is another collection's.
|
|
285
|
+
*/
|
|
286
|
+
const redeemPasswordLink = async (store, collection, token) => {
|
|
287
|
+
const taken = await store.takePasswordToken(await tokenHashOf(token));
|
|
288
|
+
return taken === void 0 || taken.collection !== collection || Date.parse(taken.expiresAt) <= Date.now() ? void 0 : taken.accountId;
|
|
289
|
+
};
|
|
290
|
+
const k$2 = new Kizuna$1();
|
|
291
|
+
/**
|
|
292
|
+
* A bearer identity whose guard gives routes the session's account, taking only sessions of its own `collection`.
|
|
293
|
+
*/
|
|
294
|
+
const accountIdentityOf = (options) => {
|
|
295
|
+
const roleNames = options.roles === void 0 ? [] : isRoles(options.roles) ? options.roles.names : options.roles;
|
|
296
|
+
return k$2.identity.bearer({
|
|
297
|
+
description: options.description,
|
|
298
|
+
context: z.object({
|
|
299
|
+
id: z.string(),
|
|
300
|
+
session: z.string()
|
|
301
|
+
}),
|
|
302
|
+
...options.roles === void 0 || roleNames.length === 0 ? {} : { roles: isRoles(options.roles) ? options.roles : Kizuna$1.roles(roleNames) }
|
|
303
|
+
}).guard(async ({ bearer, deny }) => {
|
|
304
|
+
const askToLogIn = () => deny({
|
|
305
|
+
status: 401,
|
|
306
|
+
body: { detail: `Log in as ${options.who}.` }
|
|
307
|
+
});
|
|
308
|
+
if (bearer === null) return askToLogIn();
|
|
309
|
+
const tokenHash = await tokenHashOf(bearer.token);
|
|
310
|
+
const session = await options.store.getSession(tokenHash);
|
|
311
|
+
if (session === void 0 || session.collection !== options.collection) return askToLogIn();
|
|
312
|
+
if (Date.parse(session.expiresAt) <= Date.now()) {
|
|
313
|
+
await options.store.deleteSession(tokenHash);
|
|
314
|
+
return askToLogIn();
|
|
315
|
+
}
|
|
316
|
+
const account = await options.load(session.accountId);
|
|
317
|
+
if (account === void 0) return askToLogIn();
|
|
318
|
+
return {
|
|
319
|
+
id: account.id,
|
|
320
|
+
session: tokenHash,
|
|
321
|
+
role: account.roles.filter((role) => roleNames.includes(role))
|
|
322
|
+
};
|
|
323
|
+
});
|
|
324
|
+
};
|
|
325
|
+
//#endregion
|
|
326
|
+
//#region src/where-schema.ts
|
|
327
|
+
const valueOperatorsOf = (value) => ({
|
|
328
|
+
equals: value.optional(),
|
|
329
|
+
not: value.optional(),
|
|
330
|
+
in: z.array(value).max(100).optional(),
|
|
331
|
+
notIn: z.array(value).max(100).optional(),
|
|
332
|
+
exists: z.boolean().optional()
|
|
333
|
+
});
|
|
334
|
+
const rangeOperatorsOf = (value) => ({
|
|
335
|
+
greaterThan: value.optional(),
|
|
336
|
+
atLeast: value.optional(),
|
|
337
|
+
lessThan: value.optional(),
|
|
338
|
+
atMost: value.optional()
|
|
339
|
+
});
|
|
340
|
+
/**
|
|
341
|
+
* The operators one field takes over HTTP, matching what `WhereOf` types.
|
|
342
|
+
*/
|
|
343
|
+
const operatorsOf = (field) => {
|
|
344
|
+
if ("many" in field && field.many === true) {
|
|
345
|
+
const element = schemaOf({
|
|
346
|
+
...field,
|
|
347
|
+
many: false
|
|
348
|
+
});
|
|
349
|
+
return z.strictObject({
|
|
350
|
+
contains: element.optional(),
|
|
351
|
+
hasAll: z.array(element).max(100).optional(),
|
|
352
|
+
in: z.array(element).max(100).optional(),
|
|
353
|
+
exists: z.boolean().optional()
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
switch (field.type) {
|
|
357
|
+
case "image":
|
|
358
|
+
case "file": return z.strictObject({ exists: z.boolean().optional() });
|
|
359
|
+
case "number":
|
|
360
|
+
case "date":
|
|
361
|
+
case "dateTime": return z.strictObject({
|
|
362
|
+
...valueOperatorsOf(schemaOf(field)),
|
|
363
|
+
...rangeOperatorsOf(schemaOf(field))
|
|
364
|
+
});
|
|
365
|
+
case "text":
|
|
366
|
+
case "slug":
|
|
367
|
+
case "url":
|
|
368
|
+
case "email": return z.strictObject({
|
|
369
|
+
...valueOperatorsOf(TextSchema),
|
|
370
|
+
contains: TextSchema.optional()
|
|
371
|
+
});
|
|
372
|
+
case "boolean": return z.strictObject({
|
|
373
|
+
equals: z.boolean().optional(),
|
|
374
|
+
not: z.boolean().optional(),
|
|
375
|
+
exists: z.boolean().optional()
|
|
376
|
+
});
|
|
377
|
+
default: return z.strictObject(valueOperatorsOf(schemaOf(field)));
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
const whereSchemas = /* @__PURE__ */ new WeakMap();
|
|
381
|
+
/**
|
|
382
|
+
* The schema of a list's `where`, which answers 400 to an unknown field or operator, to a list longer than
|
|
383
|
+
* {@link MAX_WHERE_LIST_LENGTH}, and to a value its field can't hold, like text with the NUL character.
|
|
384
|
+
*/
|
|
385
|
+
const whereSchemaOf = (collection) => {
|
|
386
|
+
const existing = whereSchemas.get(collection);
|
|
387
|
+
if (existing !== void 0) return existing;
|
|
388
|
+
const fields = {};
|
|
389
|
+
for (const field of collection.fields) {
|
|
390
|
+
const operators = operatorsOf(field);
|
|
391
|
+
if (operators !== void 0) fields[field.name] = operators.optional();
|
|
392
|
+
}
|
|
393
|
+
const WhereSchema = Kizuna$1.model({
|
|
394
|
+
title: `${modelNameOf(collection)}Where`,
|
|
395
|
+
schema: z.strictObject({
|
|
396
|
+
...fields,
|
|
397
|
+
get and() {
|
|
398
|
+
return z.array(WhereSchema).max(100).optional();
|
|
399
|
+
},
|
|
400
|
+
get or() {
|
|
401
|
+
return z.array(WhereSchema).max(100).optional();
|
|
402
|
+
}
|
|
403
|
+
})
|
|
404
|
+
});
|
|
405
|
+
whereSchemas.set(collection, WhereSchema);
|
|
406
|
+
return WhereSchema;
|
|
407
|
+
};
|
|
408
|
+
//#endregion
|
|
409
|
+
//#region src/runtime-route.ts
|
|
410
|
+
const k$1 = new Kizuna$1();
|
|
411
|
+
/**
|
|
412
|
+
* `k.route` without the app's `Config`, since the CMS builds its routes from definitions at runtime.
|
|
413
|
+
*/
|
|
414
|
+
const route = k$1.route;
|
|
415
|
+
/**
|
|
416
|
+
* Files routes built at runtime under a group and a subgroup, as `k.routes.<group>.<name>(routes)` does.
|
|
417
|
+
*/
|
|
418
|
+
const groupedRoutes = (group, name, routes) => {
|
|
419
|
+
return k$1.routes[group][name](routes);
|
|
420
|
+
};
|
|
421
|
+
//#endregion
|
|
422
|
+
//#region src/routes.ts
|
|
423
|
+
/**
|
|
424
|
+
* The group every collection's routes are filed under.
|
|
425
|
+
*/
|
|
426
|
+
const COLLECTIONS_GROUP = "collections";
|
|
427
|
+
/**
|
|
428
|
+
* The 409 for a document another one still points at.
|
|
429
|
+
*/
|
|
430
|
+
const inUseConflict = (use) => conflict(`The document is still used by '${use.field}' in '${use.collection ?? use.global}'. Remove it there first.`);
|
|
431
|
+
const conflict = (detail) => ({
|
|
432
|
+
status: 409,
|
|
433
|
+
body: {
|
|
434
|
+
type: "about:blank",
|
|
435
|
+
title: "Conflict",
|
|
436
|
+
status: 409,
|
|
437
|
+
detail
|
|
438
|
+
}
|
|
439
|
+
});
|
|
440
|
+
const slugFieldsOf = (collection) => collection.fields.filter((field) => field.type === "slug");
|
|
441
|
+
const isSlugTaken = async (db, collection, field, slug, id) => {
|
|
442
|
+
const { items } = await db.list(collection.name, {
|
|
443
|
+
offset: 0,
|
|
444
|
+
limit: 2
|
|
445
|
+
}, { where: { [field]: { equals: slug } } });
|
|
446
|
+
return items.some((item) => item.id !== id);
|
|
447
|
+
};
|
|
448
|
+
/**
|
|
449
|
+
* Gives each slug the CMS filled in that another document has the first free ending of `-2`, `-3` and on.
|
|
450
|
+
*/
|
|
451
|
+
const withUniqueGeneratedSlugs = async (db, collection, body, values) => {
|
|
452
|
+
const freed = { ...values };
|
|
453
|
+
for (const field of slugFieldsOf(collection)) {
|
|
454
|
+
const made = freed[field.name];
|
|
455
|
+
if (!isGeneratedSlug(field) || body[field.name] !== void 0 && body[field.name] !== "" || typeof made !== "string") continue;
|
|
456
|
+
if (made.length > 200) continue;
|
|
457
|
+
freed[field.name] = await freeSlugOf(db, collection, field.name, made);
|
|
458
|
+
}
|
|
459
|
+
return freed;
|
|
460
|
+
};
|
|
461
|
+
/**
|
|
462
|
+
* How many candidate slugs one read checks when it looks for a free ending.
|
|
463
|
+
*/
|
|
464
|
+
const SLUG_CANDIDATES_PER_READ = 100;
|
|
465
|
+
/**
|
|
466
|
+
* The made slug itself for ending 1, and otherwise with an ending of `-2`, `-3` and on.
|
|
467
|
+
*/
|
|
468
|
+
const slugCandidateOf = (made, ending) => ending === 1 ? made : `${made}-${ending}`;
|
|
469
|
+
/**
|
|
470
|
+
* The first slug from {@link slugCandidateOf} no document has, checking {@link SLUG_CANDIDATES_PER_READ} of them per
|
|
471
|
+
* read.
|
|
472
|
+
*/
|
|
473
|
+
const freeSlugOf = async (db, collection, field, made) => {
|
|
474
|
+
for (let first = 1;; first += SLUG_CANDIDATES_PER_READ) {
|
|
475
|
+
const candidates = Array.from({ length: SLUG_CANDIDATES_PER_READ }, (_, index) => slugCandidateOf(made, first + index));
|
|
476
|
+
const { items } = await db.list(collection.name, {
|
|
477
|
+
offset: 0,
|
|
478
|
+
limit: SLUG_CANDIDATES_PER_READ
|
|
479
|
+
}, { where: { [field]: { in: candidates } } });
|
|
480
|
+
const taken = new Set(items.map((item) => item[field]));
|
|
481
|
+
const free = candidates.find((candidate) => !taken.has(candidate));
|
|
482
|
+
if (free !== void 0) return free;
|
|
483
|
+
}
|
|
484
|
+
};
|
|
485
|
+
/**
|
|
486
|
+
* The 422 for a slug the CMS made that comes out longer than {@link MAX_SLUG_LENGTH}, with or without its ending, or
|
|
487
|
+
* `undefined` when every made slug fits.
|
|
488
|
+
*/
|
|
489
|
+
const longSlugProblemOf = (collection, values) => {
|
|
490
|
+
for (const field of slugFieldsOf(collection)) {
|
|
491
|
+
const slug = values[field.name];
|
|
492
|
+
if (!isGeneratedSlug(field) || typeof slug !== "string" || slug.length <= 200) continue;
|
|
493
|
+
const from = typeof field.generateFrom === "string" ? `'${field.generateFrom}'` : "the document’s values";
|
|
494
|
+
return unprocessable(`'${field.name}' is made from ${from}, and comes out longer than 200 characters. Write a shorter slug.`);
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
/**
|
|
498
|
+
* The 409 for a slug another document has, or `undefined` when every slug is free.
|
|
499
|
+
*/
|
|
500
|
+
const slugConflictOf = async (db, collection, values, id) => {
|
|
501
|
+
for (const field of slugFieldsOf(collection)) {
|
|
502
|
+
const slug = values[field.name];
|
|
503
|
+
if (typeof slug !== "string" || slug === "") continue;
|
|
504
|
+
if (await isSlugTaken(db, collection, field.name, slug, id)) return conflict(`Another document has the ${field.name} '${slug}'.`);
|
|
505
|
+
}
|
|
506
|
+
};
|
|
507
|
+
/**
|
|
508
|
+
* Runs a write, answering a {@link ConflictError} with a 409.
|
|
509
|
+
*/
|
|
510
|
+
const writeOrConflict = async (write) => {
|
|
511
|
+
try {
|
|
512
|
+
return await write();
|
|
513
|
+
} catch (error) {
|
|
514
|
+
if (error instanceof ConflictError) return conflict(error.message);
|
|
515
|
+
throw error;
|
|
516
|
+
}
|
|
517
|
+
};
|
|
518
|
+
/**
|
|
519
|
+
* The first place a document is still used, or `undefined` when nothing points at it.
|
|
520
|
+
*/
|
|
521
|
+
const firstUseOf$1 = async (db, uses, id) => {
|
|
522
|
+
for (const use of uses) {
|
|
523
|
+
if (use.global !== void 0) {
|
|
524
|
+
const value = (await db.getGlobal(use.global))?.[use.field];
|
|
525
|
+
if (value === id || Array.isArray(value) && value.includes(id)) return use;
|
|
526
|
+
continue;
|
|
527
|
+
}
|
|
528
|
+
const { total } = await db.list(use.collection, {
|
|
529
|
+
offset: 0,
|
|
530
|
+
limit: 1
|
|
531
|
+
}, { where: { [use.field]: use.many ? { contains: id } : { equals: id } } });
|
|
532
|
+
if (total > 0) return use;
|
|
533
|
+
}
|
|
534
|
+
};
|
|
535
|
+
/**
|
|
536
|
+
* The keys a list can sort by: `createdAt`, `updatedAt` and every single-value field, each also with `-` to reverse.
|
|
537
|
+
*/
|
|
538
|
+
const sortableKeysOf = (collection) => [
|
|
539
|
+
"createdAt",
|
|
540
|
+
"updatedAt",
|
|
541
|
+
...collection.fields.filter((field) => columnOf(field) !== "json").map((field) => field.name)
|
|
542
|
+
].flatMap((name) => [name, `-${name}`]);
|
|
543
|
+
/**
|
|
544
|
+
* A list's query string: the page, the ids to read, the order and the `where`.
|
|
545
|
+
*/
|
|
546
|
+
const listQuerySchemaOf = (collection) => z.object({
|
|
547
|
+
offset: z.int().min(0).default(0),
|
|
548
|
+
limit: z.int().min(1).max(100).default(20),
|
|
549
|
+
ids: z.array(TextSchema).max(100).optional().describe("Only the documents with these ids."),
|
|
550
|
+
sort: z.array(z.enum(sortableKeysOf(collection))).optional().describe("Fields to sort by. `-` in front reverses one."),
|
|
551
|
+
where: whereSchemaOf(collection).optional().describe("Which documents to read. Every field named must match. `and` and `or` take lists of the same.")
|
|
552
|
+
});
|
|
553
|
+
/**
|
|
554
|
+
* The page and read options from a list's query.
|
|
555
|
+
*/
|
|
556
|
+
const pageAndOptionsOf = (query) => ({
|
|
557
|
+
page: {
|
|
558
|
+
offset: query.offset,
|
|
559
|
+
limit: query.ids === void 0 ? query.limit : Math.max(query.limit, query.ids.length)
|
|
560
|
+
},
|
|
561
|
+
options: {
|
|
562
|
+
...query.ids === void 0 ? {} : { ids: query.ids },
|
|
563
|
+
...query.sort === void 0 ? {} : { sort: query.sort },
|
|
564
|
+
...query.where === void 0 ? {} : { where: query.where }
|
|
565
|
+
}
|
|
566
|
+
});
|
|
567
|
+
const IdParamsSchema = z.object({ id: TextSchema });
|
|
568
|
+
/**
|
|
569
|
+
* The id of the editor making a request, when one is logged in.
|
|
570
|
+
*/
|
|
571
|
+
const editorIdOf = (auth) => {
|
|
572
|
+
const id = (auth?.["editor"])?.id;
|
|
573
|
+
return typeof id === "string" ? id : void 0;
|
|
574
|
+
};
|
|
575
|
+
const notFound = (collection, id) => ({
|
|
576
|
+
status: 404,
|
|
577
|
+
body: {
|
|
578
|
+
type: "about:blank",
|
|
579
|
+
title: "Not Found",
|
|
580
|
+
status: 404,
|
|
581
|
+
detail: `No document in '${collection.name}' has the id '${id}'.`
|
|
582
|
+
}
|
|
583
|
+
});
|
|
584
|
+
const forbidden = (collection, id) => ({
|
|
585
|
+
status: 403,
|
|
586
|
+
body: {
|
|
587
|
+
type: "about:blank",
|
|
588
|
+
title: "Forbidden",
|
|
589
|
+
status: 403,
|
|
590
|
+
detail: `You hold no role that may change the document '${id}' in '${collection.name}'.`
|
|
591
|
+
}
|
|
592
|
+
});
|
|
593
|
+
/**
|
|
594
|
+
* The 403 for a caller who may change a document only because one of its fields names them, and who tries to change
|
|
595
|
+
* that field.
|
|
596
|
+
*/
|
|
597
|
+
const forbiddenField = (collection, id, field) => ({
|
|
598
|
+
status: 403,
|
|
599
|
+
body: {
|
|
600
|
+
type: "about:blank",
|
|
601
|
+
title: "Forbidden",
|
|
602
|
+
status: 403,
|
|
603
|
+
detail: `You may change the document '${id}' in '${collection.name}' because '${field}' names you, so you may not change '${field}'.`
|
|
604
|
+
}
|
|
605
|
+
});
|
|
606
|
+
/**
|
|
607
|
+
* A stored document or global with only the keys its fields and `keys` name. A value kept under a field the app has
|
|
608
|
+
* since removed stays out of every answer.
|
|
609
|
+
*/
|
|
610
|
+
const withDeclaredKeys = (definition, keys, document) => {
|
|
611
|
+
const declared = new Set([...keys, ...definition.fields.map((field) => field.name)]);
|
|
612
|
+
return Object.fromEntries(Object.entries(document).filter(([key]) => declared.has(key)));
|
|
613
|
+
};
|
|
614
|
+
/**
|
|
615
|
+
* The keys every document of a collection answers with beside its fields.
|
|
616
|
+
*/
|
|
617
|
+
const documentKeysOf = (collection) => [
|
|
618
|
+
"id",
|
|
619
|
+
"createdAt",
|
|
620
|
+
"updatedAt",
|
|
621
|
+
"createdBy",
|
|
622
|
+
"updatedBy",
|
|
623
|
+
...collection.meta === void 0 ? [] : ["meta"]
|
|
624
|
+
];
|
|
625
|
+
const declaredDocumentsOf = (collection, documents) => documents.map((document) => withDeclaredKeys(collection, documentKeysOf(collection), document));
|
|
626
|
+
/**
|
|
627
|
+
* A document with only its declared keys, and its image and file fields resolved to the files.
|
|
628
|
+
*/
|
|
629
|
+
const resolveDocument = async (db, collection, document) => (await resolveDocuments(db, collection, declaredDocumentsOf(collection, [document])))[0];
|
|
630
|
+
const resolvePage = async (db, collection, page) => ({
|
|
631
|
+
...page,
|
|
632
|
+
items: await resolveDocuments(db, collection, declaredDocumentsOf(collection, page.items))
|
|
633
|
+
});
|
|
634
|
+
/**
|
|
635
|
+
* What the hidden route answers about who made and last changed a document or a global.
|
|
636
|
+
*/
|
|
637
|
+
const EditorReferencesSchema = z.object({
|
|
638
|
+
createdBy: EditorReferenceSchema.optional(),
|
|
639
|
+
updatedBy: EditorReferenceSchema.optional()
|
|
640
|
+
});
|
|
641
|
+
/**
|
|
642
|
+
* The `auth` of the hidden route that names a document's editors: any logged-in editor when anyone may read it, and
|
|
643
|
+
* otherwise whoever may.
|
|
644
|
+
*/
|
|
645
|
+
const editorsRouteAuthOf = (read) => read.kind === "public" ? EDITOR_IDENTITY : routeAuthOf(read);
|
|
646
|
+
/**
|
|
647
|
+
* The 422 for a write whose values don't hold up, like a file missing from its store.
|
|
648
|
+
*/
|
|
649
|
+
const unprocessable = (detail) => ({
|
|
650
|
+
status: 422,
|
|
651
|
+
body: {
|
|
652
|
+
type: "about:blank",
|
|
653
|
+
title: "Unprocessable Content",
|
|
654
|
+
status: 422,
|
|
655
|
+
detail
|
|
656
|
+
}
|
|
657
|
+
});
|
|
658
|
+
/**
|
|
659
|
+
* The 422 a write declares when its collection has files, a meta image or a slug the CMS fills in.
|
|
660
|
+
*/
|
|
661
|
+
const unprocessableResponsesOf = (collection) => collection.fields.some(isFileField) || metaImageStoreOf(collection) !== void 0 || collection.fields.some(isGeneratedSlug) ? { 422: ProblemDetailsSchema } : {};
|
|
662
|
+
/**
|
|
663
|
+
* The 409 a write declares when its collection has a slug or a relationship.
|
|
664
|
+
*/
|
|
665
|
+
const conflictResponsesOf = (collection, always = false) => always || slugFieldsOf(collection).length > 0 || collection.fields.some((field) => field.type === "relationship") ? { 409: ProblemDetailsSchema } : {};
|
|
666
|
+
/**
|
|
667
|
+
* The routes that read and write one collection's documents, leaving out the actions nobody may do.
|
|
668
|
+
*/
|
|
669
|
+
const collectionRoutes = (collection, options) => {
|
|
670
|
+
const { db, access, basePath, accounts } = options;
|
|
671
|
+
const uses = options.pointedAtBy ?? [];
|
|
672
|
+
const DocumentSchema = collection.schema;
|
|
673
|
+
const ListQuerySchema = listQuerySchemaOf(collection);
|
|
674
|
+
const collectionPath = `${basePath}/${collection.name}`;
|
|
675
|
+
const { singular, plural } = labelsOf(collection);
|
|
676
|
+
const isPublicRead = access.read.kind === "public";
|
|
677
|
+
const routes = { ...accounts?.routes };
|
|
678
|
+
if (access.read.kind !== "nobody") {
|
|
679
|
+
routes["list"] = route({
|
|
680
|
+
method: "GET",
|
|
681
|
+
path: collectionPath,
|
|
682
|
+
summary: `List ${plural}`,
|
|
683
|
+
auth: routeAuthOf(access.read),
|
|
684
|
+
query: ListQuerySchema,
|
|
685
|
+
responses: { 200: {
|
|
686
|
+
body: z.object({
|
|
687
|
+
items: z.array(DocumentSchema),
|
|
688
|
+
total: z.int()
|
|
689
|
+
}),
|
|
690
|
+
cache: readCacheOf(access.read),
|
|
691
|
+
etag: true
|
|
692
|
+
} },
|
|
693
|
+
tool: toolOf(collection.tools, "read")
|
|
694
|
+
}).handler(async ({ query }) => {
|
|
695
|
+
const { page, options } = pageAndOptionsOf(query);
|
|
696
|
+
const resolved = await resolvePage(db, collection, await db.list(collection.name, page, options));
|
|
697
|
+
return {
|
|
698
|
+
status: 200,
|
|
699
|
+
body: isPublicRead ? {
|
|
700
|
+
...resolved,
|
|
701
|
+
items: resolved.items.map(withoutEditorReferences)
|
|
702
|
+
} : resolved
|
|
703
|
+
};
|
|
704
|
+
});
|
|
705
|
+
routes["get"] = route({
|
|
706
|
+
method: "GET",
|
|
707
|
+
path: `${collectionPath}/:id`,
|
|
708
|
+
summary: `Get ${singular}`,
|
|
709
|
+
auth: routeAuthOf(access.read),
|
|
710
|
+
pathParams: IdParamsSchema,
|
|
711
|
+
responses: {
|
|
712
|
+
200: {
|
|
713
|
+
body: DocumentSchema,
|
|
714
|
+
cache: readCacheOf(access.read),
|
|
715
|
+
etag: true
|
|
716
|
+
},
|
|
717
|
+
404: ProblemDetailsSchema
|
|
718
|
+
},
|
|
719
|
+
tool: toolOf(collection.tools, "read")
|
|
720
|
+
}).handler(async ({ params }) => {
|
|
721
|
+
const document = await db.get(collection.name, params.id);
|
|
722
|
+
if (document === void 0) return notFound(collection, params.id);
|
|
723
|
+
const resolved = await resolveDocument(db, collection, document);
|
|
724
|
+
return {
|
|
725
|
+
status: 200,
|
|
726
|
+
body: isPublicRead ? withoutEditorReferences(resolved) : resolved
|
|
727
|
+
};
|
|
728
|
+
});
|
|
729
|
+
routes["editors"] = route({
|
|
730
|
+
method: "GET",
|
|
731
|
+
path: `${collectionPath}/:id/editors`,
|
|
732
|
+
summary: `Who made and last changed ${singular}`,
|
|
733
|
+
auth: editorsRouteAuthOf(access.read),
|
|
734
|
+
hidden: true,
|
|
735
|
+
pathParams: IdParamsSchema,
|
|
736
|
+
responses: {
|
|
737
|
+
200: {
|
|
738
|
+
body: EditorReferencesSchema,
|
|
739
|
+
cache: "no-store"
|
|
740
|
+
},
|
|
741
|
+
404: ProblemDetailsSchema
|
|
742
|
+
}
|
|
743
|
+
}).handler(async ({ params }) => {
|
|
744
|
+
const document = await db.get(collection.name, params.id);
|
|
745
|
+
return document === void 0 ? notFound(collection, params.id) : {
|
|
746
|
+
status: 200,
|
|
747
|
+
body: await editorReferencesOf(db, document)
|
|
748
|
+
};
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
if (access.create.kind !== "nobody") routes["create"] = route({
|
|
752
|
+
method: "POST",
|
|
753
|
+
path: collectionPath,
|
|
754
|
+
summary: `Create ${singular}`,
|
|
755
|
+
auth: routeAuthOf(access.create),
|
|
756
|
+
body: createSchemaOf(collection).extend(accounts?.shape ?? {}),
|
|
757
|
+
responses: {
|
|
758
|
+
201: DocumentSchema,
|
|
759
|
+
...unprocessableResponsesOf(collection),
|
|
760
|
+
...conflictResponsesOf(collection, accounts !== void 0)
|
|
761
|
+
},
|
|
762
|
+
tool: toolOf(collection.tools, "create")
|
|
763
|
+
}).handler(async ({ body, auth }) => {
|
|
764
|
+
const problem = await fileProblemOf(db, collection.fields, body) ?? await metaImageProblemOf(db, collection, body);
|
|
765
|
+
if (problem !== void 0) return unprocessable(problem);
|
|
766
|
+
const values = await withUniqueGeneratedSlugs(db, collection, body, withGeneratedSlugs(collection, body));
|
|
767
|
+
const missingSlug = collection.fields.find((field) => isGeneratedSlug(field) && field.required === true && !values[field.name]);
|
|
768
|
+
if (missingSlug !== void 0) {
|
|
769
|
+
const from = missingSlug.generateFrom;
|
|
770
|
+
return unprocessable(typeof from === "string" ? `'${missingSlug.name}' is required, and is made from '${from}', which is empty.` : `'${missingSlug.name}' is required, and the document's values make no slug.`);
|
|
771
|
+
}
|
|
772
|
+
const long = longSlugProblemOf(collection, values);
|
|
773
|
+
if (long !== void 0) return long;
|
|
774
|
+
const taken = await slugConflictOf(db, collection, values);
|
|
775
|
+
if (taken !== void 0) return taken;
|
|
776
|
+
const checked = accounts === void 0 ? void 0 : await accounts.checkWrite(void 0, values, auth);
|
|
777
|
+
if (checked !== void 0 && "status" in checked) return checked;
|
|
778
|
+
const created = await writeOrConflict(() => db.create(collection.name, checked?.values ?? values, editorIdOf(auth)));
|
|
779
|
+
if ("status" in created) return created;
|
|
780
|
+
await checked?.after(created);
|
|
781
|
+
return {
|
|
782
|
+
status: 201,
|
|
783
|
+
body: await resolveDocument(db, collection, created)
|
|
784
|
+
};
|
|
785
|
+
});
|
|
786
|
+
if (access.update.kind !== "nobody") routes["update"] = route({
|
|
787
|
+
method: "PATCH",
|
|
788
|
+
path: `${collectionPath}/:id`,
|
|
789
|
+
summary: `Change ${singular}`,
|
|
790
|
+
auth: routeAuthOf(access.update),
|
|
791
|
+
pathParams: IdParamsSchema,
|
|
792
|
+
body: updateSchemaOf(collection).extend(accounts?.shape ?? {}),
|
|
793
|
+
responses: {
|
|
794
|
+
200: DocumentSchema,
|
|
795
|
+
404: ProblemDetailsSchema,
|
|
796
|
+
...unprocessableResponsesOf(collection),
|
|
797
|
+
...conflictResponsesOf(collection, accounts !== void 0)
|
|
798
|
+
},
|
|
799
|
+
tool: toolOf(collection.tools, "update")
|
|
800
|
+
}).handler(async ({ params, body, auth }) => {
|
|
801
|
+
const stored = await db.get(collection.name, params.id);
|
|
802
|
+
const grant = await writeGrantOf(access.update, auth, async () => stored);
|
|
803
|
+
if (grant === "none") return forbidden(collection, params.id);
|
|
804
|
+
const handedOver = grant === "document" ? changedDocumentFieldOf(access.update, body, stored) : void 0;
|
|
805
|
+
if (handedOver !== void 0) return forbiddenField(collection, params.id, handedOver);
|
|
806
|
+
const problem = await fileProblemOf(db, collection.fields, body) ?? await metaImageProblemOf(db, collection, body);
|
|
807
|
+
if (problem !== void 0) return unprocessable(problem);
|
|
808
|
+
const change = mergeMetaChange(body, stored);
|
|
809
|
+
const taken = await slugConflictOf(db, collection, change, params.id);
|
|
810
|
+
if (taken !== void 0) return taken;
|
|
811
|
+
if (stored === void 0) return notFound(collection, params.id);
|
|
812
|
+
const checked = accounts === void 0 ? void 0 : await accounts.checkWrite(params.id, change, auth);
|
|
813
|
+
if (checked !== void 0 && "status" in checked) return checked;
|
|
814
|
+
const document = await writeOrConflict(() => db.update(collection.name, params.id, checked?.values ?? change, editorIdOf(auth)));
|
|
815
|
+
if (document !== void 0 && "status" in document) return document;
|
|
816
|
+
if (document === void 0) return notFound(collection, params.id);
|
|
817
|
+
await checked?.after(document);
|
|
818
|
+
return {
|
|
819
|
+
status: 200,
|
|
820
|
+
body: await resolveDocument(db, collection, document)
|
|
821
|
+
};
|
|
822
|
+
});
|
|
823
|
+
if (collection.meta !== void 0 && access.update.kind !== "nobody") routes["ownMeta"] = route({
|
|
824
|
+
method: "GET",
|
|
825
|
+
path: `${collectionPath}/:id/meta`,
|
|
826
|
+
summary: `What editors wrote for ${singular}'s search result`,
|
|
827
|
+
auth: routeAuthOf(access.update),
|
|
828
|
+
hidden: true,
|
|
829
|
+
pathParams: IdParamsSchema,
|
|
830
|
+
responses: {
|
|
831
|
+
200: WrittenMetaSchema,
|
|
832
|
+
404: ProblemDetailsSchema
|
|
833
|
+
}
|
|
834
|
+
}).handler(async ({ params, auth }) => {
|
|
835
|
+
const document = await db.get(collection.name, params.id);
|
|
836
|
+
if (document === void 0 || !await mayWriteDocument(access.update, auth, async () => document)) return notFound(collection, params.id);
|
|
837
|
+
return {
|
|
838
|
+
status: 200,
|
|
839
|
+
body: writtenMetaOf(document)
|
|
840
|
+
};
|
|
841
|
+
});
|
|
842
|
+
if (access.delete.kind !== "nobody") routes["delete"] = route({
|
|
843
|
+
method: "DELETE",
|
|
844
|
+
path: `${collectionPath}/:id`,
|
|
845
|
+
summary: `Delete ${singular}`,
|
|
846
|
+
auth: routeAuthOf(access.delete),
|
|
847
|
+
pathParams: IdParamsSchema,
|
|
848
|
+
responses: {
|
|
849
|
+
204: z.void(),
|
|
850
|
+
404: ProblemDetailsSchema,
|
|
851
|
+
...uses.length === 0 && accounts === void 0 ? {} : { 409: ProblemDetailsSchema }
|
|
852
|
+
},
|
|
853
|
+
tool: toolOf(collection.tools, "delete")
|
|
854
|
+
}).handler(async ({ params, auth }) => {
|
|
855
|
+
if (!await mayWriteDocument(access.delete, auth, () => db.get(collection.name, params.id))) return forbidden(collection, params.id);
|
|
856
|
+
const use = await firstUseOf$1(db, uses, params.id);
|
|
857
|
+
if (use !== void 0) return inUseConflict(use);
|
|
858
|
+
const refusal = await accounts?.checkDelete(params.id);
|
|
859
|
+
if (refusal !== void 0) return refusal;
|
|
860
|
+
const deleted = await writeOrConflict(() => db.delete(collection.name, params.id));
|
|
861
|
+
if (typeof deleted !== "boolean") return deleted;
|
|
862
|
+
return deleted ? { status: 204 } : notFound(collection, params.id);
|
|
863
|
+
});
|
|
864
|
+
return groupedRoutes(collection.group ?? "collections", collection.name, routes);
|
|
865
|
+
};
|
|
866
|
+
//#endregion
|
|
867
|
+
//#region src/editors.ts
|
|
868
|
+
/**
|
|
869
|
+
* The password an account has now, which a new email or password on your own account needs.
|
|
870
|
+
*/
|
|
871
|
+
const CurrentPasswordSchema = z.string().max(256).optional().describe("Needed to change your own email or password.");
|
|
872
|
+
/**
|
|
873
|
+
* Fields the CMS keeps on a login collection itself.
|
|
874
|
+
*/
|
|
875
|
+
const RESERVED_ACCOUNT_FIELDS = [
|
|
876
|
+
"email",
|
|
877
|
+
"password",
|
|
878
|
+
"roles"
|
|
879
|
+
];
|
|
880
|
+
/**
|
|
881
|
+
* A login collection with the fields the CMS keeps: `email`, and on the admin's collection `roles`.
|
|
882
|
+
*/
|
|
883
|
+
const withAccountFields = (declared, roleNames) => {
|
|
884
|
+
for (const field of declared.fields) if (RESERVED_ACCOUNT_FIELDS.includes(field.name)) throw new Error(`Collection '${declared.name}' logs in, so the CMS keeps its '${field.name}' itself. Rename your field.`);
|
|
885
|
+
if (Array.isArray(declared.auth.read) && declared.auth.read.includes("public")) throw new Error(`Collection '${declared.name}' logs in, so its accounts can't be read without a login. Give \`auth.read\` roles, like ['admin'].`);
|
|
886
|
+
const definition = Object.fromEntries(Object.entries(declared).filter(([key]) => key !== "kind" && key !== "schema"));
|
|
887
|
+
const fields = [
|
|
888
|
+
{
|
|
889
|
+
name: "email",
|
|
890
|
+
type: "email",
|
|
891
|
+
required: true
|
|
892
|
+
},
|
|
893
|
+
...declared.fields,
|
|
894
|
+
...roleNames === void 0 ? [] : [{
|
|
895
|
+
name: "roles",
|
|
896
|
+
type: "select",
|
|
897
|
+
many: true,
|
|
898
|
+
options: roleNames
|
|
899
|
+
}]
|
|
900
|
+
];
|
|
901
|
+
return defineCollection({
|
|
902
|
+
...definition,
|
|
903
|
+
login: declared.login ?? true,
|
|
904
|
+
fields
|
|
905
|
+
});
|
|
906
|
+
};
|
|
907
|
+
/**
|
|
908
|
+
* The identity a login collection's documents log in as: the singular of its name, like `storeUser`.
|
|
909
|
+
*/
|
|
910
|
+
const loginIdentityNameOf = (collection) => pluralize.singular(collection.name);
|
|
911
|
+
/**
|
|
912
|
+
* Nouns that take `an`: `an editor`, `an uploader`, but `a user`.
|
|
913
|
+
*/
|
|
914
|
+
const TAKES_AN = /^(?:[aeio]|u[^aeiou]{2})/;
|
|
915
|
+
/**
|
|
916
|
+
* `a store user`, for a 401.
|
|
917
|
+
*/
|
|
918
|
+
const accountNounOf = (collection) => {
|
|
919
|
+
const noun = labelsOf(collection).singular.toLowerCase();
|
|
920
|
+
return `${TAKES_AN.test(noun) ? "an" : "a"} ${noun}`;
|
|
921
|
+
};
|
|
922
|
+
/**
|
|
923
|
+
* The bearer identity a login collection's documents log in as, which takes only that collection's sessions.
|
|
924
|
+
*/
|
|
925
|
+
const loginIdentityOf = (db, collection, roles) => accountIdentityOf({
|
|
926
|
+
store: db,
|
|
927
|
+
collection: collection.name,
|
|
928
|
+
description: `${labelsOf(collection).singular} of the CMS.`,
|
|
929
|
+
who: accountNounOf(collection),
|
|
930
|
+
...roles === void 0 ? {} : { roles },
|
|
931
|
+
load: async (id) => {
|
|
932
|
+
const account = await db.get(collection.name, id);
|
|
933
|
+
return account === void 0 ? void 0 : {
|
|
934
|
+
id: account.id,
|
|
935
|
+
roles: rolesOf(account)
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
});
|
|
939
|
+
const rolesOf = (document) => Array.isArray(document["roles"]) ? document["roles"].filter((role) => typeof role === "string") : [];
|
|
940
|
+
const problem = (status, title, detail) => ({
|
|
941
|
+
status,
|
|
942
|
+
body: {
|
|
943
|
+
type: "about:blank",
|
|
944
|
+
title,
|
|
945
|
+
status,
|
|
946
|
+
detail
|
|
947
|
+
}
|
|
948
|
+
});
|
|
949
|
+
/**
|
|
950
|
+
* The routes, write checks and editor API of one login collection.
|
|
951
|
+
*/
|
|
952
|
+
const accountsOf = (options) => {
|
|
953
|
+
const { db, collection, identity, isEditorsCollection, basePath } = options;
|
|
954
|
+
const passwordReset = typeof collection.login === "object" ? collection.login.passwordReset : void 0;
|
|
955
|
+
const adminRoles = [ADMIN_ROLE];
|
|
956
|
+
const path = `${basePath}/${collection.name}`;
|
|
957
|
+
const AccountSchema = collection.schema;
|
|
958
|
+
const titleField = collection.titleField;
|
|
959
|
+
const noun = labelsOf(collection).singular.toLowerCase();
|
|
960
|
+
const callerOf = (auth) => auth[identity];
|
|
961
|
+
const adminRule = {
|
|
962
|
+
identity: EDITOR_IDENTITY,
|
|
963
|
+
roles: adminRoles
|
|
964
|
+
};
|
|
965
|
+
const resolveAccount = async (document) => (await resolveDocuments(db, collection, [withDeclaredKeys(collection, documentKeysOf(collection), document)]))[0];
|
|
966
|
+
const notFound = (id) => problem(404, "Not Found", `No ${noun} has the id '${id}'.`);
|
|
967
|
+
const emailTaken = (email) => problem(409, "Conflict", `Another ${noun} has the email '${email}'.`);
|
|
968
|
+
const lastAdmin = () => problem(409, "Conflict", "The CMS needs at least one admin.");
|
|
969
|
+
const findByEmail = async (email) => (await db.list(collection.name, {
|
|
970
|
+
offset: 0,
|
|
971
|
+
limit: 1
|
|
972
|
+
}, { where: { email: { equals: normalizeEmail(email) } } })).items[0];
|
|
973
|
+
const displayNameOf = (document) => {
|
|
974
|
+
const title = titleField === void 0 ? void 0 : document[titleField];
|
|
975
|
+
return typeof title === "string" && title !== "" ? title : String(document["email"]);
|
|
976
|
+
};
|
|
977
|
+
const sendPasswordLink = async (send, document, reason) => {
|
|
978
|
+
const token = await createPasswordLink(db, collection.name, document.id, reason);
|
|
979
|
+
await send.send({
|
|
980
|
+
email: String(document["email"]),
|
|
981
|
+
name: displayNameOf(document),
|
|
982
|
+
token,
|
|
983
|
+
reason
|
|
984
|
+
});
|
|
985
|
+
};
|
|
986
|
+
/**
|
|
987
|
+
* Whether a change leaves no admin, where `next` is the editor's roles after it, or `undefined` on delete.
|
|
988
|
+
*/
|
|
989
|
+
const leavesNoAdmin = async (id, next) => {
|
|
990
|
+
const isAdmin = (held) => held.some((role) => adminRoles.includes(role));
|
|
991
|
+
const { items } = await db.list(collection.name, {
|
|
992
|
+
offset: 0,
|
|
993
|
+
limit: 1e4
|
|
994
|
+
});
|
|
995
|
+
return !items.some((editor) => editor.id === id ? next !== void 0 && isAdmin(next) : isAdmin(rolesOf(editor)));
|
|
996
|
+
};
|
|
997
|
+
const isAdminCaller = (auth) => {
|
|
998
|
+
const role = (auth?.[EDITOR_IDENTITY])?.role;
|
|
999
|
+
return (typeof role === "string" ? [role] : Array.isArray(role) ? role : []).some((each) => adminRoles.includes(each));
|
|
1000
|
+
};
|
|
1001
|
+
/**
|
|
1002
|
+
* Whether `currentPassword` is the account's password. It takes as long when the account has none.
|
|
1003
|
+
*/
|
|
1004
|
+
const isCurrentPassword = async (id, currentPassword) => {
|
|
1005
|
+
const hash = await db.passwordHashOf(collection.name, id);
|
|
1006
|
+
const matches = await verifyPassword(typeof currentPassword === "string" ? currentPassword : "", await hashToCheck(hash));
|
|
1007
|
+
return hash !== void 0 && matches;
|
|
1008
|
+
};
|
|
1009
|
+
/**
|
|
1010
|
+
* Readies an account's values for a write or refuses it, and hashes the password once the document is saved. A new
|
|
1011
|
+
* email or password needs the current password on your own account, and an admin on someone else's.
|
|
1012
|
+
*/
|
|
1013
|
+
const checkWrite = async (id, values, auth) => {
|
|
1014
|
+
const { currentPassword, ...next } = values;
|
|
1015
|
+
const password = typeof next["password"] === "string" ? next["password"] : void 0;
|
|
1016
|
+
delete next["password"];
|
|
1017
|
+
const email = typeof next["email"] === "string" ? normalizeEmail(next["email"]) : void 0;
|
|
1018
|
+
const caller = auth?.[identity];
|
|
1019
|
+
if (id !== void 0) {
|
|
1020
|
+
const stored = email === void 0 ? void 0 : await db.get(collection.name, id);
|
|
1021
|
+
if (password !== void 0 || email !== void 0 && email !== stored?.["email"]) {
|
|
1022
|
+
if (caller?.id === id) {
|
|
1023
|
+
if (!await isCurrentPassword(id, currentPassword)) return problem(400, "Bad Request", "Your current password is wrong.");
|
|
1024
|
+
} else if (!isAdminCaller(auth)) return problem(403, "Forbidden", `Only an admin changes the email or password of another ${noun}.`);
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
if (email !== void 0) {
|
|
1028
|
+
next["email"] = email;
|
|
1029
|
+
const holder = await findByEmail(email);
|
|
1030
|
+
if (holder !== void 0 && holder.id !== id) return emailTaken(email);
|
|
1031
|
+
}
|
|
1032
|
+
if (isEditorsCollection && "roles" in next) {
|
|
1033
|
+
if (!isAdminCaller(auth)) return problem(403, "Forbidden", "Only an admin sets roles.");
|
|
1034
|
+
const nextRoles = Array.isArray(next["roles"]) ? [...new Set(next["roles"])] : [];
|
|
1035
|
+
if (Array.isArray(next["roles"])) next["roles"] = nextRoles;
|
|
1036
|
+
if (id !== void 0 && await leavesNoAdmin(id, nextRoles)) return lastAdmin();
|
|
1037
|
+
}
|
|
1038
|
+
return {
|
|
1039
|
+
values: next,
|
|
1040
|
+
after: async (document) => {
|
|
1041
|
+
if (password !== void 0) await db.setPasswordHash(collection.name, document.id, await hashPassword(password));
|
|
1042
|
+
if (id === void 0) {
|
|
1043
|
+
if (password === void 0 && passwordReset !== void 0) await sendPasswordLink(passwordReset, document, "invite");
|
|
1044
|
+
return;
|
|
1045
|
+
}
|
|
1046
|
+
if (email !== void 0 || password !== void 0) await db.deletePasswordTokensOf(document.id);
|
|
1047
|
+
if (password !== void 0) await db.deleteSessionsOf(document.id, caller?.id === document.id ? caller.session : void 0);
|
|
1048
|
+
}
|
|
1049
|
+
};
|
|
1050
|
+
};
|
|
1051
|
+
const routes = {
|
|
1052
|
+
login: route({
|
|
1053
|
+
method: "POST",
|
|
1054
|
+
path: `${path}/login`,
|
|
1055
|
+
summary: `Log in as ${accountNounOf(collection)}`,
|
|
1056
|
+
auth: false,
|
|
1057
|
+
body: z.object({
|
|
1058
|
+
email: z.email().max(254),
|
|
1059
|
+
password: z.string().min(1).max(256)
|
|
1060
|
+
}),
|
|
1061
|
+
responses: {
|
|
1062
|
+
200: {
|
|
1063
|
+
body: z.object({
|
|
1064
|
+
token: z.string().describe("Lasts 30 days."),
|
|
1065
|
+
[identity]: AccountSchema
|
|
1066
|
+
}),
|
|
1067
|
+
cache: "no-store"
|
|
1068
|
+
},
|
|
1069
|
+
401: ProblemDetailsSchema,
|
|
1070
|
+
429: ProblemDetailsSchema
|
|
1071
|
+
},
|
|
1072
|
+
tool: false
|
|
1073
|
+
}).handler(async ({ body }) => {
|
|
1074
|
+
const email = normalizeEmail(body.email);
|
|
1075
|
+
if (await isOverLoginLimit(db, collection.name, email)) return problem(429, "Too Many Requests", "Too many failed logins. Try again in 15 minutes.");
|
|
1076
|
+
const document = await findByEmail(email);
|
|
1077
|
+
const hash = document === void 0 ? void 0 : await db.passwordHashOf(collection.name, document.id);
|
|
1078
|
+
const matches = await verifyPassword(body.password, await hashToCheck(hash));
|
|
1079
|
+
if (document === void 0 || hash === void 0 || !matches) return problem(401, "Unauthorized", "Wrong email or password.");
|
|
1080
|
+
await db.clearFailedLogins(collection.name, email);
|
|
1081
|
+
return {
|
|
1082
|
+
status: 200,
|
|
1083
|
+
body: {
|
|
1084
|
+
token: await startSession(db, collection.name, document.id),
|
|
1085
|
+
[identity]: await resolveAccount(document)
|
|
1086
|
+
}
|
|
1087
|
+
};
|
|
1088
|
+
}),
|
|
1089
|
+
logout: route({
|
|
1090
|
+
method: "POST",
|
|
1091
|
+
path: `${path}/logout`,
|
|
1092
|
+
summary: "Log out, ending this session",
|
|
1093
|
+
auth: identity,
|
|
1094
|
+
responses: { 204: z.void() },
|
|
1095
|
+
tool: false
|
|
1096
|
+
}).handler(async ({ auth }) => {
|
|
1097
|
+
await db.deleteSession(callerOf(auth).session);
|
|
1098
|
+
return { status: 204 };
|
|
1099
|
+
}),
|
|
1100
|
+
me: route({
|
|
1101
|
+
method: "GET",
|
|
1102
|
+
path: `${path}/me`,
|
|
1103
|
+
summary: `Get the logged-in ${noun}`,
|
|
1104
|
+
auth: identity,
|
|
1105
|
+
responses: {
|
|
1106
|
+
200: {
|
|
1107
|
+
body: AccountSchema,
|
|
1108
|
+
cache: "no-store"
|
|
1109
|
+
},
|
|
1110
|
+
404: ProblemDetailsSchema
|
|
1111
|
+
},
|
|
1112
|
+
tool: false
|
|
1113
|
+
}).handler(async ({ auth }) => {
|
|
1114
|
+
const document = await db.get(collection.name, callerOf(auth).id);
|
|
1115
|
+
return document === void 0 ? notFound(callerOf(auth).id) : {
|
|
1116
|
+
status: 200,
|
|
1117
|
+
body: await resolveAccount(document)
|
|
1118
|
+
};
|
|
1119
|
+
}),
|
|
1120
|
+
updateMe: route({
|
|
1121
|
+
method: "PATCH",
|
|
1122
|
+
path: `${path}/me`,
|
|
1123
|
+
summary: `Change the logged-in ${noun}`,
|
|
1124
|
+
description: "Never the roles. A new email or password needs the current one. A new password ends your other sessions.",
|
|
1125
|
+
auth: identity,
|
|
1126
|
+
body: (isEditorsCollection ? updateSchemaOf(collection).omit({ roles: true }) : updateSchemaOf(collection)).extend({
|
|
1127
|
+
password: PasswordSchema.optional(),
|
|
1128
|
+
currentPassword: CurrentPasswordSchema
|
|
1129
|
+
}),
|
|
1130
|
+
responses: {
|
|
1131
|
+
200: AccountSchema,
|
|
1132
|
+
400: ProblemDetailsSchema,
|
|
1133
|
+
404: ProblemDetailsSchema,
|
|
1134
|
+
409: ProblemDetailsSchema,
|
|
1135
|
+
422: ProblemDetailsSchema
|
|
1136
|
+
},
|
|
1137
|
+
tool: false
|
|
1138
|
+
}).handler(async ({ auth, body }) => {
|
|
1139
|
+
const caller = callerOf(auth);
|
|
1140
|
+
if (await db.get(collection.name, caller.id) === void 0) return notFound(caller.id);
|
|
1141
|
+
const unusable = await fileProblemOf(db, collection.fields, body);
|
|
1142
|
+
if (unusable !== void 0) return problem(400, "Bad Request", unusable);
|
|
1143
|
+
const checked = await checkWrite(caller.id, body, auth);
|
|
1144
|
+
if ("status" in checked) return checked;
|
|
1145
|
+
const document = await db.update(collection.name, caller.id, checked.values, caller.id);
|
|
1146
|
+
if (document === void 0) return notFound(caller.id);
|
|
1147
|
+
await checked.after(document);
|
|
1148
|
+
return {
|
|
1149
|
+
status: 200,
|
|
1150
|
+
body: await resolveAccount(document)
|
|
1151
|
+
};
|
|
1152
|
+
})
|
|
1153
|
+
};
|
|
1154
|
+
const SessionSchema = z.object({
|
|
1155
|
+
token: z.string().describe("Lasts 30 days."),
|
|
1156
|
+
[identity]: AccountSchema
|
|
1157
|
+
});
|
|
1158
|
+
if (isEditorsCollection) routes["setupNeeded"] = route({
|
|
1159
|
+
method: "GET",
|
|
1160
|
+
path: `${path}/setup`,
|
|
1161
|
+
summary: "Whether the CMS still needs its first account",
|
|
1162
|
+
auth: false,
|
|
1163
|
+
responses: { 200: {
|
|
1164
|
+
body: z.object({ needed: z.boolean() }),
|
|
1165
|
+
cache: "no-store"
|
|
1166
|
+
} },
|
|
1167
|
+
tool: false
|
|
1168
|
+
}).handler(async () => ({
|
|
1169
|
+
status: 200,
|
|
1170
|
+
body: { needed: (await db.list(collection.name, {
|
|
1171
|
+
offset: 0,
|
|
1172
|
+
limit: 1
|
|
1173
|
+
})).total === 0 }
|
|
1174
|
+
}));
|
|
1175
|
+
if (isEditorsCollection) routes["setup"] = route({
|
|
1176
|
+
method: "POST",
|
|
1177
|
+
path: `${path}/setup`,
|
|
1178
|
+
summary: "Create the first account",
|
|
1179
|
+
description: "Only while no editor exists. The account gets every admin role.",
|
|
1180
|
+
auth: false,
|
|
1181
|
+
body: createSchemaOf(collection).omit({ roles: true }).extend({ password: PasswordSchema }),
|
|
1182
|
+
responses: {
|
|
1183
|
+
201: {
|
|
1184
|
+
body: SessionSchema,
|
|
1185
|
+
cache: "no-store"
|
|
1186
|
+
},
|
|
1187
|
+
409: ProblemDetailsSchema
|
|
1188
|
+
},
|
|
1189
|
+
tool: false
|
|
1190
|
+
}).handler(async ({ body }) => {
|
|
1191
|
+
const taken = () => problem(409, "Conflict", "The CMS already has an account. Log in instead.");
|
|
1192
|
+
if ((await db.list(collection.name, {
|
|
1193
|
+
offset: 0,
|
|
1194
|
+
limit: 1
|
|
1195
|
+
})).total > 0) return taken();
|
|
1196
|
+
const { password, ...values } = body;
|
|
1197
|
+
const document = await db.create(collection.name, {
|
|
1198
|
+
...values,
|
|
1199
|
+
email: normalizeEmail(String(values["email"])),
|
|
1200
|
+
roles: [...adminRoles]
|
|
1201
|
+
});
|
|
1202
|
+
const first = (await db.list(collection.name, {
|
|
1203
|
+
offset: 0,
|
|
1204
|
+
limit: 1
|
|
1205
|
+
})).items[0];
|
|
1206
|
+
if (first !== void 0 && first.id !== document.id) {
|
|
1207
|
+
await db.delete(collection.name, document.id);
|
|
1208
|
+
return taken();
|
|
1209
|
+
}
|
|
1210
|
+
await db.setPasswordHash(collection.name, document.id, await hashPassword(String(password)));
|
|
1211
|
+
return {
|
|
1212
|
+
status: 201,
|
|
1213
|
+
body: {
|
|
1214
|
+
token: await startSession(db, collection.name, document.id),
|
|
1215
|
+
[identity]: await resolveAccount(document)
|
|
1216
|
+
}
|
|
1217
|
+
};
|
|
1218
|
+
});
|
|
1219
|
+
if (passwordReset !== void 0) {
|
|
1220
|
+
routes["passwordReset"] = route({
|
|
1221
|
+
method: "POST",
|
|
1222
|
+
path: `${path}/password-reset`,
|
|
1223
|
+
summary: "Email a link to set a new password",
|
|
1224
|
+
description: `Answers the same, and as fast, whether or not the email has an account, and sends the link after answering. One email gets at most 5 links an hour.`,
|
|
1225
|
+
auth: false,
|
|
1226
|
+
body: z.object({ email: z.email().max(254) }),
|
|
1227
|
+
responses: { 204: z.void() },
|
|
1228
|
+
tool: false
|
|
1229
|
+
}).handler(async ({ body, waitUntil }) => {
|
|
1230
|
+
const email = normalizeEmail(body.email);
|
|
1231
|
+
if (await isOverResetLimit(db, collection.name, email)) return { status: 204 };
|
|
1232
|
+
const document = await findByEmail(email);
|
|
1233
|
+
if (document !== void 0) waitUntil(sendPasswordLink(passwordReset, document, "reset"));
|
|
1234
|
+
return { status: 204 };
|
|
1235
|
+
});
|
|
1236
|
+
routes["setPassword"] = route({
|
|
1237
|
+
method: "POST",
|
|
1238
|
+
path: `${path}/password`,
|
|
1239
|
+
summary: "Set a password with the link from an email",
|
|
1240
|
+
description: "Every other session of the account ends.",
|
|
1241
|
+
auth: false,
|
|
1242
|
+
body: z.object({
|
|
1243
|
+
token: z.string().min(1),
|
|
1244
|
+
password: PasswordSchema
|
|
1245
|
+
}),
|
|
1246
|
+
responses: {
|
|
1247
|
+
200: {
|
|
1248
|
+
body: SessionSchema,
|
|
1249
|
+
cache: "no-store"
|
|
1250
|
+
},
|
|
1251
|
+
400: ProblemDetailsSchema
|
|
1252
|
+
},
|
|
1253
|
+
tool: false
|
|
1254
|
+
}).handler(async ({ body }) => {
|
|
1255
|
+
const editorId = await redeemPasswordLink(db, collection.name, body.token);
|
|
1256
|
+
const document = editorId === void 0 ? void 0 : await db.get(collection.name, editorId);
|
|
1257
|
+
if (document === void 0) return problem(400, "Bad Request", "The link has expired or was used. Ask for a new one.");
|
|
1258
|
+
await db.setPasswordHash(collection.name, document.id, await hashPassword(body.password));
|
|
1259
|
+
await db.deleteSessionsOf(document.id);
|
|
1260
|
+
await db.deletePasswordTokensOf(document.id);
|
|
1261
|
+
await db.clearFailedLogins(collection.name, String(document["email"]));
|
|
1262
|
+
return {
|
|
1263
|
+
status: 200,
|
|
1264
|
+
body: {
|
|
1265
|
+
token: await startSession(db, collection.name, document.id),
|
|
1266
|
+
[identity]: await resolveAccount(document)
|
|
1267
|
+
}
|
|
1268
|
+
};
|
|
1269
|
+
});
|
|
1270
|
+
routes["invite"] = route({
|
|
1271
|
+
method: "POST",
|
|
1272
|
+
path: `${path}/:id/invite`,
|
|
1273
|
+
summary: `Email ${accountNounOf(collection)} a link to set their password`,
|
|
1274
|
+
description: "The link works for 7 days.",
|
|
1275
|
+
auth: adminRule,
|
|
1276
|
+
pathParams: z.object({ id: z.string() }),
|
|
1277
|
+
responses: {
|
|
1278
|
+
204: z.void(),
|
|
1279
|
+
404: ProblemDetailsSchema
|
|
1280
|
+
},
|
|
1281
|
+
tool: false
|
|
1282
|
+
}).handler(async ({ params }) => {
|
|
1283
|
+
const document = await db.get(collection.name, params.id);
|
|
1284
|
+
if (document === void 0) return notFound(params.id);
|
|
1285
|
+
await sendPasswordLink(passwordReset, document, "invite");
|
|
1286
|
+
return { status: 204 };
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
const CreateSchema = createSchemaOf(collection).extend({ password: PasswordSchema });
|
|
1290
|
+
return {
|
|
1291
|
+
writes: {
|
|
1292
|
+
shape: {
|
|
1293
|
+
password: PasswordSchema.optional(),
|
|
1294
|
+
currentPassword: CurrentPasswordSchema
|
|
1295
|
+
},
|
|
1296
|
+
checkWrite,
|
|
1297
|
+
checkDelete: async (id) => isEditorsCollection && await leavesNoAdmin(id, void 0) ? lastAdmin() : void 0,
|
|
1298
|
+
routes
|
|
1299
|
+
},
|
|
1300
|
+
api: {
|
|
1301
|
+
create: async (editor) => {
|
|
1302
|
+
const values = CreateSchema.parse(editor);
|
|
1303
|
+
const email = normalizeEmail(String(values["email"]));
|
|
1304
|
+
if (await findByEmail(email) !== void 0) throw new Error(`Another editor has the email '${email}'.`);
|
|
1305
|
+
const { password, ...fields } = values;
|
|
1306
|
+
const document = await db.create(collection.name, {
|
|
1307
|
+
...fields,
|
|
1308
|
+
email,
|
|
1309
|
+
roles: [...new Set(values["roles"])]
|
|
1310
|
+
});
|
|
1311
|
+
await db.setPasswordHash(collection.name, document.id, await hashPassword(String(password)));
|
|
1312
|
+
return document;
|
|
1313
|
+
},
|
|
1314
|
+
find: async (findOptions = {}) => {
|
|
1315
|
+
if (findOptions.email !== void 0) {
|
|
1316
|
+
const document = await findByEmail(findOptions.email);
|
|
1317
|
+
return {
|
|
1318
|
+
items: document === void 0 ? [] : [document],
|
|
1319
|
+
total: document === void 0 ? 0 : 1
|
|
1320
|
+
};
|
|
1321
|
+
}
|
|
1322
|
+
const page = await db.list(collection.name, {
|
|
1323
|
+
offset: findOptions.offset ?? 0,
|
|
1324
|
+
limit: findOptions.limit ?? 20
|
|
1325
|
+
});
|
|
1326
|
+
return {
|
|
1327
|
+
items: page.items,
|
|
1328
|
+
total: page.total
|
|
1329
|
+
};
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
};
|
|
1333
|
+
};
|
|
1334
|
+
//#endregion
|
|
1335
|
+
//#region src/global.ts
|
|
1336
|
+
/**
|
|
1337
|
+
* Checks a global's definition and returns the global, for `k.global`.
|
|
1338
|
+
*/
|
|
1339
|
+
const defineGlobal = (definition) => {
|
|
1340
|
+
checkDefinition(`Global '${definition.name}'`, definition.name, definition.fields, "`settings` or `footer`");
|
|
1341
|
+
return {
|
|
1342
|
+
...definition,
|
|
1343
|
+
kind: "global"
|
|
1344
|
+
};
|
|
1345
|
+
};
|
|
1346
|
+
/**
|
|
1347
|
+
* The schema a global reads as, where every field and `updatedAt` are absent until saved.
|
|
1348
|
+
*/
|
|
1349
|
+
const globalSchemaOf = (global) => {
|
|
1350
|
+
const shape = {
|
|
1351
|
+
updatedAt: z.iso.datetime().optional(),
|
|
1352
|
+
updatedBy: EditorReferenceSchema.optional().describe("Who changed it last.")
|
|
1353
|
+
};
|
|
1354
|
+
const owner = global.name.charAt(0).toUpperCase() + global.name.slice(1);
|
|
1355
|
+
for (const field of global.fields) setReadSchema(shape, field, () => wrappedSchemaOf(field, (schema) => schema.optional(), owner));
|
|
1356
|
+
return z.object(shape);
|
|
1357
|
+
};
|
|
1358
|
+
/**
|
|
1359
|
+
* A stored global's values as its routes return them.
|
|
1360
|
+
*/
|
|
1361
|
+
const globalValuesOf = (document) => {
|
|
1362
|
+
if (document === void 0) return {};
|
|
1363
|
+
const { id: _id, createdAt: _createdAt, ...values } = document;
|
|
1364
|
+
return values;
|
|
1365
|
+
};
|
|
1366
|
+
//#endregion
|
|
1367
|
+
//#region src/global-routes.ts
|
|
1368
|
+
/**
|
|
1369
|
+
* The group and path prefix of the global routes.
|
|
1370
|
+
*/
|
|
1371
|
+
const GLOBALS_GROUP = "globals";
|
|
1372
|
+
const labelOf = (global) => global.label ?? global.name;
|
|
1373
|
+
/**
|
|
1374
|
+
* The keys a global answers with beside its fields.
|
|
1375
|
+
*/
|
|
1376
|
+
const GLOBAL_KEYS = ["updatedAt", "updatedBy"];
|
|
1377
|
+
/**
|
|
1378
|
+
* The routes that read and update one global, which answer with no fields until it is saved.
|
|
1379
|
+
*/
|
|
1380
|
+
const globalRoutes = (global, options) => {
|
|
1381
|
+
const { db, access, basePath } = options;
|
|
1382
|
+
const resolveValues = async (values) => (await resolveDocuments(db, global, [withDeclaredKeys(global, GLOBAL_KEYS, values)]))[0];
|
|
1383
|
+
const GlobalSchema = globalSchemaOf(global);
|
|
1384
|
+
const path = `${basePath}/${GLOBALS_GROUP}/${global.name}`;
|
|
1385
|
+
const label = labelOf(global);
|
|
1386
|
+
const routes = {};
|
|
1387
|
+
if (access.read.kind !== "nobody") {
|
|
1388
|
+
routes["get"] = route({
|
|
1389
|
+
method: "GET",
|
|
1390
|
+
path,
|
|
1391
|
+
summary: `Get ${label}`,
|
|
1392
|
+
auth: routeAuthOf(access.read),
|
|
1393
|
+
responses: { 200: {
|
|
1394
|
+
body: GlobalSchema,
|
|
1395
|
+
cache: readCacheOf(access.read),
|
|
1396
|
+
etag: true
|
|
1397
|
+
} },
|
|
1398
|
+
tool: toolOf(global.tools, "read")
|
|
1399
|
+
}).handler(async () => {
|
|
1400
|
+
const resolved = await resolveValues(globalValuesOf(await db.getGlobal(global.name)));
|
|
1401
|
+
return {
|
|
1402
|
+
status: 200,
|
|
1403
|
+
body: access.read.kind === "public" ? withoutEditorReferences(resolved) : resolved
|
|
1404
|
+
};
|
|
1405
|
+
});
|
|
1406
|
+
routes["editors"] = route({
|
|
1407
|
+
method: "GET",
|
|
1408
|
+
path: `${path}/editors`,
|
|
1409
|
+
summary: `Who last changed ${label}`,
|
|
1410
|
+
auth: editorsRouteAuthOf(access.read),
|
|
1411
|
+
hidden: true,
|
|
1412
|
+
responses: { 200: {
|
|
1413
|
+
body: EditorReferencesSchema,
|
|
1414
|
+
cache: "no-store"
|
|
1415
|
+
} }
|
|
1416
|
+
}).handler(async () => ({
|
|
1417
|
+
status: 200,
|
|
1418
|
+
body: await editorReferencesOf(db, await db.getGlobal(global.name) ?? {})
|
|
1419
|
+
}));
|
|
1420
|
+
}
|
|
1421
|
+
if (access.update.kind !== "nobody") routes["update"] = route({
|
|
1422
|
+
method: "PATCH",
|
|
1423
|
+
path,
|
|
1424
|
+
summary: `Change ${label}`,
|
|
1425
|
+
description: "`null` clears a field.",
|
|
1426
|
+
auth: routeAuthOf(access.update),
|
|
1427
|
+
body: updateSchemaOf(global),
|
|
1428
|
+
responses: {
|
|
1429
|
+
200: GlobalSchema,
|
|
1430
|
+
...global.fields.some(isFileField) ? { 422: ProblemDetailsSchema } : {}
|
|
1431
|
+
},
|
|
1432
|
+
tool: toolOf(global.tools, "update")
|
|
1433
|
+
}).handler(async ({ body, auth }) => {
|
|
1434
|
+
const problem = await fileProblemOf(db, global.fields, body);
|
|
1435
|
+
if (problem !== void 0) return {
|
|
1436
|
+
status: 422,
|
|
1437
|
+
body: {
|
|
1438
|
+
type: "about:blank",
|
|
1439
|
+
title: "Unprocessable Content",
|
|
1440
|
+
status: 422,
|
|
1441
|
+
detail: problem
|
|
1442
|
+
}
|
|
1443
|
+
};
|
|
1444
|
+
return {
|
|
1445
|
+
status: 200,
|
|
1446
|
+
body: await resolveValues(globalValuesOf(await db.updateGlobal(global.name, body, editorIdOf(auth))))
|
|
1447
|
+
};
|
|
1448
|
+
});
|
|
1449
|
+
return groupedRoutes(GLOBALS_GROUP, global.name, routes);
|
|
1450
|
+
};
|
|
1451
|
+
//#endregion
|
|
1452
|
+
//#region src/exif.ts
|
|
1453
|
+
const ascii = (bytes, start, length) => String.fromCharCode(...bytes.subarray(start, Math.min(start + length, bytes.length)));
|
|
1454
|
+
/**
|
|
1455
|
+
* The file with the removals left out and the insertions added, in one new array.
|
|
1456
|
+
*/
|
|
1457
|
+
const rebuilt = (bytes, removals, insertions = []) => {
|
|
1458
|
+
const parts = [];
|
|
1459
|
+
const sortedInsertions = [...insertions].sort((left, right) => left.at - right.at);
|
|
1460
|
+
let insertionIndex = 0;
|
|
1461
|
+
let position = 0;
|
|
1462
|
+
const copyUpTo = (end) => {
|
|
1463
|
+
while (insertionIndex < sortedInsertions.length && sortedInsertions[insertionIndex].at <= end) {
|
|
1464
|
+
const insertion = sortedInsertions[insertionIndex];
|
|
1465
|
+
if (insertion.at > position) parts.push(bytes.subarray(position, insertion.at));
|
|
1466
|
+
position = Math.max(position, insertion.at);
|
|
1467
|
+
parts.push(insertion.bytes);
|
|
1468
|
+
insertionIndex++;
|
|
1469
|
+
}
|
|
1470
|
+
if (end > position) parts.push(bytes.subarray(position, end));
|
|
1471
|
+
position = Math.max(position, end);
|
|
1472
|
+
};
|
|
1473
|
+
for (const removal of [...removals].sort((left, right) => left.start - right.start)) {
|
|
1474
|
+
copyUpTo(removal.start);
|
|
1475
|
+
position = Math.max(position, removal.end);
|
|
1476
|
+
}
|
|
1477
|
+
copyUpTo(bytes.length);
|
|
1478
|
+
const length = parts.reduce((total, part) => total + part.byteLength, 0);
|
|
1479
|
+
const result = new Uint8Array(length);
|
|
1480
|
+
let offset = 0;
|
|
1481
|
+
for (const part of parts) {
|
|
1482
|
+
result.set(part, offset);
|
|
1483
|
+
offset += part.byteLength;
|
|
1484
|
+
}
|
|
1485
|
+
return result;
|
|
1486
|
+
};
|
|
1487
|
+
/**
|
|
1488
|
+
* TIFF data that holds only the EXIF orientation: a little-endian header and one directory entry for tag 0x0112.
|
|
1489
|
+
*/
|
|
1490
|
+
const orientationTiff = (orientation) => {
|
|
1491
|
+
const tiff = new Uint8Array(26);
|
|
1492
|
+
const view = new DataView(tiff.buffer);
|
|
1493
|
+
tiff.set([
|
|
1494
|
+
73,
|
|
1495
|
+
73,
|
|
1496
|
+
42,
|
|
1497
|
+
0
|
|
1498
|
+
]);
|
|
1499
|
+
view.setUint32(4, 8, true);
|
|
1500
|
+
view.setUint16(8, 1, true);
|
|
1501
|
+
view.setUint16(10, 274, true);
|
|
1502
|
+
view.setUint16(12, 3, true);
|
|
1503
|
+
view.setUint32(14, 1, true);
|
|
1504
|
+
view.setUint16(18, orientation, true);
|
|
1505
|
+
return tiff;
|
|
1506
|
+
};
|
|
1507
|
+
/**
|
|
1508
|
+
* An APP1 segment that holds only the EXIF orientation, which keeps a photo the right way up.
|
|
1509
|
+
*/
|
|
1510
|
+
const orientationSegment = (orientation) => {
|
|
1511
|
+
const tiff = orientationTiff(orientation);
|
|
1512
|
+
const segment = new Uint8Array(10 + tiff.byteLength);
|
|
1513
|
+
segment.set([255, 225]);
|
|
1514
|
+
new DataView(segment.buffer).setUint16(2, segment.byteLength - 2);
|
|
1515
|
+
segment.set([
|
|
1516
|
+
69,
|
|
1517
|
+
120,
|
|
1518
|
+
105,
|
|
1519
|
+
102,
|
|
1520
|
+
0,
|
|
1521
|
+
0
|
|
1522
|
+
], 4);
|
|
1523
|
+
segment.set(tiff, 10);
|
|
1524
|
+
return segment;
|
|
1525
|
+
};
|
|
1526
|
+
/**
|
|
1527
|
+
* The orientation from 1 to 8 in the TIFF data that starts at `start` and ends before `end`, or `undefined` when it
|
|
1528
|
+
* holds none or points outside itself.
|
|
1529
|
+
*/
|
|
1530
|
+
const tiffOrientationOf = (bytes, start, end) => {
|
|
1531
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
1532
|
+
const limit = Math.min(end, bytes.length);
|
|
1533
|
+
if (start + 8 > limit) return void 0;
|
|
1534
|
+
const order = ascii(bytes, start, 2);
|
|
1535
|
+
if (order !== "II" && order !== "MM") return void 0;
|
|
1536
|
+
const little = order === "II";
|
|
1537
|
+
const directory = start + view.getUint32(start + 4, little);
|
|
1538
|
+
if (directory + 2 > limit) return void 0;
|
|
1539
|
+
const entries = view.getUint16(directory, little);
|
|
1540
|
+
for (let index = 0; index < entries; index++) {
|
|
1541
|
+
const entry = directory + 2 + index * 12;
|
|
1542
|
+
if (entry + 12 > limit) return void 0;
|
|
1543
|
+
if (view.getUint16(entry, little) === 274) {
|
|
1544
|
+
const orientation = view.getUint16(entry + 8, little);
|
|
1545
|
+
return orientation >= 1 && orientation <= 8 ? orientation : void 0;
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1548
|
+
};
|
|
1549
|
+
/**
|
|
1550
|
+
* The orientation from 1 to 8 in the EXIF that starts at `start` with `Exif` and ends before `end`, or `undefined`
|
|
1551
|
+
* when it holds none or points outside itself.
|
|
1552
|
+
*/
|
|
1553
|
+
const exifOrientationOf = (bytes, start, end) => ascii(bytes, start, 4) === "Exif" ? tiffOrientationOf(bytes, start + 6, end) : void 0;
|
|
1554
|
+
/**
|
|
1555
|
+
* The orientation in an EXIF chunk of a PNG or WebP, which holds TIFF data, sometimes after `Exif`.
|
|
1556
|
+
*/
|
|
1557
|
+
const chunkOrientationOf = (bytes, start, end) => exifOrientationOf(bytes, start, end) ?? tiffOrientationOf(bytes, start, end);
|
|
1558
|
+
/**
|
|
1559
|
+
* Markers that stand alone, with no length after them: TEM, the restart markers and SOI.
|
|
1560
|
+
*/
|
|
1561
|
+
const isStandaloneMarker = (marker) => marker === 1 || marker >= 208 && marker <= 216;
|
|
1562
|
+
/**
|
|
1563
|
+
* APP1 holds EXIF, XMP and extended XMP. APP13 holds IPTC and Photoshop's resources. Each can hold a location.
|
|
1564
|
+
*/
|
|
1565
|
+
const isMetadataMarker = (marker) => marker === 225 || marker === 237;
|
|
1566
|
+
/**
|
|
1567
|
+
* The end of the scan data that starts at `offset`: the next marker that is no stuffed byte or restart marker.
|
|
1568
|
+
*/
|
|
1569
|
+
const endOfScanData = (bytes, offset) => {
|
|
1570
|
+
let position = offset;
|
|
1571
|
+
while (position + 1 < bytes.length) {
|
|
1572
|
+
if (bytes[position] === 255) {
|
|
1573
|
+
const next = bytes[position + 1];
|
|
1574
|
+
if (next === 0 || next >= 208 && next <= 215) {
|
|
1575
|
+
position += 2;
|
|
1576
|
+
continue;
|
|
1577
|
+
}
|
|
1578
|
+
if (next === 255) {
|
|
1579
|
+
position += 1;
|
|
1580
|
+
continue;
|
|
1581
|
+
}
|
|
1582
|
+
return position;
|
|
1583
|
+
}
|
|
1584
|
+
position += 1;
|
|
1585
|
+
}
|
|
1586
|
+
return bytes.length;
|
|
1587
|
+
};
|
|
1588
|
+
/**
|
|
1589
|
+
* Walks one JPEG from its SOI at `start` and finds its metadata segments, where it ends and its orientation.
|
|
1590
|
+
*
|
|
1591
|
+
* A `strict` walk is for a JPEG found inside the file, like the second image of an MPO. It answers `undefined` unless
|
|
1592
|
+
* well-formed segments lead to the image data, so bytes that only look like a JPEG are left alone.
|
|
1593
|
+
*/
|
|
1594
|
+
const walkJpeg = (bytes, start, strict) => {
|
|
1595
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
1596
|
+
const removals = [];
|
|
1597
|
+
let orientation;
|
|
1598
|
+
let scanned = false;
|
|
1599
|
+
let offset = start + 2;
|
|
1600
|
+
const ended = (end) => strict && !scanned ? void 0 : {
|
|
1601
|
+
end,
|
|
1602
|
+
removals,
|
|
1603
|
+
...orientation === void 0 ? {} : { orientation }
|
|
1604
|
+
};
|
|
1605
|
+
while (offset < bytes.length) {
|
|
1606
|
+
if (bytes[offset] !== 255) {
|
|
1607
|
+
if (strict && !scanned) return void 0;
|
|
1608
|
+
offset += 1;
|
|
1609
|
+
continue;
|
|
1610
|
+
}
|
|
1611
|
+
while (offset + 1 < bytes.length && bytes[offset + 1] === 255) offset += 1;
|
|
1612
|
+
if (offset + 1 >= bytes.length) break;
|
|
1613
|
+
const marker = bytes[offset + 1];
|
|
1614
|
+
if (marker === 0 || isStandaloneMarker(marker)) {
|
|
1615
|
+
if (strict && !scanned) return void 0;
|
|
1616
|
+
offset += 2;
|
|
1617
|
+
continue;
|
|
1618
|
+
}
|
|
1619
|
+
if (marker === 217) return ended(offset + 2);
|
|
1620
|
+
if (offset + 4 > bytes.length) {
|
|
1621
|
+
if (isMetadataMarker(marker)) removals.push({
|
|
1622
|
+
start: offset,
|
|
1623
|
+
end: bytes.length
|
|
1624
|
+
});
|
|
1625
|
+
break;
|
|
1626
|
+
}
|
|
1627
|
+
const segmentEnd = offset + 2 + view.getUint16(offset + 2);
|
|
1628
|
+
if (segmentEnd < offset + 4) {
|
|
1629
|
+
if (strict && !scanned) return void 0;
|
|
1630
|
+
offset += 2;
|
|
1631
|
+
continue;
|
|
1632
|
+
}
|
|
1633
|
+
if (isMetadataMarker(marker)) {
|
|
1634
|
+
if (marker === 225) orientation ??= exifOrientationOf(bytes, offset + 4, segmentEnd);
|
|
1635
|
+
removals.push({
|
|
1636
|
+
start: offset,
|
|
1637
|
+
end: Math.min(segmentEnd, bytes.length)
|
|
1638
|
+
});
|
|
1639
|
+
}
|
|
1640
|
+
if (segmentEnd >= bytes.length) break;
|
|
1641
|
+
if (marker === 218) scanned = true;
|
|
1642
|
+
offset = marker === 218 ? endOfScanData(bytes, segmentEnd) : segmentEnd;
|
|
1643
|
+
}
|
|
1644
|
+
return ended(bytes.length);
|
|
1645
|
+
};
|
|
1646
|
+
/**
|
|
1647
|
+
* Where the next JPEG starts at or after `from`, or `undefined` when none does.
|
|
1648
|
+
*/
|
|
1649
|
+
const nextJpegStart = (bytes, from) => {
|
|
1650
|
+
for (let position = from; position + 2 < bytes.length; position++) if (bytes[position] === 255 && bytes[position + 1] === 216 && bytes[position + 2] === 255) return position;
|
|
1651
|
+
};
|
|
1652
|
+
/**
|
|
1653
|
+
* A JPEG without the EXIF, XMP and IPTC where cameras write the location. That holds for every JPEG in the file, like
|
|
1654
|
+
* the second image of an MPO or a gain map appended after the photo. Only the orientation is kept and nothing is
|
|
1655
|
+
* re-encoded. Returns `undefined` when there was nothing to remove.
|
|
1656
|
+
*/
|
|
1657
|
+
const stripJpegMetadata = (bytes) => {
|
|
1658
|
+
if (bytes[0] !== 255 || bytes[1] !== 216) return void 0;
|
|
1659
|
+
const removals = [];
|
|
1660
|
+
const insertions = [];
|
|
1661
|
+
let start = 0;
|
|
1662
|
+
while (start !== void 0) {
|
|
1663
|
+
const walked = walkJpeg(bytes, start, start > 0);
|
|
1664
|
+
if (walked !== void 0) {
|
|
1665
|
+
removals.push(...walked.removals);
|
|
1666
|
+
if (walked.orientation !== void 0 && walked.orientation !== 1) insertions.push({
|
|
1667
|
+
at: start + 2,
|
|
1668
|
+
bytes: orientationSegment(walked.orientation)
|
|
1669
|
+
});
|
|
1670
|
+
}
|
|
1671
|
+
start = nextJpegStart(bytes, Math.max(walked?.end ?? 0, start + 2));
|
|
1672
|
+
}
|
|
1673
|
+
return removals.length === 0 ? void 0 : rebuilt(bytes, removals, insertions);
|
|
1674
|
+
};
|
|
1675
|
+
const PNG_SIGNATURE = [
|
|
1676
|
+
137,
|
|
1677
|
+
80,
|
|
1678
|
+
78,
|
|
1679
|
+
71,
|
|
1680
|
+
13,
|
|
1681
|
+
10,
|
|
1682
|
+
26,
|
|
1683
|
+
10
|
|
1684
|
+
];
|
|
1685
|
+
/**
|
|
1686
|
+
* Text chunks whose keyword says they hold EXIF or XMP, as ImageMagick and Adobe write them.
|
|
1687
|
+
*/
|
|
1688
|
+
const isPngMetadataKeyword = (keyword) => /^(xml:com\.adobe\.xmp$|raw profile type |exif|xmp)/i.test(keyword);
|
|
1689
|
+
/**
|
|
1690
|
+
* A PNG chunk of `type` that holds `data`, with its checksum.
|
|
1691
|
+
*/
|
|
1692
|
+
const pngChunk = (type, data) => {
|
|
1693
|
+
const chunk = new Uint8Array(12 + data.byteLength);
|
|
1694
|
+
const view = new DataView(chunk.buffer);
|
|
1695
|
+
view.setUint32(0, data.byteLength);
|
|
1696
|
+
for (let index = 0; index < 4; index++) chunk[4 + index] = type.charCodeAt(index);
|
|
1697
|
+
chunk.set(data, 8);
|
|
1698
|
+
view.setUint32(8 + data.byteLength, crc32(chunk.subarray(4, 8 + data.byteLength)));
|
|
1699
|
+
return chunk;
|
|
1700
|
+
};
|
|
1701
|
+
/**
|
|
1702
|
+
* Walks a PNG's chunks up to IEND and calls `visit` with each.
|
|
1703
|
+
*/
|
|
1704
|
+
const walkPng = (bytes, visit) => {
|
|
1705
|
+
if (bytes.length < 8 || PNG_SIGNATURE.some((value, index) => bytes[index] !== value)) return;
|
|
1706
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
1707
|
+
let offset = 8;
|
|
1708
|
+
while (offset + 8 <= bytes.length) {
|
|
1709
|
+
const type = ascii(bytes, offset + 4, 4);
|
|
1710
|
+
const end = offset + 12 + view.getUint32(offset);
|
|
1711
|
+
visit({
|
|
1712
|
+
type,
|
|
1713
|
+
start: offset,
|
|
1714
|
+
dataStart: offset + 8,
|
|
1715
|
+
end
|
|
1716
|
+
});
|
|
1717
|
+
if (type === "IEND" || end >= bytes.length) break;
|
|
1718
|
+
offset = end;
|
|
1719
|
+
}
|
|
1720
|
+
};
|
|
1721
|
+
/**
|
|
1722
|
+
* A PNG without its eXIf chunk and the text chunks that carry EXIF or XMP. Only the orientation is kept. Returns
|
|
1723
|
+
* `undefined` when there was nothing to remove.
|
|
1724
|
+
*/
|
|
1725
|
+
const stripPngMetadata = (bytes) => {
|
|
1726
|
+
const removals = [];
|
|
1727
|
+
const insertions = [];
|
|
1728
|
+
walkPng(bytes, (chunk) => {
|
|
1729
|
+
let isMetadata = chunk.type === "eXIf";
|
|
1730
|
+
if (chunk.type === "tEXt" || chunk.type === "zTXt" || chunk.type === "iTXt") {
|
|
1731
|
+
const field = bytes.subarray(chunk.dataStart, Math.min(chunk.dataStart + 80, chunk.end, bytes.length));
|
|
1732
|
+
const keywordEnd = field.indexOf(0);
|
|
1733
|
+
isMetadata = isPngMetadataKeyword(ascii(field, 0, keywordEnd === -1 ? field.length : keywordEnd));
|
|
1734
|
+
}
|
|
1735
|
+
if (!isMetadata) return;
|
|
1736
|
+
if (chunk.type === "eXIf" && insertions.length === 0) {
|
|
1737
|
+
const orientation = chunkOrientationOf(bytes, chunk.dataStart, chunk.end - 4);
|
|
1738
|
+
if (orientation !== void 0 && orientation !== 1) insertions.push({
|
|
1739
|
+
at: chunk.start,
|
|
1740
|
+
bytes: pngChunk("eXIf", orientationTiff(orientation))
|
|
1741
|
+
});
|
|
1742
|
+
}
|
|
1743
|
+
removals.push({
|
|
1744
|
+
start: chunk.start,
|
|
1745
|
+
end: Math.min(chunk.end, bytes.length)
|
|
1746
|
+
});
|
|
1747
|
+
});
|
|
1748
|
+
return removals.length === 0 ? void 0 : rebuilt(bytes, removals, insertions);
|
|
1749
|
+
};
|
|
1750
|
+
/**
|
|
1751
|
+
* The VP8X flag that announces an EXIF chunk.
|
|
1752
|
+
*/
|
|
1753
|
+
const WEBP_EXIF_FLAG = 8;
|
|
1754
|
+
/**
|
|
1755
|
+
* The VP8X flag that announces an XMP chunk.
|
|
1756
|
+
*/
|
|
1757
|
+
const WEBP_XMP_FLAG = 4;
|
|
1758
|
+
/**
|
|
1759
|
+
* Walks a WebP's chunks and calls `visit` with each. A chunk's type is its FourCC.
|
|
1760
|
+
*/
|
|
1761
|
+
const walkWebp = (bytes, visit) => {
|
|
1762
|
+
if (bytes.length < 12 || ascii(bytes, 0, 4) !== "RIFF" || ascii(bytes, 8, 4) !== "WEBP") return;
|
|
1763
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
1764
|
+
let offset = 12;
|
|
1765
|
+
while (offset + 8 <= bytes.length) {
|
|
1766
|
+
const size = view.getUint32(offset + 4, true);
|
|
1767
|
+
const end = offset + 8 + size + size % 2;
|
|
1768
|
+
visit({
|
|
1769
|
+
type: ascii(bytes, offset, 4),
|
|
1770
|
+
start: offset,
|
|
1771
|
+
dataStart: offset + 8,
|
|
1772
|
+
end
|
|
1773
|
+
});
|
|
1774
|
+
if (end >= bytes.length) break;
|
|
1775
|
+
offset = end;
|
|
1776
|
+
}
|
|
1777
|
+
};
|
|
1778
|
+
/**
|
|
1779
|
+
* A WebP without its EXIF and XMP chunks, with the VP8X flags that announce them cleared. Only the orientation is kept.
|
|
1780
|
+
* Returns `undefined` when there was nothing to remove.
|
|
1781
|
+
*/
|
|
1782
|
+
const stripWebpMetadata = (bytes) => {
|
|
1783
|
+
const removals = [];
|
|
1784
|
+
const insertions = [];
|
|
1785
|
+
let flagsAt;
|
|
1786
|
+
walkWebp(bytes, (chunk) => {
|
|
1787
|
+
if (chunk.type === "VP8X" && chunk.dataStart < bytes.length) flagsAt = chunk.dataStart;
|
|
1788
|
+
if (chunk.type !== "EXIF" && chunk.type !== "XMP ") return;
|
|
1789
|
+
if (chunk.type === "EXIF" && insertions.length === 0) {
|
|
1790
|
+
const orientation = chunkOrientationOf(bytes, chunk.dataStart, chunk.end);
|
|
1791
|
+
if (orientation !== void 0 && orientation !== 1) {
|
|
1792
|
+
const tiff = orientationTiff(orientation);
|
|
1793
|
+
const kept = new Uint8Array(8 + tiff.byteLength);
|
|
1794
|
+
for (let index = 0; index < 4; index++) kept[index] = "EXIF".charCodeAt(index);
|
|
1795
|
+
new DataView(kept.buffer).setUint32(4, tiff.byteLength, true);
|
|
1796
|
+
kept.set(tiff, 8);
|
|
1797
|
+
insertions.push({
|
|
1798
|
+
at: chunk.start,
|
|
1799
|
+
bytes: kept
|
|
1800
|
+
});
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
removals.push({
|
|
1804
|
+
start: chunk.start,
|
|
1805
|
+
end: Math.min(chunk.end, bytes.length)
|
|
1806
|
+
});
|
|
1807
|
+
});
|
|
1808
|
+
if (removals.length === 0) return void 0;
|
|
1809
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
1810
|
+
const removedBytes = removals.reduce((total, removal) => total + removal.end - removal.start, 0);
|
|
1811
|
+
const insertedBytes = insertions.reduce((total, insertion) => total + insertion.bytes.byteLength, 0);
|
|
1812
|
+
const result = rebuilt(bytes, removals, insertions);
|
|
1813
|
+
new DataView(result.buffer, result.byteOffset, result.byteLength).setUint32(4, Math.max(view.getUint32(4, true) - removedBytes + insertedBytes, 4), true);
|
|
1814
|
+
if (flagsAt !== void 0 && removals.every((removal) => removal.start > flagsAt)) result[flagsAt] = result[flagsAt] & ~(WEBP_XMP_FLAG | (insertions.length === 0 ? WEBP_EXIF_FLAG : 0));
|
|
1815
|
+
return result;
|
|
1816
|
+
};
|
|
1817
|
+
/**
|
|
1818
|
+
* The image types {@link stripImageMetadata} removes metadata from.
|
|
1819
|
+
*/
|
|
1820
|
+
const STRIPPED_TYPES = [
|
|
1821
|
+
"image/jpeg",
|
|
1822
|
+
"image/png",
|
|
1823
|
+
"image/webp"
|
|
1824
|
+
];
|
|
1825
|
+
/**
|
|
1826
|
+
* An image of `contentType` without the metadata where cameras write the location. Returns `undefined` when there was
|
|
1827
|
+
* nothing to remove or the type is not one of {@link STRIPPED_TYPES}.
|
|
1828
|
+
*/
|
|
1829
|
+
const stripImageMetadata = (bytes, contentType) => {
|
|
1830
|
+
switch (contentType) {
|
|
1831
|
+
case "image/jpeg": return stripJpegMetadata(bytes);
|
|
1832
|
+
case "image/png": return stripPngMetadata(bytes);
|
|
1833
|
+
case "image/webp": return stripWebpMetadata(bytes);
|
|
1834
|
+
default: return;
|
|
1835
|
+
}
|
|
1836
|
+
};
|
|
1837
|
+
//#endregion
|
|
1838
|
+
//#region src/image-size.ts
|
|
1839
|
+
/**
|
|
1840
|
+
* How many bytes `imageSizeOf` reads, with room for a JPEG's metadata before its size.
|
|
1841
|
+
*/
|
|
1842
|
+
const IMAGE_HEADER_BYTES = 256 * 1024;
|
|
1843
|
+
const CONTENT_TYPES = {
|
|
1844
|
+
png: "image/png",
|
|
1845
|
+
gif: "image/gif",
|
|
1846
|
+
jpeg: "image/jpeg",
|
|
1847
|
+
webp: "image/webp",
|
|
1848
|
+
avif: "image/avif",
|
|
1849
|
+
heic: "image/heic"
|
|
1850
|
+
};
|
|
1851
|
+
/**
|
|
1852
|
+
* Whether a JPEG's EXIF orientation turns the photo a quarter, which swaps its width and height.
|
|
1853
|
+
*/
|
|
1854
|
+
const isTurnedQuarter = (bytes) => {
|
|
1855
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
1856
|
+
let offset = 2;
|
|
1857
|
+
while (offset + 4 <= bytes.length && bytes[offset] === 255) {
|
|
1858
|
+
if (bytes[offset + 1] === 255) {
|
|
1859
|
+
offset += 1;
|
|
1860
|
+
continue;
|
|
1861
|
+
}
|
|
1862
|
+
const marker = bytes[offset + 1];
|
|
1863
|
+
if (marker === 218) return false;
|
|
1864
|
+
const end = offset + 2 + view.getUint16(offset + 2);
|
|
1865
|
+
if (end < offset + 4) return false;
|
|
1866
|
+
if (marker === 225) {
|
|
1867
|
+
const orientation = exifOrientationOf(bytes, offset + 4, end);
|
|
1868
|
+
if (orientation !== void 0) return orientation >= 5 && orientation <= 8;
|
|
1869
|
+
}
|
|
1870
|
+
offset = end;
|
|
1871
|
+
}
|
|
1872
|
+
return false;
|
|
1873
|
+
};
|
|
1874
|
+
/**
|
|
1875
|
+
* Returns an image's type, and its width and height as shown, or `undefined` when the bytes are not a PNG, GIF, JPEG,
|
|
1876
|
+
* WebP, AVIF or HEIC image, or its header can't be read.
|
|
1877
|
+
*/
|
|
1878
|
+
const imageSizeOf = (bytes) => {
|
|
1879
|
+
try {
|
|
1880
|
+
const found = imageDimensionsFromData(bytes);
|
|
1881
|
+
if (found === void 0) return void 0;
|
|
1882
|
+
const turned = found.type === "jpeg" && isTurnedQuarter(bytes);
|
|
1883
|
+
return {
|
|
1884
|
+
contentType: CONTENT_TYPES[found.type],
|
|
1885
|
+
width: turned ? found.height : found.width,
|
|
1886
|
+
height: turned ? found.width : found.height
|
|
1887
|
+
};
|
|
1888
|
+
} catch {
|
|
1889
|
+
return;
|
|
1890
|
+
}
|
|
1891
|
+
};
|
|
1892
|
+
//#endregion
|
|
1893
|
+
//#region src/storage-routes.ts
|
|
1894
|
+
/**
|
|
1895
|
+
* One media type as RFC 9110 writes it, a type and a subtype with nothing around them. A list or a wildcard fails it.
|
|
1896
|
+
*/
|
|
1897
|
+
const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/;
|
|
1898
|
+
/**
|
|
1899
|
+
* The HTML, XML and JavaScript types a browser runs script in. Every type ending in `+xml` counts too.
|
|
1900
|
+
*/
|
|
1901
|
+
const SCRIPTABLE_TYPES = new Set([
|
|
1902
|
+
"text/html",
|
|
1903
|
+
"application/xhtml+xml",
|
|
1904
|
+
"text/xml",
|
|
1905
|
+
"application/xml",
|
|
1906
|
+
"text/xsl",
|
|
1907
|
+
"application/javascript",
|
|
1908
|
+
"application/ecmascript",
|
|
1909
|
+
"application/x-ecmascript",
|
|
1910
|
+
"application/x-javascript",
|
|
1911
|
+
"text/javascript",
|
|
1912
|
+
"text/javascript1.0",
|
|
1913
|
+
"text/javascript1.1",
|
|
1914
|
+
"text/javascript1.2",
|
|
1915
|
+
"text/javascript1.3",
|
|
1916
|
+
"text/javascript1.4",
|
|
1917
|
+
"text/javascript1.5",
|
|
1918
|
+
"text/ecmascript",
|
|
1919
|
+
"text/jscript",
|
|
1920
|
+
"text/livescript",
|
|
1921
|
+
"text/x-ecmascript",
|
|
1922
|
+
"text/x-javascript"
|
|
1923
|
+
]);
|
|
1924
|
+
const SCRIPTABLE_EXTENSIONS = /\.(svgz?|x?html?|xht|xml|xslt?|m?js)$/;
|
|
1925
|
+
/**
|
|
1926
|
+
* The shape of a key {@link newFileKey} hands out: the store's name, a UUID and maybe an ending.
|
|
1927
|
+
*/
|
|
1928
|
+
const issuedKeyPattern = (store) => new RegExp(`^${store}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(\\.[a-z0-9]{1,8})?$`);
|
|
1929
|
+
const STORAGE_GROUP = "storage";
|
|
1930
|
+
/**
|
|
1931
|
+
* The type name of a store's file. `images` gives `ImageFile`.
|
|
1932
|
+
*/
|
|
1933
|
+
const fileModelNameOf = (storage) => {
|
|
1934
|
+
const singular = pluralize.singular(storage.name);
|
|
1935
|
+
return `${singular.charAt(0).toUpperCase()}${singular.slice(1)}File`;
|
|
1936
|
+
};
|
|
1937
|
+
/**
|
|
1938
|
+
* The fields a caller may set on a file, as it reads, as an upload records them and as a change takes them.
|
|
1939
|
+
*/
|
|
1940
|
+
const editableShapeOf = (storage, use) => {
|
|
1941
|
+
const optional = (schema) => use === "update" ? schema.nullable().optional() : schema.optional();
|
|
1942
|
+
const shape = {
|
|
1943
|
+
alt: optional(z.string()).describe("What the image shows, for people who cannot see it."),
|
|
1944
|
+
focalPoint: optional(FocalPointSchema)
|
|
1945
|
+
};
|
|
1946
|
+
for (const field of storage.fields ?? []) shape[field.name] = field.required === true && use === "create" ? schemaOf(field) : wrappedSchemaOf(field, (schema) => field.required === true ? schema.optional() : optional(schema));
|
|
1947
|
+
return shape;
|
|
1948
|
+
};
|
|
1949
|
+
const FILE_SORT_KEYS = [
|
|
1950
|
+
"createdAt",
|
|
1951
|
+
"updatedAt",
|
|
1952
|
+
"filename"
|
|
1953
|
+
].flatMap((name) => [name, `-${name}`]);
|
|
1954
|
+
/**
|
|
1955
|
+
* The fields a list of files filters by: its name, its alt text and the store's own fields.
|
|
1956
|
+
*/
|
|
1957
|
+
const filterFieldsOf = (storage) => [
|
|
1958
|
+
{
|
|
1959
|
+
name: "filename",
|
|
1960
|
+
type: "text"
|
|
1961
|
+
},
|
|
1962
|
+
{
|
|
1963
|
+
name: "alt",
|
|
1964
|
+
type: "text"
|
|
1965
|
+
},
|
|
1966
|
+
...storage.fields ?? []
|
|
1967
|
+
];
|
|
1968
|
+
/**
|
|
1969
|
+
* Every document field that holds a file from this store.
|
|
1970
|
+
*/
|
|
1971
|
+
const fileUsesOf = (storage, collections, globals) => {
|
|
1972
|
+
const uses = [];
|
|
1973
|
+
for (const definition of [...collections, ...globals]) {
|
|
1974
|
+
const owner = definition.kind === "collection" ? { collection: definition.name } : { global: definition.name };
|
|
1975
|
+
if (metaImageStoreOf(definition) === storage.name) uses.push({
|
|
1976
|
+
...owner,
|
|
1977
|
+
field: "meta"
|
|
1978
|
+
});
|
|
1979
|
+
for (const field of definition.fields) {
|
|
1980
|
+
if (!isFileField(field) || field.storage !== storage.name) continue;
|
|
1981
|
+
uses.push({
|
|
1982
|
+
...owner,
|
|
1983
|
+
field: field.name
|
|
1984
|
+
});
|
|
1985
|
+
}
|
|
1986
|
+
}
|
|
1987
|
+
return uses;
|
|
1988
|
+
};
|
|
1989
|
+
/**
|
|
1990
|
+
* Where a use keeps the file's id, like `cover.file` or `meta.image.file`.
|
|
1991
|
+
*/
|
|
1992
|
+
const filePathOf = (use) => use.field === "meta" ? "meta.image.file" : `${use.field}.file`;
|
|
1993
|
+
/**
|
|
1994
|
+
* The id of the file a document keeps for a use, or `undefined` when it keeps none.
|
|
1995
|
+
*/
|
|
1996
|
+
const fileIdOf = (document, use) => {
|
|
1997
|
+
const value = document?.[use.field];
|
|
1998
|
+
return (use.field === "meta" ? value?.["image"] : value)?.["file"];
|
|
1999
|
+
};
|
|
2000
|
+
/**
|
|
2001
|
+
* The first place that still uses a file, or `undefined` when nothing does.
|
|
2002
|
+
*/
|
|
2003
|
+
const firstUseOf = async (db, uses, id) => {
|
|
2004
|
+
for (const use of uses) {
|
|
2005
|
+
if (use.global !== void 0) {
|
|
2006
|
+
if (fileIdOf(await db.getGlobal(use.global), use) === id) return use;
|
|
2007
|
+
continue;
|
|
2008
|
+
}
|
|
2009
|
+
const { total } = await db.list(use.collection, {
|
|
2010
|
+
offset: 0,
|
|
2011
|
+
limit: 1
|
|
2012
|
+
}, { where: { [filePathOf(use)]: { equals: id } } });
|
|
2013
|
+
if (total > 0) return use;
|
|
2014
|
+
}
|
|
2015
|
+
};
|
|
2016
|
+
/**
|
|
2017
|
+
* The routes that upload, read, update and delete a store's files.
|
|
2018
|
+
*/
|
|
2019
|
+
const storageRoutes = (storage, options) => {
|
|
2020
|
+
const { db, basePath, access, collections, globals } = options;
|
|
2021
|
+
const collection = fileCollectionOf(storage);
|
|
2022
|
+
const storePath = `${basePath}/storage/${storage.name}`;
|
|
2023
|
+
const maxBytes = storage.maxBytes ?? 20971520;
|
|
2024
|
+
const uses = fileUsesOf(storage, collections, globals);
|
|
2025
|
+
const adapter = storage.adapter;
|
|
2026
|
+
const fileShape = {
|
|
2027
|
+
id: z.string(),
|
|
2028
|
+
createdAt: z.iso.datetime(),
|
|
2029
|
+
updatedAt: z.iso.datetime(),
|
|
2030
|
+
key: z.string(),
|
|
2031
|
+
url: z.string().describe("The file."),
|
|
2032
|
+
filename: z.string(),
|
|
2033
|
+
contentType: z.string(),
|
|
2034
|
+
fileSize: z.int(),
|
|
2035
|
+
width: z.int().optional(),
|
|
2036
|
+
height: z.int().optional(),
|
|
2037
|
+
uploadedBy: z.string().optional().describe("The editor who uploaded the file. Only reads behind a login carry it."),
|
|
2038
|
+
...editableShapeOf(storage, "read")
|
|
2039
|
+
};
|
|
2040
|
+
const FileSchema = Kizuna$1.model({
|
|
2041
|
+
title: fileModelNameOf(storage),
|
|
2042
|
+
schema: z.object(fileShape)
|
|
2043
|
+
});
|
|
2044
|
+
const storedNames = Object.keys(fileShape).filter((name) => name !== "url");
|
|
2045
|
+
/**
|
|
2046
|
+
* A file as a route answers it: the values its schema names and its URL. `withUploader` keeps who uploaded it.
|
|
2047
|
+
*/
|
|
2048
|
+
const fileBodyOf = async (document, withUploader) => ({
|
|
2049
|
+
...Object.fromEntries(storedNames.filter((name) => document[name] !== void 0 && (withUploader || name !== "uploadedBy")).map((name) => [name, document[name]])),
|
|
2050
|
+
url: await adapter.url(document["key"])
|
|
2051
|
+
});
|
|
2052
|
+
const notFound = (id) => ({
|
|
2053
|
+
status: 404,
|
|
2054
|
+
body: {
|
|
2055
|
+
type: "about:blank",
|
|
2056
|
+
title: "Not Found",
|
|
2057
|
+
status: 404,
|
|
2058
|
+
detail: `No file in '${storage.name}' has the id '${id}'.`
|
|
2059
|
+
}
|
|
2060
|
+
});
|
|
2061
|
+
const routes = {};
|
|
2062
|
+
/**
|
|
2063
|
+
* Whether a browser would run script in the file, which would let its URL act as the site.
|
|
2064
|
+
*/
|
|
2065
|
+
const isScriptable = (contentType, filename) => {
|
|
2066
|
+
if (SCRIPTABLE_EXTENSIONS.test(filename.toLowerCase())) return true;
|
|
2067
|
+
if (contentType === void 0) return false;
|
|
2068
|
+
const essence = contentType.split(";", 1)[0].trim().toLowerCase();
|
|
2069
|
+
return !MEDIA_TYPE.test(essence) || SCRIPTABLE_TYPES.has(essence) || essence.endsWith("+xml");
|
|
2070
|
+
};
|
|
2071
|
+
const typeRefused = (contentType) => ({
|
|
2072
|
+
status: 400,
|
|
2073
|
+
body: {
|
|
2074
|
+
type: "about:blank",
|
|
2075
|
+
title: "Bad Request",
|
|
2076
|
+
status: 400,
|
|
2077
|
+
detail: `'${storage.name}' takes ${storage.contentTypes?.join(", ")}, not ${contentType ?? "a file of unknown type"}.`
|
|
2078
|
+
}
|
|
2079
|
+
});
|
|
2080
|
+
const scriptRefused = () => ({
|
|
2081
|
+
status: 400,
|
|
2082
|
+
body: {
|
|
2083
|
+
type: "about:blank",
|
|
2084
|
+
title: "Bad Request",
|
|
2085
|
+
status: 400,
|
|
2086
|
+
detail: "SVG, HTML, XML and script files are not taken, because a browser runs script in them. A content type must be one media type, like `image/png`."
|
|
2087
|
+
}
|
|
2088
|
+
});
|
|
2089
|
+
if (access.create.kind !== "nobody") {
|
|
2090
|
+
routes["upload"] = route({
|
|
2091
|
+
method: "POST",
|
|
2092
|
+
path: `${storePath}/uploads`,
|
|
2093
|
+
summary: `Start an upload to ${storage.name}`,
|
|
2094
|
+
auth: routeAuthOf(access.create),
|
|
2095
|
+
body: z.strictObject({
|
|
2096
|
+
filename: z.string().min(1).max(200),
|
|
2097
|
+
contentType: z.string().min(1),
|
|
2098
|
+
fileSize: z.int().min(1).max(maxBytes)
|
|
2099
|
+
}),
|
|
2100
|
+
responses: {
|
|
2101
|
+
400: ProblemDetailsSchema,
|
|
2102
|
+
201: z.object({
|
|
2103
|
+
key: z.string().describe("Send this back to record the file once the upload is done."),
|
|
2104
|
+
url: z.string().describe("Upload the file here with PUT."),
|
|
2105
|
+
headers: z.record(z.string(), z.string()).describe("Send these headers with the PUT.")
|
|
2106
|
+
})
|
|
2107
|
+
}
|
|
2108
|
+
}).handler(async ({ body }) => {
|
|
2109
|
+
if (isScriptable(body.contentType, body.filename)) return scriptRefused();
|
|
2110
|
+
if (!acceptsType(storage, body.contentType)) return typeRefused(body.contentType);
|
|
2111
|
+
const key = newFileKey(storage, body.filename);
|
|
2112
|
+
return {
|
|
2113
|
+
status: 201,
|
|
2114
|
+
body: {
|
|
2115
|
+
key,
|
|
2116
|
+
...await adapter.presignUpload({
|
|
2117
|
+
key,
|
|
2118
|
+
contentType: body.contentType,
|
|
2119
|
+
fileSize: body.fileSize,
|
|
2120
|
+
expiresIn: 900
|
|
2121
|
+
})
|
|
2122
|
+
}
|
|
2123
|
+
};
|
|
2124
|
+
});
|
|
2125
|
+
routes["create"] = route({
|
|
2126
|
+
method: "POST",
|
|
2127
|
+
path: storePath,
|
|
2128
|
+
summary: `Record a file uploaded to ${storage.name}`,
|
|
2129
|
+
auth: routeAuthOf(access.create),
|
|
2130
|
+
body: z.strictObject({
|
|
2131
|
+
key: z.string(),
|
|
2132
|
+
filename: z.string().min(1).max(200),
|
|
2133
|
+
...editableShapeOf(storage, "create")
|
|
2134
|
+
}),
|
|
2135
|
+
responses: {
|
|
2136
|
+
201: FileSchema,
|
|
2137
|
+
400: ProblemDetailsSchema
|
|
2138
|
+
}
|
|
2139
|
+
}).handler(async ({ body, auth }) => {
|
|
2140
|
+
const refuse = (detail) => ({
|
|
2141
|
+
status: 400,
|
|
2142
|
+
body: {
|
|
2143
|
+
type: "about:blank",
|
|
2144
|
+
title: "Bad Request",
|
|
2145
|
+
status: 400,
|
|
2146
|
+
detail
|
|
2147
|
+
}
|
|
2148
|
+
});
|
|
2149
|
+
const editor = auth?.["editor"];
|
|
2150
|
+
const uploader = editor?.id === void 0 ? {} : { uploadedBy: editor.id };
|
|
2151
|
+
if (!issuedKeyPattern(storage.name).test(body.key)) return refuse(`The key '${body.key}' was not handed out by '${storage.name}'.`);
|
|
2152
|
+
const recorded = await db.list(collection, {
|
|
2153
|
+
offset: 0,
|
|
2154
|
+
limit: 1
|
|
2155
|
+
}, { where: { key: { equals: body.key } } });
|
|
2156
|
+
const recordedAlready = () => refuse(`The file under '${body.key}' is recorded already.`);
|
|
2157
|
+
if (recorded.total > 0) return recordedAlready();
|
|
2158
|
+
const uploaded = await adapter.head(body.key);
|
|
2159
|
+
if (uploaded === void 0) return refuse(`Nothing was uploaded under '${body.key}'.`);
|
|
2160
|
+
if (isScriptable(uploaded.contentType, body.filename)) {
|
|
2161
|
+
await adapter.delete(body.key);
|
|
2162
|
+
return scriptRefused();
|
|
2163
|
+
}
|
|
2164
|
+
if (uploaded.fileSize > maxBytes) {
|
|
2165
|
+
await adapter.delete(body.key);
|
|
2166
|
+
return refuse(`The file is ${uploaded.fileSize} bytes, and '${storage.name}' takes at most ${maxBytes}.`);
|
|
2167
|
+
}
|
|
2168
|
+
const header = await adapter.read(body.key, IMAGE_HEADER_BYTES);
|
|
2169
|
+
const image = header === void 0 ? void 0 : imageSizeOf(header);
|
|
2170
|
+
if (image !== void 0 && image.width * image.height > 1e8) {
|
|
2171
|
+
await adapter.delete(body.key);
|
|
2172
|
+
return refuse(`The image is ${image.width} by ${image.height} pixels, more than the ${MAX_IMAGE_PIXELS / 1e6} megapixels a store takes.`);
|
|
2173
|
+
}
|
|
2174
|
+
const contentType = image?.contentType ?? uploaded.contentType;
|
|
2175
|
+
if (!acceptsType(storage, contentType)) {
|
|
2176
|
+
await adapter.delete(body.key);
|
|
2177
|
+
return typeRefused(contentType);
|
|
2178
|
+
}
|
|
2179
|
+
let fileSize = uploaded.fileSize;
|
|
2180
|
+
if (storage.stripExif !== false && contentType !== void 0 && STRIPPED_TYPES.includes(contentType)) {
|
|
2181
|
+
const original = await adapter.read(body.key, Number.POSITIVE_INFINITY);
|
|
2182
|
+
let stripped;
|
|
2183
|
+
try {
|
|
2184
|
+
stripped = original === void 0 ? void 0 : stripImageMetadata(original, contentType);
|
|
2185
|
+
} catch {
|
|
2186
|
+
await adapter.delete(body.key);
|
|
2187
|
+
return refuse("The image's metadata can't be read, so the location in it can't be removed.");
|
|
2188
|
+
}
|
|
2189
|
+
if (stripped !== void 0) {
|
|
2190
|
+
await adapter.put(body.key, stripped, contentType);
|
|
2191
|
+
fileSize = stripped.byteLength;
|
|
2192
|
+
}
|
|
2193
|
+
}
|
|
2194
|
+
let created;
|
|
2195
|
+
try {
|
|
2196
|
+
created = await db.create(collection, {
|
|
2197
|
+
...body,
|
|
2198
|
+
contentType: contentType ?? "application/octet-stream",
|
|
2199
|
+
fileSize,
|
|
2200
|
+
...image === void 0 ? {} : {
|
|
2201
|
+
width: image.width,
|
|
2202
|
+
height: image.height
|
|
2203
|
+
},
|
|
2204
|
+
...uploader
|
|
2205
|
+
});
|
|
2206
|
+
} catch (error) {
|
|
2207
|
+
if (error instanceof ConflictError) return recordedAlready();
|
|
2208
|
+
throw error;
|
|
2209
|
+
}
|
|
2210
|
+
return {
|
|
2211
|
+
status: 201,
|
|
2212
|
+
body: await fileBodyOf(created, access.create.kind !== "public")
|
|
2213
|
+
};
|
|
2214
|
+
});
|
|
2215
|
+
}
|
|
2216
|
+
if (access.read.kind !== "nobody") {
|
|
2217
|
+
const readsUploader = access.read.kind !== "public";
|
|
2218
|
+
routes["list"] = route({
|
|
2219
|
+
method: "GET",
|
|
2220
|
+
path: storePath,
|
|
2221
|
+
summary: `List the files in ${storage.name}`,
|
|
2222
|
+
auth: routeAuthOf(access.read),
|
|
2223
|
+
query: z.object({
|
|
2224
|
+
offset: z.int().min(0).default(0),
|
|
2225
|
+
limit: z.int().min(1).max(100).default(20),
|
|
2226
|
+
sort: z.array(z.enum(FILE_SORT_KEYS)).optional().describe("Fields to sort by. `-` in front reverses one."),
|
|
2227
|
+
where: whereSchemaOf({
|
|
2228
|
+
name: storage.name,
|
|
2229
|
+
model: fileModelNameOf(storage),
|
|
2230
|
+
fields: filterFieldsOf(storage)
|
|
2231
|
+
}).optional().describe("Which files to read, like `{ \"filename\": { \"contains\": \"harbour\" } }`.")
|
|
2232
|
+
}),
|
|
2233
|
+
responses: { 200: {
|
|
2234
|
+
body: z.object({
|
|
2235
|
+
items: z.array(FileSchema),
|
|
2236
|
+
total: z.int()
|
|
2237
|
+
}),
|
|
2238
|
+
cache: readCacheOf(access.read)
|
|
2239
|
+
} },
|
|
2240
|
+
tool: toolOf(void 0, "read")
|
|
2241
|
+
}).handler(async ({ query }) => {
|
|
2242
|
+
const page = await db.list(collection, {
|
|
2243
|
+
offset: query.offset,
|
|
2244
|
+
limit: query.limit
|
|
2245
|
+
}, {
|
|
2246
|
+
...query.sort === void 0 ? {} : { sort: query.sort },
|
|
2247
|
+
...query.where === void 0 ? {} : { where: query.where }
|
|
2248
|
+
});
|
|
2249
|
+
return {
|
|
2250
|
+
status: 200,
|
|
2251
|
+
body: {
|
|
2252
|
+
items: await Promise.all(page.items.map((item) => fileBodyOf(item, readsUploader))),
|
|
2253
|
+
total: page.total
|
|
2254
|
+
}
|
|
2255
|
+
};
|
|
2256
|
+
});
|
|
2257
|
+
routes["get"] = route({
|
|
2258
|
+
method: "GET",
|
|
2259
|
+
path: `${storePath}/:id`,
|
|
2260
|
+
summary: `Get a file from ${storage.name}`,
|
|
2261
|
+
auth: routeAuthOf(access.read),
|
|
2262
|
+
pathParams: z.object({ id: z.string() }),
|
|
2263
|
+
responses: {
|
|
2264
|
+
200: {
|
|
2265
|
+
body: FileSchema,
|
|
2266
|
+
cache: readCacheOf(access.read)
|
|
2267
|
+
},
|
|
2268
|
+
404: ProblemDetailsSchema
|
|
2269
|
+
}
|
|
2270
|
+
}).handler(async ({ params }) => {
|
|
2271
|
+
const document = await db.get(collection, params.id);
|
|
2272
|
+
return document === void 0 ? notFound(params.id) : {
|
|
2273
|
+
status: 200,
|
|
2274
|
+
body: await fileBodyOf(document, readsUploader)
|
|
2275
|
+
};
|
|
2276
|
+
});
|
|
2277
|
+
}
|
|
2278
|
+
if (access.update.kind !== "nobody") routes["update"] = route({
|
|
2279
|
+
method: "PATCH",
|
|
2280
|
+
path: `${storePath}/:id`,
|
|
2281
|
+
summary: `Change a file's details in ${storage.name}`,
|
|
2282
|
+
auth: routeAuthOf(access.update),
|
|
2283
|
+
pathParams: z.object({ id: z.string() }),
|
|
2284
|
+
body: z.strictObject(editableShapeOf(storage, "update")),
|
|
2285
|
+
responses: {
|
|
2286
|
+
200: FileSchema,
|
|
2287
|
+
403: ProblemDetailsSchema,
|
|
2288
|
+
404: ProblemDetailsSchema
|
|
2289
|
+
}
|
|
2290
|
+
}).handler(async ({ params, body, auth }) => {
|
|
2291
|
+
const stored = await db.get(collection, params.id);
|
|
2292
|
+
const grant = await writeGrantOf(access.update, auth, async () => stored);
|
|
2293
|
+
if (grant === "none") return notFound(params.id);
|
|
2294
|
+
const handedOver = grant === "document" ? changedDocumentFieldOf(access.update, body, stored) : void 0;
|
|
2295
|
+
if (handedOver !== void 0) return {
|
|
2296
|
+
status: 403,
|
|
2297
|
+
body: {
|
|
2298
|
+
type: "about:blank",
|
|
2299
|
+
title: "Forbidden",
|
|
2300
|
+
status: 403,
|
|
2301
|
+
detail: `You may change the file '${params.id}' in '${storage.name}' because '${handedOver}' names you, so you may not change '${handedOver}'.`
|
|
2302
|
+
}
|
|
2303
|
+
};
|
|
2304
|
+
const updated = await db.update(collection, params.id, body);
|
|
2305
|
+
return updated === void 0 ? notFound(params.id) : {
|
|
2306
|
+
status: 200,
|
|
2307
|
+
body: await fileBodyOf(updated, access.update.kind !== "public")
|
|
2308
|
+
};
|
|
2309
|
+
});
|
|
2310
|
+
if (access.delete.kind !== "nobody") routes["delete"] = route({
|
|
2311
|
+
method: "DELETE",
|
|
2312
|
+
path: `${storePath}/:id`,
|
|
2313
|
+
summary: `Delete a file from ${storage.name}`,
|
|
2314
|
+
auth: routeAuthOf(access.delete),
|
|
2315
|
+
pathParams: z.object({ id: z.string() }),
|
|
2316
|
+
responses: {
|
|
2317
|
+
204: z.void(),
|
|
2318
|
+
404: ProblemDetailsSchema,
|
|
2319
|
+
409: ProblemDetailsSchema
|
|
2320
|
+
}
|
|
2321
|
+
}).handler(async ({ params, auth }) => {
|
|
2322
|
+
const document = await db.get(collection, params.id);
|
|
2323
|
+
if (document === void 0 || !await mayWriteDocument(access.delete, auth, async () => document)) return notFound(params.id);
|
|
2324
|
+
const use = await firstUseOf(db, uses, params.id);
|
|
2325
|
+
if (use !== void 0) return {
|
|
2326
|
+
status: 409,
|
|
2327
|
+
body: {
|
|
2328
|
+
type: "about:blank",
|
|
2329
|
+
title: "Conflict",
|
|
2330
|
+
status: 409,
|
|
2331
|
+
detail: `The file is still used by ${use.field === "meta" ? "the share image" : `'${use.field}'`} in ${use.global === void 0 ? `the collection '${use.collection}'` : `the global '${use.global}'`}. Remove it there first.`
|
|
2332
|
+
}
|
|
2333
|
+
};
|
|
2334
|
+
await db.delete(collection, params.id);
|
|
2335
|
+
await adapter.delete(document["key"]);
|
|
2336
|
+
return { status: 204 };
|
|
2337
|
+
});
|
|
2338
|
+
return groupedRoutes(STORAGE_GROUP, storage.name, routes);
|
|
2339
|
+
};
|
|
2340
|
+
//#endregion
|
|
2341
|
+
//#region src/define-config.ts
|
|
2342
|
+
const k = new Kizuna$1();
|
|
2343
|
+
const BASE_PATH_PATTERN = /^(\/[a-zA-Z0-9_-]+)+$/;
|
|
2344
|
+
const collectionGroupsOf = (collections) => Object.fromEntries(collections.map((collection) => [collection.name, labelsOf(collection).plural]));
|
|
2345
|
+
const checkCollectionNames = (collections) => {
|
|
2346
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2347
|
+
for (const collection of collections) {
|
|
2348
|
+
if (seen.has(collection.name)) throw new Error(`Two collections are named '${collection.name}'. Give each its own name.`);
|
|
2349
|
+
seen.add(collection.name);
|
|
2350
|
+
}
|
|
2351
|
+
};
|
|
2352
|
+
/**
|
|
2353
|
+
* Files each grouped collection's routes as a subgroup of its group.
|
|
2354
|
+
*/
|
|
2355
|
+
const withCollectionSubgroups = (appGroups, collections) => {
|
|
2356
|
+
const merged = { ...appGroups };
|
|
2357
|
+
for (const collection of collections) {
|
|
2358
|
+
if (collection.group === void 0) continue;
|
|
2359
|
+
const declared = merged[collection.group];
|
|
2360
|
+
if (declared === void 0) {
|
|
2361
|
+
const names = Object.keys(appGroups);
|
|
2362
|
+
throw new Error(`Collection '${collection.name}' is in the group '${collection.group}', and \`groups\` declares no group of that name.${names.length === 0 ? " Declare it with `k.groups`." : ` Use one of: ${names.join(", ")}.`}`);
|
|
2363
|
+
}
|
|
2364
|
+
const options = typeof declared === "string" ? { title: declared } : declared;
|
|
2365
|
+
const subgroups = options.groups ?? {};
|
|
2366
|
+
if (subgroups[collection.name] !== void 0) throw new Error(`The group '${collection.group}' already has a group named '${collection.name}', where the collection's routes would go. Rename one.`);
|
|
2367
|
+
merged[collection.group] = {
|
|
2368
|
+
...options,
|
|
2369
|
+
groups: {
|
|
2370
|
+
...subgroups,
|
|
2371
|
+
[collection.name]: labelsOf(collection).plural
|
|
2372
|
+
}
|
|
2373
|
+
};
|
|
2374
|
+
}
|
|
2375
|
+
return merged;
|
|
2376
|
+
};
|
|
2377
|
+
/**
|
|
2378
|
+
* What an error calls the thing a field belongs to.
|
|
2379
|
+
*/
|
|
2380
|
+
const kindLabelOf = (definition) => ({
|
|
2381
|
+
collection: "Collection",
|
|
2382
|
+
global: "Global",
|
|
2383
|
+
storage: "Storage"
|
|
2384
|
+
})[definition.kind] ?? "Definition";
|
|
2385
|
+
/**
|
|
2386
|
+
* Checks that every relationship points at a collection the CMS holds.
|
|
2387
|
+
*/
|
|
2388
|
+
const checkRelationships = (collections, globals) => {
|
|
2389
|
+
const names = collections.map((collection) => collection.name);
|
|
2390
|
+
for (const definition of [...collections, ...globals]) for (const field of definition.fields) {
|
|
2391
|
+
if (field.type !== "relationship" || names.includes(field.to)) continue;
|
|
2392
|
+
throw new Error(`${kindLabelOf(definition)} '${definition.name}' points '${field.name}' at '${field.to}', and no collection has that name. Use one of: ${names.join(", ")}.`);
|
|
2393
|
+
}
|
|
2394
|
+
};
|
|
2395
|
+
/**
|
|
2396
|
+
* Checks that store names are unique and that every image and file field names a store.
|
|
2397
|
+
*/
|
|
2398
|
+
const checkStorage = (storage, collections, globals) => {
|
|
2399
|
+
const names = /* @__PURE__ */ new Set();
|
|
2400
|
+
for (const store of storage) {
|
|
2401
|
+
if (names.has(store.name)) throw new Error(`Two stores are named '${store.name}'. Give each its own name.`);
|
|
2402
|
+
names.add(store.name);
|
|
2403
|
+
}
|
|
2404
|
+
for (const definition of [...collections, ...globals]) {
|
|
2405
|
+
const metaStore = metaImageStoreOf(definition);
|
|
2406
|
+
if (metaStore === void 0) continue;
|
|
2407
|
+
if (storage.find((candidate) => candidate.name === metaStore) === void 0) throw new Error(`${kindLabelOf(definition)} '${definition.name}' keeps its meta image in '${metaStore}', and \`storage\` lists no store of images by that name.`);
|
|
2408
|
+
}
|
|
2409
|
+
for (const definition of [
|
|
2410
|
+
...collections,
|
|
2411
|
+
...globals,
|
|
2412
|
+
...storage
|
|
2413
|
+
]) for (const field of definition.fields ?? []) {
|
|
2414
|
+
if (!isFileField(field)) continue;
|
|
2415
|
+
const owner = kindLabelOf(definition);
|
|
2416
|
+
if (storage.find((candidate) => candidate.name === field.storage) === void 0) throw new Error(`${owner} '${definition.name}' keeps '${field.name}' in the store '${field.storage}', and \`storage\` lists no store of that name. Add it there.`);
|
|
2417
|
+
}
|
|
2418
|
+
};
|
|
2419
|
+
const globalGroupsOf = (globals) => Object.fromEntries(globals.map((global) => [global.name, global.label ?? global.name]));
|
|
2420
|
+
const checkGlobalNames = (globals) => {
|
|
2421
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2422
|
+
for (const global of globals) {
|
|
2423
|
+
if (seen.has(global.name)) throw new Error(`Two globals are named '${global.name}'. Give each its own name.`);
|
|
2424
|
+
seen.add(global.name);
|
|
2425
|
+
}
|
|
2426
|
+
};
|
|
2427
|
+
/**
|
|
2428
|
+
* Creates a CMS from its collections, globals, stores and users. It takes every Kizuna.js `defineConfig` option too,
|
|
2429
|
+
* and serves each collection's routes beside the app's own.
|
|
2430
|
+
*
|
|
2431
|
+
* @example
|
|
2432
|
+
* export default defineConfig({
|
|
2433
|
+
* name: 'Example',
|
|
2434
|
+
* db: postgresAdapter(drizzle(process.env.DATABASE_URL)),
|
|
2435
|
+
* collections: [Articles, Users],
|
|
2436
|
+
* users: Users,
|
|
2437
|
+
* roles: ['editor'],
|
|
2438
|
+
* });
|
|
2439
|
+
*/
|
|
2440
|
+
const defineConfig = (options) => {
|
|
2441
|
+
const { name, db, collections: declaredCollections, globals: declaredGlobals, meta, slugs, users: declaredUsers, roles: declaredRoles, documentRoles, storage = [], basePath = "", baseUrl, ...config } = options;
|
|
2442
|
+
if (basePath !== "" && !BASE_PATH_PATTERN.test(basePath)) throw new Error(`\`basePath\` is '${basePath}'. Write it like \`/cms\`: a leading slash and no trailing one.`);
|
|
2443
|
+
if (baseUrl !== void 0 && !/^https?:\/\/[^/?#]+(\/[^?#]*[^/?#])?$/.test(baseUrl)) throw new Error(`\`baseUrl\` is '${baseUrl}'. Write it like \`https://cms.example.com\`, with no trailing slash.`);
|
|
2444
|
+
const globals = declaredGlobals ?? [];
|
|
2445
|
+
checkGlobalNames(globals);
|
|
2446
|
+
if (declaredUsers === void 0) throw new Error("`users` names no collection. Name the login collection users log in to the admin from, like `users: Users`.");
|
|
2447
|
+
if (!declaredCollections.includes(declaredUsers)) throw new Error(`\`users\` names collection '${declaredUsers.name}', which \`collections\` leaves out. Add it there.`);
|
|
2448
|
+
if (declaredUsers.login === void 0) throw new Error(`\`users\` names collection '${declaredUsers.name}', which doesn't log in. Give it \`login: true\`.`);
|
|
2449
|
+
const roles = withAdminRole(declaredRoles);
|
|
2450
|
+
const roleNames = roleNamesOf(roles);
|
|
2451
|
+
const withLogin = (collection) => collection === declaredUsers ? withAccountFields(collection, roleNames) : collection.login === void 0 ? collection : withAccountFields(collection);
|
|
2452
|
+
const collections = declaredCollections.map(withLogin);
|
|
2453
|
+
const usersCollection = collections[declaredCollections.indexOf(declaredUsers)];
|
|
2454
|
+
const loginCollections = collections.filter((collection) => collection.login !== void 0);
|
|
2455
|
+
const identityOf = (collection) => collection === usersCollection ? EDITOR_IDENTITY : loginIdentityNameOf(collection);
|
|
2456
|
+
for (const collection of collections) if (meta !== void 0 && collection.meta !== void 0) setTitleSuffix(collection, meta);
|
|
2457
|
+
for (const definition of [...collections, ...globals]) if (slugs !== void 0) setSlugOptions(definition, slugs);
|
|
2458
|
+
const appGroups = config.groups?.declared ?? {};
|
|
2459
|
+
for (const reserved of [
|
|
2460
|
+
COLLECTIONS_GROUP,
|
|
2461
|
+
GLOBALS_GROUP,
|
|
2462
|
+
STORAGE_GROUP
|
|
2463
|
+
]) if (appGroups[reserved] !== void 0) throw new Error(`The CMS files its routes under the group '${reserved}', and \`groups\` declares a group of the same name. Rename yours.`);
|
|
2464
|
+
checkRelationships(collections, globals);
|
|
2465
|
+
checkStorage(storage, collections, globals);
|
|
2466
|
+
registerStores(storage);
|
|
2467
|
+
db.prepare?.({
|
|
2468
|
+
collections,
|
|
2469
|
+
globals,
|
|
2470
|
+
storage,
|
|
2471
|
+
editors: usersCollection.name,
|
|
2472
|
+
logins: loginCollections.map((collection) => collection.name)
|
|
2473
|
+
});
|
|
2474
|
+
setEditorsCollection(db, usersCollection);
|
|
2475
|
+
const catalog = permissionCatalogOf(roles);
|
|
2476
|
+
const access = accessOf({
|
|
2477
|
+
roles,
|
|
2478
|
+
documentRoles,
|
|
2479
|
+
collections,
|
|
2480
|
+
globals
|
|
2481
|
+
});
|
|
2482
|
+
const appAuth = config.auth;
|
|
2483
|
+
const loginIdentities = {};
|
|
2484
|
+
for (const collection of loginCollections) {
|
|
2485
|
+
const identity = identityOf(collection);
|
|
2486
|
+
if (appAuth?.identities?.[identity] !== void 0) throw new Error(`\`auth.identities\` declares '${identity}', the identity the CMS declares for ${collection === usersCollection ? "its editors" : `collection '${collection.name}'`}. Rename yours, and they log in through the CMS.`);
|
|
2487
|
+
if (loginIdentities[identity] !== void 0) throw new Error(`Collection '${collection.name}' would log in as '${identity}', which another login collection already does. Rename one.`);
|
|
2488
|
+
loginIdentities[identity] = loginIdentityOf(db, collection, collection === usersCollection ? roles : void 0);
|
|
2489
|
+
}
|
|
2490
|
+
const auth = {
|
|
2491
|
+
...appAuth,
|
|
2492
|
+
identities: {
|
|
2493
|
+
...appAuth?.identities,
|
|
2494
|
+
...loginIdentities
|
|
2495
|
+
}
|
|
2496
|
+
};
|
|
2497
|
+
checkCollectionNames(collections);
|
|
2498
|
+
const groups = k.groups({
|
|
2499
|
+
...withCollectionSubgroups(appGroups, collections),
|
|
2500
|
+
...collections.some((collection) => collection.group === void 0) ? { [COLLECTIONS_GROUP]: {
|
|
2501
|
+
title: "Collections",
|
|
2502
|
+
groups: collectionGroupsOf(collections.filter((collection) => collection.group === void 0))
|
|
2503
|
+
} } : {},
|
|
2504
|
+
...globals.length === 0 ? {} : { [GLOBALS_GROUP]: {
|
|
2505
|
+
title: "Globals",
|
|
2506
|
+
groups: globalGroupsOf(globals)
|
|
2507
|
+
} },
|
|
2508
|
+
...storage.length === 0 ? {} : { [STORAGE_GROUP]: {
|
|
2509
|
+
title: "Storage",
|
|
2510
|
+
groups: Object.fromEntries(storage.map((store) => [store.name, store.name]))
|
|
2511
|
+
} }
|
|
2512
|
+
});
|
|
2513
|
+
const relationshipsTo = (collection) => [...collections, ...globals].flatMap((definition) => definition.fields.filter((field) => field.type === "relationship" && field.to === collection.name).map((field) => ({
|
|
2514
|
+
...definition.kind === "global" ? { global: definition.name } : { collection: definition.name },
|
|
2515
|
+
field: field.name,
|
|
2516
|
+
many: field.type === "relationship" && field.many === true
|
|
2517
|
+
})));
|
|
2518
|
+
const accounts = new Map(loginCollections.map((collection) => [collection, accountsOf({
|
|
2519
|
+
db,
|
|
2520
|
+
collection,
|
|
2521
|
+
identity: identityOf(collection),
|
|
2522
|
+
isEditorsCollection: collection === usersCollection,
|
|
2523
|
+
basePath
|
|
2524
|
+
})]));
|
|
2525
|
+
const routeOptionsOf = (collection) => ({
|
|
2526
|
+
db,
|
|
2527
|
+
basePath,
|
|
2528
|
+
access: access.ofCollection(collection),
|
|
2529
|
+
pointedAtBy: relationshipsTo(collection),
|
|
2530
|
+
...accounts.has(collection) ? { accounts: accounts.get(collection).writes } : {}
|
|
2531
|
+
});
|
|
2532
|
+
const contentRoutes = [...collections.map((collection) => collectionRoutes(collection, routeOptionsOf(collection))), ...globals.map((global) => globalRoutes(global, {
|
|
2533
|
+
db,
|
|
2534
|
+
basePath,
|
|
2535
|
+
access: access.ofGlobal(global)
|
|
2536
|
+
}))];
|
|
2537
|
+
const fileRoutes = storage.map((store) => storageRoutes(store, {
|
|
2538
|
+
db,
|
|
2539
|
+
basePath,
|
|
2540
|
+
access: access.ofCollection({
|
|
2541
|
+
kind: "store",
|
|
2542
|
+
name: store.name,
|
|
2543
|
+
fields: store.fields ?? [],
|
|
2544
|
+
auth: store.auth
|
|
2545
|
+
}),
|
|
2546
|
+
collections,
|
|
2547
|
+
globals
|
|
2548
|
+
}));
|
|
2549
|
+
const typescript = config.typescript;
|
|
2550
|
+
return {
|
|
2551
|
+
...defineConfig$1({
|
|
2552
|
+
...config,
|
|
2553
|
+
auth,
|
|
2554
|
+
groups,
|
|
2555
|
+
routes: [
|
|
2556
|
+
...config.routes ?? [],
|
|
2557
|
+
...contentRoutes,
|
|
2558
|
+
...fileRoutes
|
|
2559
|
+
],
|
|
2560
|
+
typescript: {
|
|
2561
|
+
...typescript,
|
|
2562
|
+
extend: [...typescript?.extend ?? [], { cms: {
|
|
2563
|
+
collections: collections.map((collection) => collection.name),
|
|
2564
|
+
globals: globals.map((global) => global.name),
|
|
2565
|
+
roles: roleNames,
|
|
2566
|
+
documentRoles: Object.keys(documentRoles ?? {}),
|
|
2567
|
+
...catalog === void 0 ? {} : { permissions: catalog },
|
|
2568
|
+
storage: Object.fromEntries(storage.map((store) => [store.name, storeFieldTypesOf(store)]))
|
|
2569
|
+
} }]
|
|
2570
|
+
}
|
|
2571
|
+
}),
|
|
2572
|
+
editors: accounts.get(usersCollection).api,
|
|
2573
|
+
cms: {
|
|
2574
|
+
name,
|
|
2575
|
+
basePath,
|
|
2576
|
+
db,
|
|
2577
|
+
collections,
|
|
2578
|
+
globals,
|
|
2579
|
+
slugs,
|
|
2580
|
+
meta,
|
|
2581
|
+
groups: Object.entries(appGroups).filter(([group]) => collections.some((collection) => collection.group === group)).map(([group, declared]) => ({
|
|
2582
|
+
name: group,
|
|
2583
|
+
title: typeof declared === "string" ? declared : declared.title
|
|
2584
|
+
})),
|
|
2585
|
+
users: usersCollection,
|
|
2586
|
+
roles,
|
|
2587
|
+
documentRoles,
|
|
2588
|
+
storage
|
|
2589
|
+
}
|
|
2590
|
+
};
|
|
2591
|
+
};
|
|
2592
|
+
//#endregion
|
|
2593
|
+
//#region src/kizuna.ts
|
|
2594
|
+
/**
|
|
2595
|
+
* Declares the collections, globals, file stores and routes of a CMS.
|
|
2596
|
+
*
|
|
2597
|
+
* @example
|
|
2598
|
+
* import { Kizuna } from 'kizunacms';
|
|
2599
|
+
* import type { Config } from './kizuna.types';
|
|
2600
|
+
*
|
|
2601
|
+
* export const k = new Kizuna<Config>();
|
|
2602
|
+
*
|
|
2603
|
+
* export const Articles = k.collection({
|
|
2604
|
+
* name: 'articles',
|
|
2605
|
+
* auth: {
|
|
2606
|
+
* read: ['public'],
|
|
2607
|
+
* create: ['editor'],
|
|
2608
|
+
* update: ['editor'],
|
|
2609
|
+
* delete: ['editor'],
|
|
2610
|
+
* },
|
|
2611
|
+
* fields: [
|
|
2612
|
+
* {
|
|
2613
|
+
* name: 'title',
|
|
2614
|
+
* type: 'text',
|
|
2615
|
+
* required: true,
|
|
2616
|
+
* },
|
|
2617
|
+
* ],
|
|
2618
|
+
* });
|
|
2619
|
+
*/
|
|
2620
|
+
var Kizuna = class extends Kizuna$1 {
|
|
2621
|
+
/**
|
|
2622
|
+
* Declares a collection of documents that share the same fields.
|
|
2623
|
+
*
|
|
2624
|
+
* @example
|
|
2625
|
+
* export const Articles = k.collection({
|
|
2626
|
+
* name: 'articles',
|
|
2627
|
+
* auth: {
|
|
2628
|
+
* read: ['public'],
|
|
2629
|
+
* create: ['editor'],
|
|
2630
|
+
* update: ['editor'],
|
|
2631
|
+
* delete: ['editor'],
|
|
2632
|
+
* },
|
|
2633
|
+
* fields: [
|
|
2634
|
+
* {
|
|
2635
|
+
* name: 'title',
|
|
2636
|
+
* type: 'text',
|
|
2637
|
+
* required: true,
|
|
2638
|
+
* },
|
|
2639
|
+
* {
|
|
2640
|
+
* name: 'author',
|
|
2641
|
+
* type: 'relationship',
|
|
2642
|
+
* to: 'authors',
|
|
2643
|
+
* },
|
|
2644
|
+
* ],
|
|
2645
|
+
* });
|
|
2646
|
+
*/
|
|
2647
|
+
collection(definition) {
|
|
2648
|
+
return defineCollection(definition);
|
|
2649
|
+
}
|
|
2650
|
+
/**
|
|
2651
|
+
* Declares a global: a single document with no list.
|
|
2652
|
+
*
|
|
2653
|
+
* @example
|
|
2654
|
+
* export const Settings = k.global({
|
|
2655
|
+
* name: 'settings',
|
|
2656
|
+
* auth: {
|
|
2657
|
+
* read: ['public'],
|
|
2658
|
+
* update: ['editor'],
|
|
2659
|
+
* },
|
|
2660
|
+
* label: 'Settings',
|
|
2661
|
+
* fields: [
|
|
2662
|
+
* {
|
|
2663
|
+
* name: 'siteName',
|
|
2664
|
+
* type: 'text',
|
|
2665
|
+
* },
|
|
2666
|
+
* ],
|
|
2667
|
+
* });
|
|
2668
|
+
*/
|
|
2669
|
+
global(definition) {
|
|
2670
|
+
return defineGlobal(definition);
|
|
2671
|
+
}
|
|
2672
|
+
/**
|
|
2673
|
+
* Declares a store that image and file fields upload to.
|
|
2674
|
+
*
|
|
2675
|
+
* @example
|
|
2676
|
+
* export const Images = k.storage({
|
|
2677
|
+
* name: 'images',
|
|
2678
|
+
* auth: {
|
|
2679
|
+
* read: ['public'],
|
|
2680
|
+
* create: ['editor'],
|
|
2681
|
+
* update: ['editor'],
|
|
2682
|
+
* delete: ['editor'],
|
|
2683
|
+
* },
|
|
2684
|
+
* adapter: s3Storage({
|
|
2685
|
+
* bucket: 'example-images',
|
|
2686
|
+
* }),
|
|
2687
|
+
* });
|
|
2688
|
+
*
|
|
2689
|
+
* // an image field names it
|
|
2690
|
+
* {
|
|
2691
|
+
* name: 'cover',
|
|
2692
|
+
* type: 'image',
|
|
2693
|
+
* storage: 'images',
|
|
2694
|
+
* }
|
|
2695
|
+
*/
|
|
2696
|
+
storage(definition) {
|
|
2697
|
+
return defineStorage(definition);
|
|
2698
|
+
}
|
|
2699
|
+
};
|
|
2700
|
+
//#endregion
|
|
2701
|
+
export { GLOBALS_COLLECTION, Kizuna, SlugSchema, columnOf, defineConfig, diskStorage, documentSchemaOf, hashPassword, imageSizeOf, labelsOf, memoryAdapter, memoryStorage, schemaOf, verifyPassword };
|