kizunacms 0.0.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.MD +9 -0
- package/README.md +208 -0
- package/dist/access-4YiqVHXB.d.mts +1251 -0
- package/dist/access-CrrWP0hv.d.cts +1251 -0
- package/dist/db-Cnv0aXba.cjs +1603 -0
- package/dist/db-wUR_ude-.mjs +1274 -0
- package/dist/index.cjs +2716 -0
- package/dist/index.d.cts +545 -0
- package/dist/index.d.mts +545 -0
- package/dist/index.mjs +2701 -0
- package/dist/postgres.cjs +1152 -0
- package/dist/postgres.d.cts +99 -0
- package/dist/postgres.d.mts +99 -0
- package/dist/postgres.mjs +1151 -0
- package/package.json +96 -3
|
@@ -0,0 +1,1603 @@
|
|
|
1
|
+
//#region \0rolldown/runtime.js
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __copyProps = (to, from, except, desc) => {
|
|
9
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
10
|
+
key = keys[i];
|
|
11
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
12
|
+
get: ((k) => from[k]).bind(null, key),
|
|
13
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
19
|
+
value: mod,
|
|
20
|
+
enumerable: true
|
|
21
|
+
}) : target, mod));
|
|
22
|
+
//#endregion
|
|
23
|
+
let kizunajs = require("kizunajs");
|
|
24
|
+
let zod = require("zod");
|
|
25
|
+
let pluralize = require("pluralize");
|
|
26
|
+
pluralize = __toESM(pluralize, 1);
|
|
27
|
+
let node_crypto = require("node:crypto");
|
|
28
|
+
let node_fs_promises = require("node:fs/promises");
|
|
29
|
+
let node_path = require("node:path");
|
|
30
|
+
let _sindresorhus_slugify = require("@sindresorhus/slugify");
|
|
31
|
+
_sindresorhus_slugify = __toESM(_sindresorhus_slugify, 1);
|
|
32
|
+
//#region src/storage.ts
|
|
33
|
+
/**
|
|
34
|
+
* The fields the CMS keeps on every file.
|
|
35
|
+
*/
|
|
36
|
+
const FILE_RECORD_FIELDS = [
|
|
37
|
+
"key",
|
|
38
|
+
"filename",
|
|
39
|
+
"contentType",
|
|
40
|
+
"fileSize",
|
|
41
|
+
"width",
|
|
42
|
+
"height",
|
|
43
|
+
"alt",
|
|
44
|
+
"focalPoint",
|
|
45
|
+
"uploadedBy"
|
|
46
|
+
];
|
|
47
|
+
/**
|
|
48
|
+
* The collection a store's file records are saved in.
|
|
49
|
+
*/
|
|
50
|
+
const fileCollectionOf = (storage) => `storage:${storage.name}`;
|
|
51
|
+
const storesByName = /* @__PURE__ */ new Map();
|
|
52
|
+
/**
|
|
53
|
+
* Keeps stores by name so a field can find the one it names.
|
|
54
|
+
*/
|
|
55
|
+
const registerStores = (declared) => {
|
|
56
|
+
for (const store of declared) storesByName.set(store.name, store);
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* A store's own fields as `kizuna generate` writes them into `Config`.
|
|
60
|
+
*/
|
|
61
|
+
const storeFieldTypesOf = (store) => Object.fromEntries((store.fields ?? []).map((field) => {
|
|
62
|
+
return [field.name, {
|
|
63
|
+
type: [field.type],
|
|
64
|
+
required: [String(field.required === true)],
|
|
65
|
+
...field.type === "select" ? {
|
|
66
|
+
options: field.options.map((option) => typeof option === "string" ? option : option.value),
|
|
67
|
+
many: [String(field.many === true)]
|
|
68
|
+
} : {}
|
|
69
|
+
}];
|
|
70
|
+
}));
|
|
71
|
+
const storeNamed = (name) => {
|
|
72
|
+
const store = storesByName.get(name);
|
|
73
|
+
if (store === void 0) throw new Error(`No store is named '${name}'. Declare it with \`k.storage\`, and list it under \`storage\` in the config.`);
|
|
74
|
+
return store;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Checks a store's definition and returns the store, for `k.storage`.
|
|
78
|
+
*/
|
|
79
|
+
const defineStorage = (definition) => {
|
|
80
|
+
checkDefinition(`Storage '${definition.name}'`, definition.name, definition.fields ?? [], "`images` or `documents`");
|
|
81
|
+
const taken = (definition.fields ?? []).find((field) => [
|
|
82
|
+
...FILE_RECORD_FIELDS,
|
|
83
|
+
"url",
|
|
84
|
+
"original"
|
|
85
|
+
].includes(field.name));
|
|
86
|
+
if (taken !== void 0) throw new Error(`Storage '${definition.name}' has a field named '${taken.name}', which every file already carries.`);
|
|
87
|
+
const store = {
|
|
88
|
+
...definition,
|
|
89
|
+
kind: "storage"
|
|
90
|
+
};
|
|
91
|
+
registerStores([store]);
|
|
92
|
+
return store;
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* Creates a storage adapter that keeps files in memory, for tests.
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* adapter: memoryStorage(),
|
|
99
|
+
*/
|
|
100
|
+
const memoryStorage = (uploadBase = "memory://uploads") => {
|
|
101
|
+
const files = /* @__PURE__ */ new Map();
|
|
102
|
+
return {
|
|
103
|
+
files,
|
|
104
|
+
put: async (key, bytes, contentType) => {
|
|
105
|
+
files.set(key, {
|
|
106
|
+
bytes,
|
|
107
|
+
contentType
|
|
108
|
+
});
|
|
109
|
+
},
|
|
110
|
+
presignUpload: async ({ key, contentType }) => ({
|
|
111
|
+
url: `${uploadBase}/${key}`,
|
|
112
|
+
headers: { "content-type": contentType }
|
|
113
|
+
}),
|
|
114
|
+
head: async (key) => {
|
|
115
|
+
const file = files.get(key);
|
|
116
|
+
return file === void 0 ? void 0 : {
|
|
117
|
+
fileSize: file.bytes.byteLength,
|
|
118
|
+
contentType: file.contentType
|
|
119
|
+
};
|
|
120
|
+
},
|
|
121
|
+
read: async (key, length) => files.get(key)?.bytes.slice(0, length),
|
|
122
|
+
delete: async (key) => {
|
|
123
|
+
files.delete(key);
|
|
124
|
+
},
|
|
125
|
+
url: async (key) => `${uploadBase}/${key}`
|
|
126
|
+
};
|
|
127
|
+
};
|
|
128
|
+
const CONTENT_TYPES_BY_EXTENSION = {
|
|
129
|
+
jpg: "image/jpeg",
|
|
130
|
+
jpeg: "image/jpeg",
|
|
131
|
+
png: "image/png",
|
|
132
|
+
gif: "image/gif",
|
|
133
|
+
webp: "image/webp",
|
|
134
|
+
avif: "image/avif",
|
|
135
|
+
heic: "image/heic",
|
|
136
|
+
pdf: "application/pdf"
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* Reads a request's body, or returns `undefined` when it holds more than `limit` bytes. It stops reading past the limit.
|
|
140
|
+
*/
|
|
141
|
+
const bodyWithin = async (request, limit) => {
|
|
142
|
+
const declared = Number(request.headers.get("content-length") ?? NaN);
|
|
143
|
+
if (Number.isFinite(declared) && declared > limit) return void 0;
|
|
144
|
+
if (request.body === null) return new Uint8Array();
|
|
145
|
+
const reader = request.body.getReader();
|
|
146
|
+
const chunks = [];
|
|
147
|
+
let length = 0;
|
|
148
|
+
for (;;) {
|
|
149
|
+
const { done, value } = await reader.read();
|
|
150
|
+
if (done) break;
|
|
151
|
+
length += value.byteLength;
|
|
152
|
+
if (length > limit) {
|
|
153
|
+
await reader.cancel();
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
chunks.push(value);
|
|
157
|
+
}
|
|
158
|
+
const bytes = new Uint8Array(length);
|
|
159
|
+
let offset = 0;
|
|
160
|
+
for (const chunk of chunks) {
|
|
161
|
+
bytes.set(chunk, offset);
|
|
162
|
+
offset += chunk.byteLength;
|
|
163
|
+
}
|
|
164
|
+
return bytes;
|
|
165
|
+
};
|
|
166
|
+
/**
|
|
167
|
+
* Creates a storage adapter that keeps files on disk, for development. Send the requests under `publicUrl` to its
|
|
168
|
+
* `handle`, which answers uploads and downloads.
|
|
169
|
+
*
|
|
170
|
+
* An upload URL is signed for one key, one content type and a largest size, until it expires. Its PUT writes a key
|
|
171
|
+
* once, so a recorded file is never replaced. Every file is served with a sandboxing Content Security Policy, and a
|
|
172
|
+
* file that isn't an image is served as a download.
|
|
173
|
+
*
|
|
174
|
+
* @example
|
|
175
|
+
* adapter: diskStorage({
|
|
176
|
+
* directory: '.data/uploads',
|
|
177
|
+
* publicUrl: 'http://localhost:3100/uploads',
|
|
178
|
+
* secret: process.env.UPLOADS_SECRET,
|
|
179
|
+
* }),
|
|
180
|
+
*/
|
|
181
|
+
const diskStorage = (options) => {
|
|
182
|
+
if (!/^https?:\/\/[^/?#]+(\/[^?#]*[^/?#])?$/.test(options.publicUrl)) throw new Error(`\`publicUrl\` is '${options.publicUrl}'. Write it whole, like \`http://localhost:3100/uploads\`, with no trailing slash.`);
|
|
183
|
+
const publicPath = new URL(options.publicUrl).pathname.replace(/\/$/, "");
|
|
184
|
+
const isValidKey = (key) => /^[A-Za-z0-9._/-]+$/.test(key) && !key.includes("..");
|
|
185
|
+
const pathOf = (key) => {
|
|
186
|
+
if (!isValidKey(key)) throw new Error(`'${key}' is not a file key.`);
|
|
187
|
+
return (0, node_path.join)(options.directory, key);
|
|
188
|
+
};
|
|
189
|
+
const signatureOf = (upload) => (0, node_crypto.createHmac)("sha256", options.secret).update(JSON.stringify([
|
|
190
|
+
upload.key,
|
|
191
|
+
upload.expires,
|
|
192
|
+
upload.contentType,
|
|
193
|
+
upload.fileSize
|
|
194
|
+
])).digest("base64url");
|
|
195
|
+
const isSignatureValid = (key, url, contentType) => {
|
|
196
|
+
const expires = Number(url.searchParams.get("expires") ?? NaN);
|
|
197
|
+
const fileSize = Number(url.searchParams.get("size") ?? NaN);
|
|
198
|
+
const given = url.searchParams.get("signature");
|
|
199
|
+
if (given === null || contentType === null || !Number.isSafeInteger(expires) || expires < Date.now()) return false;
|
|
200
|
+
if (!Number.isSafeInteger(fileSize) || fileSize < 0) return false;
|
|
201
|
+
const expected = Buffer.from(signatureOf({
|
|
202
|
+
key,
|
|
203
|
+
expires,
|
|
204
|
+
contentType,
|
|
205
|
+
fileSize
|
|
206
|
+
}));
|
|
207
|
+
const provided = Buffer.from(given);
|
|
208
|
+
return expected.length === provided.length && (0, node_crypto.timingSafeEqual)(expected, provided);
|
|
209
|
+
};
|
|
210
|
+
const status = (code) => new Response(null, { status: code });
|
|
211
|
+
return {
|
|
212
|
+
presignUpload: async ({ key, contentType, fileSize, expiresIn }) => {
|
|
213
|
+
const expires = Date.now() + expiresIn * 1e3;
|
|
214
|
+
const signature = signatureOf({
|
|
215
|
+
key,
|
|
216
|
+
expires,
|
|
217
|
+
contentType,
|
|
218
|
+
fileSize
|
|
219
|
+
});
|
|
220
|
+
return {
|
|
221
|
+
url: `${options.publicUrl}/${key}?expires=${expires}&size=${fileSize}&signature=${signature}`,
|
|
222
|
+
headers: { "content-type": contentType }
|
|
223
|
+
};
|
|
224
|
+
},
|
|
225
|
+
head: async (key) => {
|
|
226
|
+
const found = await (0, node_fs_promises.stat)(pathOf(key)).catch(() => void 0);
|
|
227
|
+
return found === void 0 ? void 0 : { fileSize: found.size };
|
|
228
|
+
},
|
|
229
|
+
read: async (key, length) => {
|
|
230
|
+
const bytes = await (0, node_fs_promises.readFile)(pathOf(key)).catch(() => void 0);
|
|
231
|
+
return bytes === void 0 ? void 0 : new Uint8Array(bytes.subarray(0, length));
|
|
232
|
+
},
|
|
233
|
+
put: async (key, bytes) => {
|
|
234
|
+
await (0, node_fs_promises.mkdir)((0, node_path.dirname)(pathOf(key)), { recursive: true });
|
|
235
|
+
await (0, node_fs_promises.writeFile)(pathOf(key), bytes);
|
|
236
|
+
},
|
|
237
|
+
delete: async (key) => {
|
|
238
|
+
await (0, node_fs_promises.rm)(pathOf(key), { force: true });
|
|
239
|
+
},
|
|
240
|
+
url: async (key) => `${options.publicUrl}/${key}`,
|
|
241
|
+
handle: async (request) => {
|
|
242
|
+
const url = new URL(request.url);
|
|
243
|
+
if (!url.pathname.startsWith(`${publicPath}/`)) return status(404);
|
|
244
|
+
const key = url.pathname.slice(publicPath.length + 1);
|
|
245
|
+
if (!isValidKey(key)) return status(404);
|
|
246
|
+
if (request.method === "PUT") {
|
|
247
|
+
if (!isSignatureValid(key, url, request.headers.get("content-type"))) return status(403);
|
|
248
|
+
const bytes = await bodyWithin(request, Number(url.searchParams.get("size")));
|
|
249
|
+
if (bytes === void 0) return status(413);
|
|
250
|
+
await (0, node_fs_promises.mkdir)((0, node_path.dirname)(pathOf(key)), { recursive: true });
|
|
251
|
+
return status(await (0, node_fs_promises.writeFile)(pathOf(key), bytes, { flag: "wx" }).then(() => true, (error) => {
|
|
252
|
+
if (error.code === "EEXIST") return false;
|
|
253
|
+
throw error;
|
|
254
|
+
}) ? 200 : 409);
|
|
255
|
+
}
|
|
256
|
+
const bytes = await (0, node_fs_promises.readFile)(pathOf(key)).catch(() => void 0);
|
|
257
|
+
if (bytes === void 0) return status(404);
|
|
258
|
+
const contentType = CONTENT_TYPES_BY_EXTENSION[/\.([a-z0-9]+)$/.exec(key)?.[1] ?? ""] ?? "application/octet-stream";
|
|
259
|
+
return new Response(new Uint8Array(bytes), {
|
|
260
|
+
status: 200,
|
|
261
|
+
headers: {
|
|
262
|
+
"content-type": contentType,
|
|
263
|
+
"x-content-type-options": "nosniff",
|
|
264
|
+
"content-security-policy": "default-src 'none'; sandbox",
|
|
265
|
+
...contentType.startsWith("image/") ? {} : { "content-disposition": "attachment" }
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
};
|
|
271
|
+
/**
|
|
272
|
+
* A new key for an upload, which keeps the file's extension.
|
|
273
|
+
*/
|
|
274
|
+
const newFileKey = (storage, filename) => {
|
|
275
|
+
const extension = /\.([A-Za-z0-9]{1,8})$/.exec(filename)?.[1]?.toLowerCase();
|
|
276
|
+
return `${storage.name}/${(0, node_crypto.randomUUID)()}${extension === void 0 ? "" : `.${extension}`}`;
|
|
277
|
+
};
|
|
278
|
+
/**
|
|
279
|
+
* Whether the store takes a file of this type, where `image/*` matches every image type.
|
|
280
|
+
*/
|
|
281
|
+
const acceptsType = (storage, contentType) => {
|
|
282
|
+
if (storage.contentTypes === void 0) return true;
|
|
283
|
+
const type = contentType?.split(";", 1)[0].trim().toLowerCase();
|
|
284
|
+
if (type === void 0 || type === "") return false;
|
|
285
|
+
return storage.contentTypes.some((allowed) => {
|
|
286
|
+
const pattern = allowed.toLowerCase();
|
|
287
|
+
return pattern.endsWith("/*") ? type.startsWith(pattern.slice(0, -1)) : type === pattern;
|
|
288
|
+
});
|
|
289
|
+
};
|
|
290
|
+
//#endregion
|
|
291
|
+
//#region src/images.ts
|
|
292
|
+
const isFileField = (field) => field.type === "image" || field.type === "file";
|
|
293
|
+
const capitalized = (name) => name.charAt(0).toUpperCase() + name.slice(1);
|
|
294
|
+
const ImageVersionSchema = kizunajs.Kizuna.model({
|
|
295
|
+
title: "ImageVersion",
|
|
296
|
+
schema: zod.z.object({
|
|
297
|
+
url: zod.z.string(),
|
|
298
|
+
width: zod.z.int(),
|
|
299
|
+
height: zod.z.int()
|
|
300
|
+
})
|
|
301
|
+
});
|
|
302
|
+
/**
|
|
303
|
+
* What an image or file field takes on write: the file's id.
|
|
304
|
+
*/
|
|
305
|
+
const fileWriteSchemaOf = (field) => zod.z.strictObject({ file: TextSchema.describe(`The id of ${field.type === "image" ? "an image" : "a file"} in \`${field.storage}\`.`) });
|
|
306
|
+
const readSchemas = /* @__PURE__ */ new WeakMap();
|
|
307
|
+
/**
|
|
308
|
+
* What an image or file field reads as, built once per field so its model has one definition.
|
|
309
|
+
*/
|
|
310
|
+
const fileReadSchemaOf = (field, owner, storeFields) => {
|
|
311
|
+
const existing = readSchemas.get(field);
|
|
312
|
+
if (existing !== void 0) return existing;
|
|
313
|
+
const schema = buildReadSchema(field, owner, storeFields());
|
|
314
|
+
readSchemas.set(field, schema);
|
|
315
|
+
return schema;
|
|
316
|
+
};
|
|
317
|
+
const buildReadSchema = (field, owner, storeFields) => {
|
|
318
|
+
const title = `${owner}${capitalized(field.name)}`;
|
|
319
|
+
if (field.type === "file") return kizunajs.Kizuna.model({
|
|
320
|
+
title,
|
|
321
|
+
schema: zod.z.object({
|
|
322
|
+
id: zod.z.string(),
|
|
323
|
+
url: zod.z.string(),
|
|
324
|
+
filename: zod.z.string(),
|
|
325
|
+
contentType: zod.z.string(),
|
|
326
|
+
fileSize: zod.z.int(),
|
|
327
|
+
...storeFields
|
|
328
|
+
})
|
|
329
|
+
});
|
|
330
|
+
return kizunajs.Kizuna.model({
|
|
331
|
+
title,
|
|
332
|
+
schema: zod.z.object({
|
|
333
|
+
id: zod.z.string(),
|
|
334
|
+
alt: zod.z.string().optional(),
|
|
335
|
+
filename: zod.z.string(),
|
|
336
|
+
contentType: zod.z.string(),
|
|
337
|
+
fileSize: zod.z.int(),
|
|
338
|
+
focalPoint: FocalPointSchema,
|
|
339
|
+
original: ImageVersionSchema,
|
|
340
|
+
...storeFields
|
|
341
|
+
})
|
|
342
|
+
});
|
|
343
|
+
};
|
|
344
|
+
/**
|
|
345
|
+
* Where an image stays in view when a site crops it, in percent from its top left corner.
|
|
346
|
+
*/
|
|
347
|
+
const FocalPointSchema = kizunajs.Kizuna.model({
|
|
348
|
+
title: "FocalPoint",
|
|
349
|
+
schema: zod.z.object({
|
|
350
|
+
x: zod.z.number().min(0).max(100),
|
|
351
|
+
y: zod.z.number().min(0).max(100)
|
|
352
|
+
})
|
|
353
|
+
});
|
|
354
|
+
/**
|
|
355
|
+
* An image's focal point, or its center when none is set.
|
|
356
|
+
*/
|
|
357
|
+
const focalPointOf = (record) => record["focalPoint"] ?? {
|
|
358
|
+
x: 50,
|
|
359
|
+
y: 50
|
|
360
|
+
};
|
|
361
|
+
/**
|
|
362
|
+
* Why a document's files can't be written, or `undefined` when they can.
|
|
363
|
+
*/
|
|
364
|
+
const fileProblemOf = async (db, fields, values) => {
|
|
365
|
+
for (const field of fields) {
|
|
366
|
+
if (!isFileField(field)) continue;
|
|
367
|
+
const value = values[field.name];
|
|
368
|
+
if (value === void 0 || value === null) continue;
|
|
369
|
+
if (await db.get(fileCollectionOf(storeNamed(field.storage)), value.file) === void 0) return `'${field.name}' points at '${value.file}', and '${field.storage}' has no file with that id.`;
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
/**
|
|
373
|
+
* Documents with their image and file fields read as the files they point at.
|
|
374
|
+
*/
|
|
375
|
+
const resolveFiles = async (db, fields, documents) => {
|
|
376
|
+
const fileFields = fields.filter(isFileField);
|
|
377
|
+
if (fileFields.length === 0 || documents.length === 0) return [...documents];
|
|
378
|
+
const wanted = /* @__PURE__ */ new Map();
|
|
379
|
+
for (const document of documents) for (const field of fileFields) {
|
|
380
|
+
const value = document[field.name];
|
|
381
|
+
if (value?.file === void 0) continue;
|
|
382
|
+
const storage = storeNamed(field.storage);
|
|
383
|
+
const ids = wanted.get(storage) ?? /* @__PURE__ */ new Set();
|
|
384
|
+
ids.add(value.file);
|
|
385
|
+
wanted.set(storage, ids);
|
|
386
|
+
}
|
|
387
|
+
const found = /* @__PURE__ */ new Map();
|
|
388
|
+
for (const [storage, ids] of wanted) {
|
|
389
|
+
const { items } = await db.list(fileCollectionOf(storage), {
|
|
390
|
+
offset: 0,
|
|
391
|
+
limit: ids.size
|
|
392
|
+
}, { ids: [...ids] });
|
|
393
|
+
for (const record of items) {
|
|
394
|
+
const url = await storage.adapter.url(record["key"]);
|
|
395
|
+
found.set(`${storage.name}:${record.id}`, {
|
|
396
|
+
...record,
|
|
397
|
+
url
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
return documents.map((document) => {
|
|
402
|
+
const resolved = { ...document };
|
|
403
|
+
for (const field of fileFields) {
|
|
404
|
+
const value = document[field.name];
|
|
405
|
+
if (value?.file === void 0) continue;
|
|
406
|
+
const record = found.get(`${field.storage}:${value.file}`);
|
|
407
|
+
if (record === void 0) {
|
|
408
|
+
delete resolved[field.name];
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
resolved[field.name] = field.type === "image" ? imageValueOf(field, record) : fileValueOf(field, record);
|
|
412
|
+
}
|
|
413
|
+
return resolved;
|
|
414
|
+
});
|
|
415
|
+
};
|
|
416
|
+
const storeFieldValuesOf = (field, record) => Object.fromEntries((storeNamed(field.storage).fields ?? []).filter((own) => record[own.name] !== void 0).map((own) => [own.name, record[own.name]]));
|
|
417
|
+
const fileValueOf = (field, record) => ({
|
|
418
|
+
id: record["id"],
|
|
419
|
+
url: record["url"],
|
|
420
|
+
filename: record["filename"],
|
|
421
|
+
contentType: record["contentType"],
|
|
422
|
+
fileSize: record["fileSize"],
|
|
423
|
+
...storeFieldValuesOf(field, record)
|
|
424
|
+
});
|
|
425
|
+
/**
|
|
426
|
+
* A stored image's original as a document reads it.
|
|
427
|
+
*/
|
|
428
|
+
const originalImageOf = async (storage, record) => ({
|
|
429
|
+
url: await storage.adapter.url(record["key"]),
|
|
430
|
+
width: record["width"] ?? 0,
|
|
431
|
+
height: record["height"] ?? 0
|
|
432
|
+
});
|
|
433
|
+
const imageValueOf = (field, record) => ({
|
|
434
|
+
id: record["id"],
|
|
435
|
+
...record["alt"] === void 0 ? {} : { alt: record["alt"] },
|
|
436
|
+
filename: record["filename"],
|
|
437
|
+
contentType: record["contentType"],
|
|
438
|
+
fileSize: record["fileSize"],
|
|
439
|
+
focalPoint: focalPointOf(record),
|
|
440
|
+
original: {
|
|
441
|
+
url: record["url"],
|
|
442
|
+
width: record["width"] ?? 0,
|
|
443
|
+
height: record["height"] ?? 0
|
|
444
|
+
},
|
|
445
|
+
...storeFieldValuesOf(field, record)
|
|
446
|
+
});
|
|
447
|
+
//#endregion
|
|
448
|
+
//#region src/limits.ts
|
|
449
|
+
const MINUTE = 60 * 1e3;
|
|
450
|
+
const HOUR = 60 * MINUTE;
|
|
451
|
+
const DAY = 24 * HOUR;
|
|
452
|
+
/**
|
|
453
|
+
* The largest upload in bytes when a store sets no `maxBytes`.
|
|
454
|
+
*/
|
|
455
|
+
const DEFAULT_MAX_UPLOAD_BYTES = 20 * 1024 * 1024;
|
|
456
|
+
/**
|
|
457
|
+
* The most pixels an uploaded image may have.
|
|
458
|
+
*/
|
|
459
|
+
const MAX_IMAGE_PIXELS = 1e8;
|
|
460
|
+
/**
|
|
461
|
+
* How long a session lasts after logging in, in milliseconds.
|
|
462
|
+
*/
|
|
463
|
+
const SESSION_LIFETIME = 30 * DAY;
|
|
464
|
+
/**
|
|
465
|
+
* How long a password reset link works, in milliseconds.
|
|
466
|
+
*/
|
|
467
|
+
const PASSWORD_RESET_LIFETIME = HOUR;
|
|
468
|
+
/**
|
|
469
|
+
* How long an invite link works, in milliseconds.
|
|
470
|
+
*/
|
|
471
|
+
const INVITE_LIFETIME = 7 * DAY;
|
|
472
|
+
/**
|
|
473
|
+
* The time {@link LOGIN_ATTEMPT_LIMIT} counts failed logins over, in milliseconds.
|
|
474
|
+
*/
|
|
475
|
+
const LOGIN_WINDOW = 15 * MINUTE;
|
|
476
|
+
/**
|
|
477
|
+
* The time {@link PASSWORD_RESET_LIMIT} counts reset requests over, in milliseconds.
|
|
478
|
+
*/
|
|
479
|
+
const PASSWORD_RESET_WINDOW = HOUR;
|
|
480
|
+
//#endregion
|
|
481
|
+
//#region src/fields.ts
|
|
482
|
+
const NUL_MESSAGE = "Text can’t hold the NUL character (U+0000).";
|
|
483
|
+
/**
|
|
484
|
+
* Whether a text is free of the NUL character, which Postgres can't store in text.
|
|
485
|
+
*/
|
|
486
|
+
const isWithoutNul = (text) => !text.includes("\0");
|
|
487
|
+
/**
|
|
488
|
+
* Refuses the NUL character (U+0000) in a string schema, since Postgres can't store it in text.
|
|
489
|
+
*/
|
|
490
|
+
const withoutNul = (schema) => schema.refine(isWithoutNul, NUL_MESSAGE);
|
|
491
|
+
/**
|
|
492
|
+
* The schema text passes: any string without the NUL character (U+0000).
|
|
493
|
+
*/
|
|
494
|
+
const TextSchema = withoutNul(zod.z.string());
|
|
495
|
+
const YEAR_MESSAGE = "Use a year from 0001 to 9999.";
|
|
496
|
+
/**
|
|
497
|
+
* Whether an ISO date or date-time names a year Postgres can store. ISO allows the year 0000, and Postgres has no
|
|
498
|
+
* year 0.
|
|
499
|
+
*/
|
|
500
|
+
const isStorableYear = (value) => !value.startsWith("0000");
|
|
501
|
+
/**
|
|
502
|
+
* The schema a slug passes: lowercase letters and digits, with single hyphens between them, at most
|
|
503
|
+
* {@link MAX_SLUG_LENGTH} characters.
|
|
504
|
+
*/
|
|
505
|
+
const SlugSchema = zod.z.string().max(200).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Use lowercase letters, digits and single hyphens.");
|
|
506
|
+
const optionValuesOf = (options) => {
|
|
507
|
+
const values = options.map((option) => typeof option === "string" ? option : option.value);
|
|
508
|
+
if (values.length === 0) throw new Error("A `select` field needs at least one option.");
|
|
509
|
+
return values;
|
|
510
|
+
};
|
|
511
|
+
const builtInSchemaOf = (field) => {
|
|
512
|
+
switch (field.type) {
|
|
513
|
+
case "text": {
|
|
514
|
+
let schema = TextSchema;
|
|
515
|
+
if (field.minLength !== void 0) schema = schema.min(field.minLength);
|
|
516
|
+
if (field.maxLength !== void 0) schema = schema.max(field.maxLength);
|
|
517
|
+
return schema;
|
|
518
|
+
}
|
|
519
|
+
case "number": {
|
|
520
|
+
let schema = field.integer === true ? zod.z.int() : zod.z.number();
|
|
521
|
+
if (field.min !== void 0) schema = schema.min(field.min);
|
|
522
|
+
if (field.max !== void 0) schema = schema.max(field.max);
|
|
523
|
+
return schema;
|
|
524
|
+
}
|
|
525
|
+
case "boolean": return zod.z.boolean();
|
|
526
|
+
case "url": return withoutNul(zod.z.url());
|
|
527
|
+
case "email": return withoutNul(zod.z.email().max(254));
|
|
528
|
+
case "slug": return SlugSchema;
|
|
529
|
+
case "select": {
|
|
530
|
+
const choice = zod.z.enum(optionValuesOf(field.options));
|
|
531
|
+
return field.many === true ? zod.z.array(choice) : choice;
|
|
532
|
+
}
|
|
533
|
+
case "date": return zod.z.iso.date().refine(isStorableYear, YEAR_MESSAGE);
|
|
534
|
+
case "dateTime": return zod.z.iso.datetime().refine(isStorableYear, YEAR_MESSAGE);
|
|
535
|
+
case "relationship": return field.many === true ? zod.z.array(TextSchema) : TextSchema;
|
|
536
|
+
case "image":
|
|
537
|
+
case "file": return zod.z.unknown();
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
const builtInColumnOf = (field) => {
|
|
541
|
+
switch (field.type) {
|
|
542
|
+
case "number": return "number";
|
|
543
|
+
case "boolean": return "boolean";
|
|
544
|
+
case "select":
|
|
545
|
+
case "relationship": return field.many === true ? "json" : "text";
|
|
546
|
+
default: return "text";
|
|
547
|
+
}
|
|
548
|
+
};
|
|
549
|
+
/**
|
|
550
|
+
* The description that says where a relationship's or file's id points.
|
|
551
|
+
*/
|
|
552
|
+
const referenceDescriptionOf = (field) => {
|
|
553
|
+
if (isFileField(field)) return `The id of a file in the store \`${field.storage}\`.`;
|
|
554
|
+
if (field.type !== "relationship") return void 0;
|
|
555
|
+
return field.many === true ? `The ids of documents in \`${field.to}\`.` : `The id of a document in \`${field.to}\`.`;
|
|
556
|
+
};
|
|
557
|
+
/**
|
|
558
|
+
* Returns the schema a field's value passes, with a description that says where a relationship's id points.
|
|
559
|
+
*/
|
|
560
|
+
const schemaOf = (field, owner = "") => {
|
|
561
|
+
if (isFileField(field)) {
|
|
562
|
+
const storeFields = () => Object.fromEntries((storeNamed(field.storage).fields ?? []).map((own) => [own.name, wrappedSchemaOf(own, (schema) => schema.optional())]));
|
|
563
|
+
return fileReadSchemaOf(field, owner, storeFields);
|
|
564
|
+
}
|
|
565
|
+
const schema = builtInSchemaOf(field);
|
|
566
|
+
const description = [field.description, referenceDescriptionOf(field)].filter((line) => line !== void 0).join("\n\n");
|
|
567
|
+
return description === "" ? schema : schema.describe(description);
|
|
568
|
+
};
|
|
569
|
+
/**
|
|
570
|
+
* A field's schema wrapped in `optional` or `nullable`, with its description moved to the outer schema.
|
|
571
|
+
*/
|
|
572
|
+
const wrappedSchemaOf = (field, wrap, owner = "") => {
|
|
573
|
+
const schema = schemaOf(field, owner);
|
|
574
|
+
const outer = wrap(schema);
|
|
575
|
+
return schema.description === void 0 ? outer : outer.describe(schema.description);
|
|
576
|
+
};
|
|
577
|
+
/**
|
|
578
|
+
* Returns how a field's value is stored in the database.
|
|
579
|
+
*/
|
|
580
|
+
const columnOf = (field) => builtInColumnOf(field);
|
|
581
|
+
/**
|
|
582
|
+
* The schema a field's value passes on write, where an image or file is its id.
|
|
583
|
+
*/
|
|
584
|
+
const writeSchemaOf = (field) => isFileField(field) ? fileWriteSchemaOf(field) : schemaOf(field);
|
|
585
|
+
/**
|
|
586
|
+
* {@link writeSchemaOf} with a wrap, like {@link wrappedSchemaOf}.
|
|
587
|
+
*/
|
|
588
|
+
const wrappedWriteSchemaOf = (field, wrap) => {
|
|
589
|
+
const schema = writeSchemaOf(field);
|
|
590
|
+
const outer = wrap(schema);
|
|
591
|
+
return schema.description === void 0 ? outer : outer.describe(schema.description);
|
|
592
|
+
};
|
|
593
|
+
/**
|
|
594
|
+
* Puts a field's read schema into a shape, as a getter for image and file fields whose store loads later.
|
|
595
|
+
*/
|
|
596
|
+
const setReadSchema = (shape, field, schemaFor) => {
|
|
597
|
+
if (!isFileField(field)) {
|
|
598
|
+
shape[field.name] = schemaFor();
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
let schema;
|
|
602
|
+
Object.defineProperty(shape, field.name, {
|
|
603
|
+
enumerable: true,
|
|
604
|
+
get: () => schema ??= schemaFor()
|
|
605
|
+
});
|
|
606
|
+
};
|
|
607
|
+
//#endregion
|
|
608
|
+
//#region src/titles.ts
|
|
609
|
+
/**
|
|
610
|
+
* Fills in `titleField` as the default `generateFrom` of each slug and of the `meta` title.
|
|
611
|
+
*/
|
|
612
|
+
const withTitleDefaults = (label, definition) => {
|
|
613
|
+
const title = definition.titleField;
|
|
614
|
+
if (title === void 0) return definition;
|
|
615
|
+
const field = definition.fields.find((candidate) => candidate.name === title);
|
|
616
|
+
if (field === void 0 || field.type !== "text") throw new Error(`${label} is titled by '${title}', which is no text field of it.`);
|
|
617
|
+
const meta = definition.meta === true ? {} : definition.meta;
|
|
618
|
+
return {
|
|
619
|
+
...definition,
|
|
620
|
+
fields: definition.fields.map((candidate) => candidate.type === "slug" && candidate.generateFrom === void 0 ? {
|
|
621
|
+
...candidate,
|
|
622
|
+
generateFrom: title
|
|
623
|
+
} : candidate),
|
|
624
|
+
...meta === void 0 ? {} : { meta: {
|
|
625
|
+
...meta,
|
|
626
|
+
title: {
|
|
627
|
+
generateFrom: title,
|
|
628
|
+
...meta.title
|
|
629
|
+
}
|
|
630
|
+
} }
|
|
631
|
+
};
|
|
632
|
+
};
|
|
633
|
+
//#endregion
|
|
634
|
+
//#region src/meta.ts
|
|
635
|
+
/**
|
|
636
|
+
* A definition's `meta` options, where `true` reads as `{}`.
|
|
637
|
+
*/
|
|
638
|
+
const metaOptionsOf = (definition) => definition.meta === true ? {} : definition.meta;
|
|
639
|
+
const titleOptions = /* @__PURE__ */ new WeakMap();
|
|
640
|
+
const setTitleSuffix = (definition, options) => {
|
|
641
|
+
titleOptions.set(definition, options);
|
|
642
|
+
};
|
|
643
|
+
const fieldNamed = (definition, name) => definition.fields.find((field) => field.name === name);
|
|
644
|
+
/**
|
|
645
|
+
* The store an editor's own share image comes from: `image.storage`, or the image field's store.
|
|
646
|
+
*/
|
|
647
|
+
const metaImageStoreOf = (definition) => {
|
|
648
|
+
const meta = metaOptionsOf(definition);
|
|
649
|
+
if (meta?.image?.storage !== void 0) return meta.image.storage;
|
|
650
|
+
const source = meta?.image?.generateFrom;
|
|
651
|
+
if (source === void 0) return void 0;
|
|
652
|
+
const field = fieldNamed(definition, source);
|
|
653
|
+
return field !== void 0 && field.type === "image" ? field.storage : void 0;
|
|
654
|
+
};
|
|
655
|
+
/**
|
|
656
|
+
* Checks what `meta` points at when the collection is declared.
|
|
657
|
+
*/
|
|
658
|
+
const checkMeta = (label, definition) => {
|
|
659
|
+
const meta = metaOptionsOf(definition);
|
|
660
|
+
if (meta === void 0) return;
|
|
661
|
+
for (const key of ["title", "description"]) {
|
|
662
|
+
const name = meta[key]?.generateFrom;
|
|
663
|
+
if (name === void 0) continue;
|
|
664
|
+
const field = fieldNamed(definition, name);
|
|
665
|
+
if (field === void 0 || field.type !== "text") throw new Error(`${label} takes its meta ${key} from '${name}', which is no text field of it.`);
|
|
666
|
+
}
|
|
667
|
+
const source = meta.image?.generateFrom;
|
|
668
|
+
if (source !== void 0) {
|
|
669
|
+
const field = fieldNamed(definition, source);
|
|
670
|
+
if (field === void 0 || field.type !== "image") throw new Error(`${label} takes its meta image from '${source}', which is no image field of it.`);
|
|
671
|
+
}
|
|
672
|
+
};
|
|
673
|
+
const MetaImageSchema = kizunajs.Kizuna.model({
|
|
674
|
+
title: "MetaImage",
|
|
675
|
+
schema: zod.z.object({
|
|
676
|
+
id: zod.z.string(),
|
|
677
|
+
url: zod.z.string(),
|
|
678
|
+
width: zod.z.int(),
|
|
679
|
+
height: zod.z.int()
|
|
680
|
+
})
|
|
681
|
+
});
|
|
682
|
+
const metaSchemas = /* @__PURE__ */ new WeakMap();
|
|
683
|
+
/**
|
|
684
|
+
* The schema a document's `meta` reads as, where each value is the editor's, the field's or `null`.
|
|
685
|
+
*/
|
|
686
|
+
const metaReadSchemaOf = (definition, owner) => {
|
|
687
|
+
const existing = metaSchemas.get(definition);
|
|
688
|
+
if (existing !== void 0) return existing;
|
|
689
|
+
const schema = kizunajs.Kizuna.model({
|
|
690
|
+
title: `${owner}Meta`,
|
|
691
|
+
schema: zod.z.object({
|
|
692
|
+
title: zod.z.string().nullable(),
|
|
693
|
+
description: zod.z.string().nullable(),
|
|
694
|
+
...metaImageStoreOf(definition) === void 0 ? {} : { image: MetaImageSchema.nullable() },
|
|
695
|
+
absoluteTitle: zod.z.boolean().describe("The title as written, without the site’s suffix."),
|
|
696
|
+
robots: zod.z.object({
|
|
697
|
+
index: zod.z.boolean().describe("Show the page in search results."),
|
|
698
|
+
follow: zod.z.boolean().describe("Let search engines follow the page's links.")
|
|
699
|
+
}).describe("What search engines may do with the page, in the shape `robots` takes in Next.js metadata."),
|
|
700
|
+
canonical: zod.z.string().nullable().describe("Another address that is the original of this page.")
|
|
701
|
+
})
|
|
702
|
+
});
|
|
703
|
+
metaSchemas.set(definition, schema);
|
|
704
|
+
return schema;
|
|
705
|
+
};
|
|
706
|
+
/**
|
|
707
|
+
* The editor's own `meta` values a write takes, where `null` falls back to the field.
|
|
708
|
+
*/
|
|
709
|
+
const metaWriteSchemaOf = (definition) => zod.z.strictObject({
|
|
710
|
+
title: TextSchema.min(1).max(70).nullable().optional().describe(`Up to 60 characters show in full.`),
|
|
711
|
+
description: TextSchema.min(1).max(200).nullable().optional().describe(`Up to 160 characters show in full.`),
|
|
712
|
+
...metaImageStoreOf(definition) === void 0 ? {} : { image: zod.z.strictObject({ file: TextSchema }).nullable().optional() },
|
|
713
|
+
...titleOptions.has(definition) ? { absoluteTitle: zod.z.boolean().optional() } : {},
|
|
714
|
+
robots: zod.z.strictObject({
|
|
715
|
+
index: zod.z.boolean().optional(),
|
|
716
|
+
follow: zod.z.boolean().optional()
|
|
717
|
+
}).optional(),
|
|
718
|
+
canonical: withoutNul(zod.z.url()).nullable().optional()
|
|
719
|
+
}).optional();
|
|
720
|
+
/**
|
|
721
|
+
* Returns the editor's own `robots` values from a stored `meta`.
|
|
722
|
+
*/
|
|
723
|
+
const robotsOf = (meta) => typeof meta["robots"] === "object" && meta["robots"] !== null ? meta["robots"] : {};
|
|
724
|
+
/**
|
|
725
|
+
* An update's `meta` merged over the stored one, where `null` removes a value.
|
|
726
|
+
*/
|
|
727
|
+
const mergeMetaChange = (change, stored) => {
|
|
728
|
+
const next = change["meta"];
|
|
729
|
+
if (next === void 0) return change;
|
|
730
|
+
const merged = { ...stored?.["meta"] ?? {} };
|
|
731
|
+
for (const [key, value] of Object.entries(next)) if (value === null) delete merged[key];
|
|
732
|
+
else if (key === "robots") merged[key] = {
|
|
733
|
+
...robotsOf(merged),
|
|
734
|
+
...value
|
|
735
|
+
};
|
|
736
|
+
else merged[key] = value;
|
|
737
|
+
return {
|
|
738
|
+
...change,
|
|
739
|
+
meta: merged
|
|
740
|
+
};
|
|
741
|
+
};
|
|
742
|
+
/**
|
|
743
|
+
* Why a write's own share image can't be used, or `undefined`.
|
|
744
|
+
*/
|
|
745
|
+
const metaImageProblemOf = async (db, definition, values) => {
|
|
746
|
+
const image = values["meta"]?.image;
|
|
747
|
+
const store = metaImageStoreOf(definition);
|
|
748
|
+
if (image === void 0 || image === null || store === void 0) return void 0;
|
|
749
|
+
return await db.get(fileCollectionOf(storeNamed(store)), image.file) === void 0 ? `The meta image '${image.file}' is no file of '${store}'.` : void 0;
|
|
750
|
+
};
|
|
751
|
+
/**
|
|
752
|
+
* Documents with their `meta` filled in for search results, once their image fields are resolved.
|
|
753
|
+
*/
|
|
754
|
+
const resolveMeta = async (db, definition, documents) => {
|
|
755
|
+
const meta = metaOptionsOf(definition);
|
|
756
|
+
if (meta === void 0) return [...documents];
|
|
757
|
+
const storeName = metaImageStoreOf(definition);
|
|
758
|
+
const storage = storeName === void 0 ? void 0 : storeNamed(storeName);
|
|
759
|
+
const ownIds = documents.map((document) => document["meta"]?.image?.file).filter((id) => id !== void 0);
|
|
760
|
+
const ownImages = /* @__PURE__ */ new Map();
|
|
761
|
+
if (storage !== void 0 && ownIds.length > 0) {
|
|
762
|
+
const { items } = await db.list(fileCollectionOf(storage), {
|
|
763
|
+
offset: 0,
|
|
764
|
+
limit: ownIds.length
|
|
765
|
+
}, { ids: [...new Set(ownIds)] });
|
|
766
|
+
for (const record of items) ownImages.set(record.id, record);
|
|
767
|
+
}
|
|
768
|
+
const source = meta.image?.generateFrom;
|
|
769
|
+
return Promise.all(documents.map(async (document) => {
|
|
770
|
+
const own = document["meta"] ?? {};
|
|
771
|
+
const absolute = own["absoluteTitle"] === true;
|
|
772
|
+
const text = (key) => {
|
|
773
|
+
if (typeof own[key] === "string") return own[key];
|
|
774
|
+
const name = meta[key]?.generateFrom;
|
|
775
|
+
const value = name === void 0 ? void 0 : document[name];
|
|
776
|
+
return typeof value === "string" && value !== "" ? value : null;
|
|
777
|
+
};
|
|
778
|
+
const image = async () => {
|
|
779
|
+
const ownFile = own["image"]?.file;
|
|
780
|
+
const ownRecord = ownFile === void 0 ? void 0 : ownImages.get(ownFile);
|
|
781
|
+
if (ownRecord !== void 0 && storage !== void 0) return {
|
|
782
|
+
id: ownRecord.id,
|
|
783
|
+
...await originalImageOf(storage, ownRecord)
|
|
784
|
+
};
|
|
785
|
+
if (source === void 0) return null;
|
|
786
|
+
const pointed = document[source];
|
|
787
|
+
return pointed === void 0 ? null : {
|
|
788
|
+
id: pointed.id,
|
|
789
|
+
...pointed.original
|
|
790
|
+
};
|
|
791
|
+
};
|
|
792
|
+
const title = () => {
|
|
793
|
+
const written = text("title");
|
|
794
|
+
const ending = titleOptions.get(definition);
|
|
795
|
+
if (written === null || ending === void 0 || absolute || written.endsWith(ending.suffix)) return written;
|
|
796
|
+
return `${written} ${ending.separator ?? "-"} ${ending.suffix}`;
|
|
797
|
+
};
|
|
798
|
+
return {
|
|
799
|
+
...document,
|
|
800
|
+
meta: {
|
|
801
|
+
title: title(),
|
|
802
|
+
description: text("description"),
|
|
803
|
+
...storeName === void 0 ? {} : { image: await image() },
|
|
804
|
+
absoluteTitle: absolute,
|
|
805
|
+
robots: {
|
|
806
|
+
index: robotsOf(own)["index"] !== false,
|
|
807
|
+
follow: robotsOf(own)["follow"] !== false
|
|
808
|
+
},
|
|
809
|
+
canonical: typeof own["canonical"] === "string" ? own["canonical"] : null
|
|
810
|
+
}
|
|
811
|
+
};
|
|
812
|
+
}));
|
|
813
|
+
};
|
|
814
|
+
/**
|
|
815
|
+
* Documents read with their files and their `meta`.
|
|
816
|
+
*/
|
|
817
|
+
const resolveDocuments = async (db, definition, documents) => resolveEditors(db, await resolveMeta(db, definition, await resolveFiles(db, definition.fields, documents)));
|
|
818
|
+
const editorsCollections = /* @__PURE__ */ new WeakMap();
|
|
819
|
+
/**
|
|
820
|
+
* Names the collection a database's `createdBy` and `updatedBy` editors are kept in.
|
|
821
|
+
*/
|
|
822
|
+
const setEditorsCollection = (db, collection) => {
|
|
823
|
+
editorsCollections.set(db, {
|
|
824
|
+
collection: collection.name,
|
|
825
|
+
titleField: collection.titleField
|
|
826
|
+
});
|
|
827
|
+
};
|
|
828
|
+
/**
|
|
829
|
+
* Turns each `createdBy` and `updatedBy` id into the editor's id and name. It leaves out editors who are gone, and
|
|
830
|
+
* editors with no name, so an email never stands in for one.
|
|
831
|
+
*/
|
|
832
|
+
const resolveEditors = async (db, documents) => {
|
|
833
|
+
const ids = new Set(documents.flatMap((document) => [document["createdBy"], document["updatedBy"]].filter((id) => typeof id === "string")));
|
|
834
|
+
const editors = editorsCollections.get(db);
|
|
835
|
+
const names = /* @__PURE__ */ new Map();
|
|
836
|
+
for (const id of editors === void 0 ? [] : ids) {
|
|
837
|
+
const editor = await db.get(editors.collection, id);
|
|
838
|
+
if (editor === void 0) continue;
|
|
839
|
+
const title = editors.titleField === void 0 ? void 0 : editor[editors.titleField];
|
|
840
|
+
if (typeof title === "string" && title !== "") names.set(id, title);
|
|
841
|
+
}
|
|
842
|
+
return documents.map((document) => {
|
|
843
|
+
const resolved = { ...document };
|
|
844
|
+
for (const key of ["createdBy", "updatedBy"]) {
|
|
845
|
+
const id = document[key];
|
|
846
|
+
if (typeof id !== "string") continue;
|
|
847
|
+
const name = names.get(id);
|
|
848
|
+
if (name === void 0) delete resolved[key];
|
|
849
|
+
else resolved[key] = {
|
|
850
|
+
id,
|
|
851
|
+
name
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
return resolved;
|
|
855
|
+
});
|
|
856
|
+
};
|
|
857
|
+
/**
|
|
858
|
+
* Returns the document without `createdBy` and `updatedBy`, as a read anyone may make shows it.
|
|
859
|
+
*/
|
|
860
|
+
const withoutEditorReferences = (document) => {
|
|
861
|
+
const { createdBy: _createdBy, updatedBy: _updatedBy, ...rest } = document;
|
|
862
|
+
return rest;
|
|
863
|
+
};
|
|
864
|
+
/**
|
|
865
|
+
* Returns who made and last changed a stored document, as `createdBy` and `updatedBy` with each editor's id and name.
|
|
866
|
+
*/
|
|
867
|
+
const editorReferencesOf = async (db, stored) => {
|
|
868
|
+
const [resolved] = await resolveEditors(db, [{
|
|
869
|
+
createdBy: stored["createdBy"],
|
|
870
|
+
updatedBy: stored["updatedBy"]
|
|
871
|
+
}]);
|
|
872
|
+
return resolved;
|
|
873
|
+
};
|
|
874
|
+
/**
|
|
875
|
+
* A document's `meta` as the editor wrote it, without fallbacks.
|
|
876
|
+
*/
|
|
877
|
+
const writtenMetaOf = (stored) => stored?.["meta"] ?? {};
|
|
878
|
+
/**
|
|
879
|
+
* The schema of the `meta` an editor wrote, which a hidden route returns.
|
|
880
|
+
*/
|
|
881
|
+
const WrittenMetaSchema = zod.z.record(zod.z.string(), zod.z.unknown());
|
|
882
|
+
//#endregion
|
|
883
|
+
//#region src/slugs.ts
|
|
884
|
+
const slugOptions = /* @__PURE__ */ new WeakMap();
|
|
885
|
+
const setSlugOptions = (definition, options) => {
|
|
886
|
+
slugOptions.set(definition, options);
|
|
887
|
+
};
|
|
888
|
+
/**
|
|
889
|
+
* The slug a text makes, in the definition's style. A text with no letters or digits makes `''`.
|
|
890
|
+
*/
|
|
891
|
+
const slugOf = (definition, text) => {
|
|
892
|
+
const options = slugOptions.get(definition);
|
|
893
|
+
return (0, _sindresorhus_slugify.default)(text, {
|
|
894
|
+
...options?.locale === void 0 ? {} : { locale: options.locale },
|
|
895
|
+
...options?.replacements === void 0 ? {} : { customReplacements: options.replacements.map(([from, to]) => [from, to]) }
|
|
896
|
+
});
|
|
897
|
+
};
|
|
898
|
+
const generatedSlugFieldsOf = (fields) => fields.filter((field) => field.type === "slug" && field.generateFrom !== void 0);
|
|
899
|
+
/**
|
|
900
|
+
* Checks that a slug's `generateFrom` names a text field beside it.
|
|
901
|
+
*/
|
|
902
|
+
const checkSlugs = (label, fields) => {
|
|
903
|
+
for (const slug of generatedSlugFieldsOf(fields)) {
|
|
904
|
+
if (typeof slug.generateFrom === "function") continue;
|
|
905
|
+
const source = fields.find((field) => field.name === slug.generateFrom);
|
|
906
|
+
if (source === void 0 || source.type !== "text") throw new Error(`${label} makes the slug '${slug.name}' from '${slug.generateFrom}', which is no text field of it.`);
|
|
907
|
+
}
|
|
908
|
+
};
|
|
909
|
+
/**
|
|
910
|
+
* Fills each empty slug in a new document from its `generateFrom`. A made slug that comes out empty counts as no slug,
|
|
911
|
+
* so a required one answers 422.
|
|
912
|
+
*/
|
|
913
|
+
const withGeneratedSlugs = (definition, values) => {
|
|
914
|
+
const filled = { ...values };
|
|
915
|
+
for (const slug of generatedSlugFieldsOf(definition.fields)) {
|
|
916
|
+
const current = filled[slug.name];
|
|
917
|
+
if (current !== void 0 && current !== "") continue;
|
|
918
|
+
const source = typeof slug.generateFrom === "function" ? slug.generateFrom(filled) : filled[slug.generateFrom];
|
|
919
|
+
const made = typeof source === "string" ? slugOf(definition, source) : "";
|
|
920
|
+
if (made === "") delete filled[slug.name];
|
|
921
|
+
else filled[slug.name] = made;
|
|
922
|
+
}
|
|
923
|
+
return filled;
|
|
924
|
+
};
|
|
925
|
+
/**
|
|
926
|
+
* Whether the CMS fills in the slug when a new document leaves it out.
|
|
927
|
+
*/
|
|
928
|
+
const isGeneratedSlug = (field) => field.type === "slug" && field.generateFrom !== void 0;
|
|
929
|
+
//#endregion
|
|
930
|
+
//#region src/collection.ts
|
|
931
|
+
const NAME_PATTERN = /^[a-z][a-zA-Z0-9]*$/;
|
|
932
|
+
/**
|
|
933
|
+
* Names no collection may take, because the CMS's own routes sit at these paths.
|
|
934
|
+
*/
|
|
935
|
+
const RESERVED_COLLECTION_NAMES = new Set(["globals", "storage"]);
|
|
936
|
+
const MODEL_NAME_PATTERN = /^[A-Z][a-zA-Z0-9]*$/;
|
|
937
|
+
const RESERVED_FIELDS = new Set([
|
|
938
|
+
"id",
|
|
939
|
+
"createdAt",
|
|
940
|
+
"updatedAt",
|
|
941
|
+
"createdBy",
|
|
942
|
+
"updatedBy",
|
|
943
|
+
"meta"
|
|
944
|
+
]);
|
|
945
|
+
/**
|
|
946
|
+
* Checks the name and fields of a collection, global or store.
|
|
947
|
+
*/
|
|
948
|
+
const checkDefinition = (label, name, fields, example) => {
|
|
949
|
+
if (!NAME_PATTERN.test(name)) throw new Error(`${label} needs a camelCase name that starts with a letter, like ${example}.`);
|
|
950
|
+
const seen = /* @__PURE__ */ new Set();
|
|
951
|
+
for (const field of fields) {
|
|
952
|
+
if (RESERVED_FIELDS.has(field.name)) throw new Error(`${label} has a field named '${field.name}', which every document already carries.`);
|
|
953
|
+
if (seen.has(field.name)) throw new Error(`${label} has two fields named '${field.name}'.`);
|
|
954
|
+
seen.add(field.name);
|
|
955
|
+
}
|
|
956
|
+
checkSlugs(label, fields);
|
|
957
|
+
};
|
|
958
|
+
/**
|
|
959
|
+
* `blogPosts` as "Blog posts".
|
|
960
|
+
*/
|
|
961
|
+
const sentenceCaseOf = (name) => {
|
|
962
|
+
const words = name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase();
|
|
963
|
+
return words.charAt(0).toUpperCase() + words.slice(1);
|
|
964
|
+
};
|
|
965
|
+
/**
|
|
966
|
+
* Returns what a collection calls one document and the whole collection, from its `labels` or its name.
|
|
967
|
+
*/
|
|
968
|
+
const labelsOf = (collection) => ({
|
|
969
|
+
singular: collection.labels?.singular ?? sentenceCaseOf(pluralize.default.singular(collection.name)),
|
|
970
|
+
plural: collection.labels?.plural ?? sentenceCaseOf(collection.name)
|
|
971
|
+
});
|
|
972
|
+
/**
|
|
973
|
+
* The document's type name: `model`, or the singular of `name` with a capital letter.
|
|
974
|
+
*/
|
|
975
|
+
const modelNameOf = (collection) => {
|
|
976
|
+
const singular = pluralize.default.singular(collection.name);
|
|
977
|
+
return collection.model ?? singular.charAt(0).toUpperCase() + singular.slice(1);
|
|
978
|
+
};
|
|
979
|
+
/**
|
|
980
|
+
* Checks a collection's definition and returns the collection, for `k.collection`.
|
|
981
|
+
*/
|
|
982
|
+
const defineCollection = (declared) => {
|
|
983
|
+
const definition = withTitleDefaults(`Collection '${declared.name}'`, declared);
|
|
984
|
+
checkDefinition(`Collection '${definition.name}'`, definition.name, definition.fields, "`stores` or `blogPosts`");
|
|
985
|
+
if (RESERVED_COLLECTION_NAMES.has(definition.name)) throw new Error(`Collection '${definition.name}' takes the path /${definition.name}, where the CMS's own routes sit. Pick another name.`);
|
|
986
|
+
checkMeta(`Collection '${definition.name}'`, definition);
|
|
987
|
+
if (definition.model !== void 0 && !MODEL_NAME_PATTERN.test(definition.model)) throw new Error(`Collection '${definition.name}' needs a \`model\` that starts with a capital letter, like \`Employee\`.`);
|
|
988
|
+
const title = modelNameOf(definition);
|
|
989
|
+
return {
|
|
990
|
+
...definition,
|
|
991
|
+
...definition.meta === true ? { meta: {} } : {},
|
|
992
|
+
kind: "collection",
|
|
993
|
+
schema: kizunajs.Kizuna.model({
|
|
994
|
+
title,
|
|
995
|
+
schema: documentSchemaOf(definition)
|
|
996
|
+
})
|
|
997
|
+
};
|
|
998
|
+
};
|
|
999
|
+
/**
|
|
1000
|
+
* The editor a document's `createdBy` or `updatedBy` names.
|
|
1001
|
+
*/
|
|
1002
|
+
const EditorReferenceSchema = kizunajs.Kizuna.model({
|
|
1003
|
+
title: "EditorRef",
|
|
1004
|
+
schema: zod.z.object({
|
|
1005
|
+
id: zod.z.string(),
|
|
1006
|
+
name: zod.z.string()
|
|
1007
|
+
})
|
|
1008
|
+
});
|
|
1009
|
+
const DocumentMetaShape = {
|
|
1010
|
+
id: zod.z.string().describe("The document's id."),
|
|
1011
|
+
createdAt: zod.z.iso.datetime().describe("When the document was made."),
|
|
1012
|
+
updatedAt: zod.z.iso.datetime().describe("When the document last changed."),
|
|
1013
|
+
createdBy: EditorReferenceSchema.optional().describe("Who made it."),
|
|
1014
|
+
updatedBy: EditorReferenceSchema.optional().describe("Who changed it last.")
|
|
1015
|
+
};
|
|
1016
|
+
/**
|
|
1017
|
+
* Returns the schema of one stored document of a collection.
|
|
1018
|
+
*/
|
|
1019
|
+
const documentSchemaOf = (collection) => {
|
|
1020
|
+
const owner = modelNameOf(collection);
|
|
1021
|
+
const shape = { ...DocumentMetaShape };
|
|
1022
|
+
for (const field of collection.fields) setReadSchema(shape, field, () => field.required === true ? schemaOf(field, owner) : wrappedSchemaOf(field, (schema) => schema.optional(), owner));
|
|
1023
|
+
if (collection.meta !== void 0) shape["meta"] = metaReadSchemaOf(collection, owner);
|
|
1024
|
+
return zod.z.object(shape);
|
|
1025
|
+
};
|
|
1026
|
+
/**
|
|
1027
|
+
* The schema a create's body passes, without the read-only fields.
|
|
1028
|
+
*/
|
|
1029
|
+
const createSchemaOf = (collection) => {
|
|
1030
|
+
const shape = {};
|
|
1031
|
+
for (const field of collection.fields) {
|
|
1032
|
+
if (field.readOnly === true) continue;
|
|
1033
|
+
shape[field.name] = field.required === true && !isGeneratedSlug(field) ? writeSchemaOf(field) : wrappedWriteSchemaOf(field, (schema) => schema.optional());
|
|
1034
|
+
}
|
|
1035
|
+
if (collection.meta !== void 0) shape["meta"] = metaWriteSchemaOf(collection);
|
|
1036
|
+
return zod.z.strictObject(shape);
|
|
1037
|
+
};
|
|
1038
|
+
/**
|
|
1039
|
+
* The schema an update's body passes, where every writable field is optional and `null` clears an optional one.
|
|
1040
|
+
*/
|
|
1041
|
+
const updateSchemaOf = (collection) => {
|
|
1042
|
+
const shape = {};
|
|
1043
|
+
for (const field of collection.fields) {
|
|
1044
|
+
if (field.readOnly === true) continue;
|
|
1045
|
+
shape[field.name] = wrappedWriteSchemaOf(field, (schema) => field.required === true ? schema.optional() : schema.nullable().optional());
|
|
1046
|
+
}
|
|
1047
|
+
if (collection.meta !== void 0) shape["meta"] = metaWriteSchemaOf(collection);
|
|
1048
|
+
return zod.z.strictObject(shape);
|
|
1049
|
+
};
|
|
1050
|
+
//#endregion
|
|
1051
|
+
//#region src/where.ts
|
|
1052
|
+
const OPERATORS = new Set([
|
|
1053
|
+
"equals",
|
|
1054
|
+
"not",
|
|
1055
|
+
"in",
|
|
1056
|
+
"notIn",
|
|
1057
|
+
"exists",
|
|
1058
|
+
"contains",
|
|
1059
|
+
"hasAll",
|
|
1060
|
+
"greaterThan",
|
|
1061
|
+
"atLeast",
|
|
1062
|
+
"lessThan",
|
|
1063
|
+
"atMost"
|
|
1064
|
+
]);
|
|
1065
|
+
/**
|
|
1066
|
+
* Each field's conditions. Throws on an operator the CMS doesn't know.
|
|
1067
|
+
*/
|
|
1068
|
+
const conditionsOf = (where) => {
|
|
1069
|
+
const conditions = [];
|
|
1070
|
+
for (const [field, operators] of Object.entries(where)) {
|
|
1071
|
+
if (field === "and" || field === "or" || operators === void 0) continue;
|
|
1072
|
+
for (const [operator, value] of Object.entries(operators)) {
|
|
1073
|
+
if (!OPERATORS.has(operator)) throw new Error(`'${operator}' on '${field}' is not an operator. Use one of: ${[...OPERATORS].join(", ")}.`);
|
|
1074
|
+
if (value === void 0) continue;
|
|
1075
|
+
conditions.push({
|
|
1076
|
+
field,
|
|
1077
|
+
operator,
|
|
1078
|
+
value
|
|
1079
|
+
});
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
return conditions;
|
|
1083
|
+
};
|
|
1084
|
+
/**
|
|
1085
|
+
* The sort as field names and directions, in turn.
|
|
1086
|
+
*/
|
|
1087
|
+
const sortOrderOf = (sort) => (sort === void 0 ? [] : typeof sort === "string" ? [sort] : sort).map((key) => key.startsWith("-") ? {
|
|
1088
|
+
field: key.slice(1),
|
|
1089
|
+
descending: true
|
|
1090
|
+
} : {
|
|
1091
|
+
field: key,
|
|
1092
|
+
descending: false
|
|
1093
|
+
});
|
|
1094
|
+
const isPresent = (value) => value !== void 0 && value !== null;
|
|
1095
|
+
const matchesCondition = (actual, operator, expected) => {
|
|
1096
|
+
switch (operator) {
|
|
1097
|
+
case "equals": return actual === expected;
|
|
1098
|
+
case "not": return actual !== expected;
|
|
1099
|
+
case "in": return Array.isArray(actual) ? actual.some((item) => expected.includes(item)) : expected.includes(actual);
|
|
1100
|
+
case "notIn": return !expected.includes(actual);
|
|
1101
|
+
case "exists": return isPresent(actual) === expected;
|
|
1102
|
+
case "contains": return Array.isArray(actual) ? actual.includes(expected) : typeof actual === "string" && actual.toLowerCase().includes(String(expected).toLowerCase());
|
|
1103
|
+
case "hasAll": return Array.isArray(actual) && expected.every((item) => actual.includes(item));
|
|
1104
|
+
case "greaterThan": return isPresent(actual) && actual > expected;
|
|
1105
|
+
case "atLeast": return isPresent(actual) && actual >= expected;
|
|
1106
|
+
case "lessThan": return isPresent(actual) && actual < expected;
|
|
1107
|
+
case "atMost": return isPresent(actual) && actual <= expected;
|
|
1108
|
+
default: return false;
|
|
1109
|
+
}
|
|
1110
|
+
};
|
|
1111
|
+
/**
|
|
1112
|
+
* A field's value, following a dotted path like `cover.file` into a stored object.
|
|
1113
|
+
*/
|
|
1114
|
+
const valueAt = (document, path) => path.split(".").reduce((value, key) => value !== null && typeof value === "object" ? value[key] : void 0, document);
|
|
1115
|
+
/**
|
|
1116
|
+
* Whether a document matches a `where`.
|
|
1117
|
+
*/
|
|
1118
|
+
const matchesWhere = (document, where) => conditionsOf(where).every(({ field, operator, value }) => matchesCondition(valueAt(document, field), operator, value)) && (where.and ?? []).every((part) => matchesWhere(document, part)) && (where.or === void 0 || where.or.some((part) => matchesWhere(document, part)));
|
|
1119
|
+
/**
|
|
1120
|
+
* Orders documents by a sort. A document without the value comes last.
|
|
1121
|
+
*/
|
|
1122
|
+
const compareBySort = (sort) => (first, second) => {
|
|
1123
|
+
for (const { field, descending } of sort) {
|
|
1124
|
+
const left = first[field];
|
|
1125
|
+
const right = second[field];
|
|
1126
|
+
if (left === right) continue;
|
|
1127
|
+
if (!isPresent(left)) return 1;
|
|
1128
|
+
if (!isPresent(right)) return -1;
|
|
1129
|
+
const order = left < right ? -1 : 1;
|
|
1130
|
+
return descending ? -order : order;
|
|
1131
|
+
}
|
|
1132
|
+
return 0;
|
|
1133
|
+
};
|
|
1134
|
+
//#endregion
|
|
1135
|
+
//#region src/db.ts
|
|
1136
|
+
/**
|
|
1137
|
+
* The collection that holds globals, one document each with the global's name as its id.
|
|
1138
|
+
*/
|
|
1139
|
+
const GLOBALS_COLLECTION = "globals";
|
|
1140
|
+
/**
|
|
1141
|
+
* The error an adapter throws when another document blocks a write, which routes answer with a 409.
|
|
1142
|
+
*/
|
|
1143
|
+
var ConflictError = class extends Error {};
|
|
1144
|
+
const withoutNulls = (values) => Object.fromEntries(Object.entries(values).filter(([, value]) => value !== null && value !== void 0));
|
|
1145
|
+
/**
|
|
1146
|
+
* Creates a database adapter that keeps everything in memory, for tests. Nothing survives a restart.
|
|
1147
|
+
*
|
|
1148
|
+
* @example
|
|
1149
|
+
* export default defineConfig({
|
|
1150
|
+
* name: 'Example',
|
|
1151
|
+
* db: memoryAdapter(),
|
|
1152
|
+
* collections: [Articles, Users],
|
|
1153
|
+
* users: Users,
|
|
1154
|
+
* roles: ['editor'],
|
|
1155
|
+
* });
|
|
1156
|
+
*/
|
|
1157
|
+
const memoryAdapter = () => {
|
|
1158
|
+
const collections = /* @__PURE__ */ new Map();
|
|
1159
|
+
const passwordHashes = /* @__PURE__ */ new Map();
|
|
1160
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
1161
|
+
const passwordTokens = /* @__PURE__ */ new Map();
|
|
1162
|
+
const failedLogins = /* @__PURE__ */ new Map();
|
|
1163
|
+
const passwordResetRequests = /* @__PURE__ */ new Map();
|
|
1164
|
+
/**
|
|
1165
|
+
* The collections that hold a store's file records, where one key has one record.
|
|
1166
|
+
*/
|
|
1167
|
+
const stores = /* @__PURE__ */ new Set();
|
|
1168
|
+
const withoutTimesBefore = (times, before) => {
|
|
1169
|
+
for (const [key, kept] of times) {
|
|
1170
|
+
const recent = kept.filter((at) => at >= before);
|
|
1171
|
+
if (recent.length === 0) times.delete(key);
|
|
1172
|
+
else times.set(key, recent);
|
|
1173
|
+
}
|
|
1174
|
+
};
|
|
1175
|
+
const documentsOf = (collection) => {
|
|
1176
|
+
const existing = collections.get(collection);
|
|
1177
|
+
if (existing !== void 0) return existing;
|
|
1178
|
+
const created = /* @__PURE__ */ new Map();
|
|
1179
|
+
collections.set(collection, created);
|
|
1180
|
+
return created;
|
|
1181
|
+
};
|
|
1182
|
+
const createGlobalIfMissing = (name) => {
|
|
1183
|
+
const globals = documentsOf(GLOBALS_COLLECTION);
|
|
1184
|
+
if (globals.has(name)) return;
|
|
1185
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1186
|
+
globals.set(name, {
|
|
1187
|
+
id: name,
|
|
1188
|
+
createdAt: now,
|
|
1189
|
+
updatedAt: now
|
|
1190
|
+
});
|
|
1191
|
+
};
|
|
1192
|
+
const db = {
|
|
1193
|
+
prepare: (definitions) => {
|
|
1194
|
+
for (const store of definitions.storage) stores.add(fileCollectionOf(store));
|
|
1195
|
+
},
|
|
1196
|
+
list: async (collection, page, options) => {
|
|
1197
|
+
const where = options?.where;
|
|
1198
|
+
const ids = options?.ids;
|
|
1199
|
+
const readable = [...documentsOf(collection).values()].filter((document) => ids === void 0 || ids.includes(document.id)).filter((document) => where === void 0 || matchesWhere(document, where)).sort(compareBySort(sortOrderOf(options?.sort)));
|
|
1200
|
+
return {
|
|
1201
|
+
items: readable.slice(page.offset, page.offset + page.limit),
|
|
1202
|
+
total: readable.length
|
|
1203
|
+
};
|
|
1204
|
+
},
|
|
1205
|
+
get: async (collection, id) => documentsOf(collection).get(id),
|
|
1206
|
+
create: async (collection, values, by) => {
|
|
1207
|
+
if (stores.has(collection) && [...documentsOf(collection).values()].some((document) => document["key"] === values["key"])) throw new ConflictError(`Another file has the key '${String(values["key"])}'.`);
|
|
1208
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1209
|
+
const document = {
|
|
1210
|
+
...values,
|
|
1211
|
+
id: crypto.randomUUID(),
|
|
1212
|
+
createdAt: now,
|
|
1213
|
+
updatedAt: now,
|
|
1214
|
+
...by === void 0 ? {} : {
|
|
1215
|
+
createdBy: by,
|
|
1216
|
+
updatedBy: by
|
|
1217
|
+
}
|
|
1218
|
+
};
|
|
1219
|
+
documentsOf(collection).set(document.id, document);
|
|
1220
|
+
return document;
|
|
1221
|
+
},
|
|
1222
|
+
update: async (collection, id, values, by) => {
|
|
1223
|
+
const documents = documentsOf(collection);
|
|
1224
|
+
const existing = documents.get(id);
|
|
1225
|
+
if (existing === void 0) return void 0;
|
|
1226
|
+
const updated = {
|
|
1227
|
+
...withoutNulls({
|
|
1228
|
+
...existing,
|
|
1229
|
+
...values
|
|
1230
|
+
}),
|
|
1231
|
+
id,
|
|
1232
|
+
createdAt: existing.createdAt,
|
|
1233
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1234
|
+
...by === void 0 ? {} : { updatedBy: by }
|
|
1235
|
+
};
|
|
1236
|
+
documents.set(id, updated);
|
|
1237
|
+
return updated;
|
|
1238
|
+
},
|
|
1239
|
+
delete: async (collection, id) => {
|
|
1240
|
+
passwordHashes.delete(`${collection}\u0000${id}`);
|
|
1241
|
+
for (const [tokenHash, session] of sessions) if (session.accountId === id) sessions.delete(tokenHash);
|
|
1242
|
+
for (const [tokenHash, token] of passwordTokens) if (token.accountId === id) passwordTokens.delete(tokenHash);
|
|
1243
|
+
return documentsOf(collection).delete(id);
|
|
1244
|
+
},
|
|
1245
|
+
getGlobal: (name) => db.get(GLOBALS_COLLECTION, name),
|
|
1246
|
+
updateGlobal: async (name, values, by) => {
|
|
1247
|
+
createGlobalIfMissing(name);
|
|
1248
|
+
return await db.update(GLOBALS_COLLECTION, name, values, by);
|
|
1249
|
+
},
|
|
1250
|
+
passwordHashOf: async (collection, id) => passwordHashes.get(`${collection}\u0000${id}`),
|
|
1251
|
+
setPasswordHash: async (collection, id, hash) => {
|
|
1252
|
+
if (documentsOf(collection).has(id)) passwordHashes.set(`${collection}\u0000${id}`, hash);
|
|
1253
|
+
},
|
|
1254
|
+
createSession: async (session) => {
|
|
1255
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1256
|
+
for (const [tokenHash, stored] of sessions) if (stored.expiresAt <= now) sessions.delete(tokenHash);
|
|
1257
|
+
sessions.set(session.tokenHash, { ...session });
|
|
1258
|
+
},
|
|
1259
|
+
getSession: async (tokenHash) => sessions.get(tokenHash),
|
|
1260
|
+
deleteSession: async (tokenHash) => {
|
|
1261
|
+
sessions.delete(tokenHash);
|
|
1262
|
+
},
|
|
1263
|
+
deleteSessionsOf: async (accountId, keep) => {
|
|
1264
|
+
for (const [tokenHash, session] of sessions) if (session.accountId === accountId && tokenHash !== keep) sessions.delete(tokenHash);
|
|
1265
|
+
},
|
|
1266
|
+
createPasswordToken: async (token) => {
|
|
1267
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1268
|
+
for (const [tokenHash, stored] of passwordTokens) if (stored.expiresAt <= now) passwordTokens.delete(tokenHash);
|
|
1269
|
+
passwordTokens.set(token.tokenHash, { ...token });
|
|
1270
|
+
},
|
|
1271
|
+
takePasswordToken: async (tokenHash) => {
|
|
1272
|
+
const token = passwordTokens.get(tokenHash);
|
|
1273
|
+
passwordTokens.delete(tokenHash);
|
|
1274
|
+
return token;
|
|
1275
|
+
},
|
|
1276
|
+
deletePasswordTokensOf: async (accountId) => {
|
|
1277
|
+
for (const [tokenHash, token] of passwordTokens) if (token.accountId === accountId) passwordTokens.delete(tokenHash);
|
|
1278
|
+
},
|
|
1279
|
+
recordFailedLogin: async (collection, email) => {
|
|
1280
|
+
withoutTimesBefore(failedLogins, new Date(Date.now() - LOGIN_WINDOW).toISOString());
|
|
1281
|
+
const key = `${collection}\u0000${email}`;
|
|
1282
|
+
failedLogins.set(key, [...failedLogins.get(key) ?? [], (/* @__PURE__ */ new Date()).toISOString()]);
|
|
1283
|
+
},
|
|
1284
|
+
failedLoginsSince: async (collection, email, since) => (failedLogins.get(`${collection}\u0000${email}`) ?? []).filter((at) => at >= since).length,
|
|
1285
|
+
clearFailedLogins: async (collection, email) => {
|
|
1286
|
+
failedLogins.delete(`${collection}\u0000${email}`);
|
|
1287
|
+
},
|
|
1288
|
+
recordPasswordResetRequest: async (collection, email) => {
|
|
1289
|
+
withoutTimesBefore(passwordResetRequests, new Date(Date.now() - PASSWORD_RESET_WINDOW).toISOString());
|
|
1290
|
+
const key = `${collection}\u0000${email}`;
|
|
1291
|
+
passwordResetRequests.set(key, [...passwordResetRequests.get(key) ?? [], (/* @__PURE__ */ new Date()).toISOString()]);
|
|
1292
|
+
},
|
|
1293
|
+
passwordResetRequestsSince: async (collection, email, since) => (passwordResetRequests.get(`${collection}\u0000${email}`) ?? []).filter((at) => at >= since).length
|
|
1294
|
+
};
|
|
1295
|
+
return db;
|
|
1296
|
+
};
|
|
1297
|
+
//#endregion
|
|
1298
|
+
Object.defineProperty(exports, "ConflictError", {
|
|
1299
|
+
enumerable: true,
|
|
1300
|
+
get: function() {
|
|
1301
|
+
return ConflictError;
|
|
1302
|
+
}
|
|
1303
|
+
});
|
|
1304
|
+
Object.defineProperty(exports, "DEFAULT_MAX_UPLOAD_BYTES", {
|
|
1305
|
+
enumerable: true,
|
|
1306
|
+
get: function() {
|
|
1307
|
+
return DEFAULT_MAX_UPLOAD_BYTES;
|
|
1308
|
+
}
|
|
1309
|
+
});
|
|
1310
|
+
Object.defineProperty(exports, "EditorReferenceSchema", {
|
|
1311
|
+
enumerable: true,
|
|
1312
|
+
get: function() {
|
|
1313
|
+
return EditorReferenceSchema;
|
|
1314
|
+
}
|
|
1315
|
+
});
|
|
1316
|
+
Object.defineProperty(exports, "FocalPointSchema", {
|
|
1317
|
+
enumerable: true,
|
|
1318
|
+
get: function() {
|
|
1319
|
+
return FocalPointSchema;
|
|
1320
|
+
}
|
|
1321
|
+
});
|
|
1322
|
+
Object.defineProperty(exports, "GLOBALS_COLLECTION", {
|
|
1323
|
+
enumerable: true,
|
|
1324
|
+
get: function() {
|
|
1325
|
+
return GLOBALS_COLLECTION;
|
|
1326
|
+
}
|
|
1327
|
+
});
|
|
1328
|
+
Object.defineProperty(exports, "INVITE_LIFETIME", {
|
|
1329
|
+
enumerable: true,
|
|
1330
|
+
get: function() {
|
|
1331
|
+
return INVITE_LIFETIME;
|
|
1332
|
+
}
|
|
1333
|
+
});
|
|
1334
|
+
Object.defineProperty(exports, "LOGIN_WINDOW", {
|
|
1335
|
+
enumerable: true,
|
|
1336
|
+
get: function() {
|
|
1337
|
+
return LOGIN_WINDOW;
|
|
1338
|
+
}
|
|
1339
|
+
});
|
|
1340
|
+
Object.defineProperty(exports, "MAX_IMAGE_PIXELS", {
|
|
1341
|
+
enumerable: true,
|
|
1342
|
+
get: function() {
|
|
1343
|
+
return MAX_IMAGE_PIXELS;
|
|
1344
|
+
}
|
|
1345
|
+
});
|
|
1346
|
+
Object.defineProperty(exports, "PASSWORD_RESET_LIFETIME", {
|
|
1347
|
+
enumerable: true,
|
|
1348
|
+
get: function() {
|
|
1349
|
+
return PASSWORD_RESET_LIFETIME;
|
|
1350
|
+
}
|
|
1351
|
+
});
|
|
1352
|
+
Object.defineProperty(exports, "PASSWORD_RESET_WINDOW", {
|
|
1353
|
+
enumerable: true,
|
|
1354
|
+
get: function() {
|
|
1355
|
+
return PASSWORD_RESET_WINDOW;
|
|
1356
|
+
}
|
|
1357
|
+
});
|
|
1358
|
+
Object.defineProperty(exports, "SESSION_LIFETIME", {
|
|
1359
|
+
enumerable: true,
|
|
1360
|
+
get: function() {
|
|
1361
|
+
return SESSION_LIFETIME;
|
|
1362
|
+
}
|
|
1363
|
+
});
|
|
1364
|
+
Object.defineProperty(exports, "SlugSchema", {
|
|
1365
|
+
enumerable: true,
|
|
1366
|
+
get: function() {
|
|
1367
|
+
return SlugSchema;
|
|
1368
|
+
}
|
|
1369
|
+
});
|
|
1370
|
+
Object.defineProperty(exports, "TextSchema", {
|
|
1371
|
+
enumerable: true,
|
|
1372
|
+
get: function() {
|
|
1373
|
+
return TextSchema;
|
|
1374
|
+
}
|
|
1375
|
+
});
|
|
1376
|
+
Object.defineProperty(exports, "WrittenMetaSchema", {
|
|
1377
|
+
enumerable: true,
|
|
1378
|
+
get: function() {
|
|
1379
|
+
return WrittenMetaSchema;
|
|
1380
|
+
}
|
|
1381
|
+
});
|
|
1382
|
+
Object.defineProperty(exports, "__toESM", {
|
|
1383
|
+
enumerable: true,
|
|
1384
|
+
get: function() {
|
|
1385
|
+
return __toESM;
|
|
1386
|
+
}
|
|
1387
|
+
});
|
|
1388
|
+
Object.defineProperty(exports, "acceptsType", {
|
|
1389
|
+
enumerable: true,
|
|
1390
|
+
get: function() {
|
|
1391
|
+
return acceptsType;
|
|
1392
|
+
}
|
|
1393
|
+
});
|
|
1394
|
+
Object.defineProperty(exports, "checkDefinition", {
|
|
1395
|
+
enumerable: true,
|
|
1396
|
+
get: function() {
|
|
1397
|
+
return checkDefinition;
|
|
1398
|
+
}
|
|
1399
|
+
});
|
|
1400
|
+
Object.defineProperty(exports, "columnOf", {
|
|
1401
|
+
enumerable: true,
|
|
1402
|
+
get: function() {
|
|
1403
|
+
return columnOf;
|
|
1404
|
+
}
|
|
1405
|
+
});
|
|
1406
|
+
Object.defineProperty(exports, "conditionsOf", {
|
|
1407
|
+
enumerable: true,
|
|
1408
|
+
get: function() {
|
|
1409
|
+
return conditionsOf;
|
|
1410
|
+
}
|
|
1411
|
+
});
|
|
1412
|
+
Object.defineProperty(exports, "createSchemaOf", {
|
|
1413
|
+
enumerable: true,
|
|
1414
|
+
get: function() {
|
|
1415
|
+
return createSchemaOf;
|
|
1416
|
+
}
|
|
1417
|
+
});
|
|
1418
|
+
Object.defineProperty(exports, "defineCollection", {
|
|
1419
|
+
enumerable: true,
|
|
1420
|
+
get: function() {
|
|
1421
|
+
return defineCollection;
|
|
1422
|
+
}
|
|
1423
|
+
});
|
|
1424
|
+
Object.defineProperty(exports, "defineStorage", {
|
|
1425
|
+
enumerable: true,
|
|
1426
|
+
get: function() {
|
|
1427
|
+
return defineStorage;
|
|
1428
|
+
}
|
|
1429
|
+
});
|
|
1430
|
+
Object.defineProperty(exports, "diskStorage", {
|
|
1431
|
+
enumerable: true,
|
|
1432
|
+
get: function() {
|
|
1433
|
+
return diskStorage;
|
|
1434
|
+
}
|
|
1435
|
+
});
|
|
1436
|
+
Object.defineProperty(exports, "documentSchemaOf", {
|
|
1437
|
+
enumerable: true,
|
|
1438
|
+
get: function() {
|
|
1439
|
+
return documentSchemaOf;
|
|
1440
|
+
}
|
|
1441
|
+
});
|
|
1442
|
+
Object.defineProperty(exports, "editorReferencesOf", {
|
|
1443
|
+
enumerable: true,
|
|
1444
|
+
get: function() {
|
|
1445
|
+
return editorReferencesOf;
|
|
1446
|
+
}
|
|
1447
|
+
});
|
|
1448
|
+
Object.defineProperty(exports, "fileCollectionOf", {
|
|
1449
|
+
enumerable: true,
|
|
1450
|
+
get: function() {
|
|
1451
|
+
return fileCollectionOf;
|
|
1452
|
+
}
|
|
1453
|
+
});
|
|
1454
|
+
Object.defineProperty(exports, "fileProblemOf", {
|
|
1455
|
+
enumerable: true,
|
|
1456
|
+
get: function() {
|
|
1457
|
+
return fileProblemOf;
|
|
1458
|
+
}
|
|
1459
|
+
});
|
|
1460
|
+
Object.defineProperty(exports, "isFileField", {
|
|
1461
|
+
enumerable: true,
|
|
1462
|
+
get: function() {
|
|
1463
|
+
return isFileField;
|
|
1464
|
+
}
|
|
1465
|
+
});
|
|
1466
|
+
Object.defineProperty(exports, "isGeneratedSlug", {
|
|
1467
|
+
enumerable: true,
|
|
1468
|
+
get: function() {
|
|
1469
|
+
return isGeneratedSlug;
|
|
1470
|
+
}
|
|
1471
|
+
});
|
|
1472
|
+
Object.defineProperty(exports, "labelsOf", {
|
|
1473
|
+
enumerable: true,
|
|
1474
|
+
get: function() {
|
|
1475
|
+
return labelsOf;
|
|
1476
|
+
}
|
|
1477
|
+
});
|
|
1478
|
+
Object.defineProperty(exports, "memoryAdapter", {
|
|
1479
|
+
enumerable: true,
|
|
1480
|
+
get: function() {
|
|
1481
|
+
return memoryAdapter;
|
|
1482
|
+
}
|
|
1483
|
+
});
|
|
1484
|
+
Object.defineProperty(exports, "memoryStorage", {
|
|
1485
|
+
enumerable: true,
|
|
1486
|
+
get: function() {
|
|
1487
|
+
return memoryStorage;
|
|
1488
|
+
}
|
|
1489
|
+
});
|
|
1490
|
+
Object.defineProperty(exports, "mergeMetaChange", {
|
|
1491
|
+
enumerable: true,
|
|
1492
|
+
get: function() {
|
|
1493
|
+
return mergeMetaChange;
|
|
1494
|
+
}
|
|
1495
|
+
});
|
|
1496
|
+
Object.defineProperty(exports, "metaImageProblemOf", {
|
|
1497
|
+
enumerable: true,
|
|
1498
|
+
get: function() {
|
|
1499
|
+
return metaImageProblemOf;
|
|
1500
|
+
}
|
|
1501
|
+
});
|
|
1502
|
+
Object.defineProperty(exports, "metaImageStoreOf", {
|
|
1503
|
+
enumerable: true,
|
|
1504
|
+
get: function() {
|
|
1505
|
+
return metaImageStoreOf;
|
|
1506
|
+
}
|
|
1507
|
+
});
|
|
1508
|
+
Object.defineProperty(exports, "modelNameOf", {
|
|
1509
|
+
enumerable: true,
|
|
1510
|
+
get: function() {
|
|
1511
|
+
return modelNameOf;
|
|
1512
|
+
}
|
|
1513
|
+
});
|
|
1514
|
+
Object.defineProperty(exports, "newFileKey", {
|
|
1515
|
+
enumerable: true,
|
|
1516
|
+
get: function() {
|
|
1517
|
+
return newFileKey;
|
|
1518
|
+
}
|
|
1519
|
+
});
|
|
1520
|
+
Object.defineProperty(exports, "registerStores", {
|
|
1521
|
+
enumerable: true,
|
|
1522
|
+
get: function() {
|
|
1523
|
+
return registerStores;
|
|
1524
|
+
}
|
|
1525
|
+
});
|
|
1526
|
+
Object.defineProperty(exports, "resolveDocuments", {
|
|
1527
|
+
enumerable: true,
|
|
1528
|
+
get: function() {
|
|
1529
|
+
return resolveDocuments;
|
|
1530
|
+
}
|
|
1531
|
+
});
|
|
1532
|
+
Object.defineProperty(exports, "schemaOf", {
|
|
1533
|
+
enumerable: true,
|
|
1534
|
+
get: function() {
|
|
1535
|
+
return schemaOf;
|
|
1536
|
+
}
|
|
1537
|
+
});
|
|
1538
|
+
Object.defineProperty(exports, "setEditorsCollection", {
|
|
1539
|
+
enumerable: true,
|
|
1540
|
+
get: function() {
|
|
1541
|
+
return setEditorsCollection;
|
|
1542
|
+
}
|
|
1543
|
+
});
|
|
1544
|
+
Object.defineProperty(exports, "setReadSchema", {
|
|
1545
|
+
enumerable: true,
|
|
1546
|
+
get: function() {
|
|
1547
|
+
return setReadSchema;
|
|
1548
|
+
}
|
|
1549
|
+
});
|
|
1550
|
+
Object.defineProperty(exports, "setSlugOptions", {
|
|
1551
|
+
enumerable: true,
|
|
1552
|
+
get: function() {
|
|
1553
|
+
return setSlugOptions;
|
|
1554
|
+
}
|
|
1555
|
+
});
|
|
1556
|
+
Object.defineProperty(exports, "setTitleSuffix", {
|
|
1557
|
+
enumerable: true,
|
|
1558
|
+
get: function() {
|
|
1559
|
+
return setTitleSuffix;
|
|
1560
|
+
}
|
|
1561
|
+
});
|
|
1562
|
+
Object.defineProperty(exports, "sortOrderOf", {
|
|
1563
|
+
enumerable: true,
|
|
1564
|
+
get: function() {
|
|
1565
|
+
return sortOrderOf;
|
|
1566
|
+
}
|
|
1567
|
+
});
|
|
1568
|
+
Object.defineProperty(exports, "storeFieldTypesOf", {
|
|
1569
|
+
enumerable: true,
|
|
1570
|
+
get: function() {
|
|
1571
|
+
return storeFieldTypesOf;
|
|
1572
|
+
}
|
|
1573
|
+
});
|
|
1574
|
+
Object.defineProperty(exports, "updateSchemaOf", {
|
|
1575
|
+
enumerable: true,
|
|
1576
|
+
get: function() {
|
|
1577
|
+
return updateSchemaOf;
|
|
1578
|
+
}
|
|
1579
|
+
});
|
|
1580
|
+
Object.defineProperty(exports, "withGeneratedSlugs", {
|
|
1581
|
+
enumerable: true,
|
|
1582
|
+
get: function() {
|
|
1583
|
+
return withGeneratedSlugs;
|
|
1584
|
+
}
|
|
1585
|
+
});
|
|
1586
|
+
Object.defineProperty(exports, "withoutEditorReferences", {
|
|
1587
|
+
enumerable: true,
|
|
1588
|
+
get: function() {
|
|
1589
|
+
return withoutEditorReferences;
|
|
1590
|
+
}
|
|
1591
|
+
});
|
|
1592
|
+
Object.defineProperty(exports, "wrappedSchemaOf", {
|
|
1593
|
+
enumerable: true,
|
|
1594
|
+
get: function() {
|
|
1595
|
+
return wrappedSchemaOf;
|
|
1596
|
+
}
|
|
1597
|
+
});
|
|
1598
|
+
Object.defineProperty(exports, "writtenMetaOf", {
|
|
1599
|
+
enumerable: true,
|
|
1600
|
+
get: function() {
|
|
1601
|
+
return writtenMetaOf;
|
|
1602
|
+
}
|
|
1603
|
+
});
|