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