@wervt/cms 0.0.4 → 0.0.6
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/README.md +177 -18
- package/dist/editor/assets/Button-DrsXdow7.js +6 -0
- package/dist/editor/assets/RichTextInput-BrNTSUXL.js +271 -0
- package/dist/editor/assets/Toast-DsP3Sdxg.js +13 -0
- package/dist/editor/assets/index-CWQLsBfF.js +16 -0
- package/dist/editor/assets/index-esGfkiTV.css +2 -0
- package/dist/editor/index.html +3 -3
- package/dist/editor-theme.d.ts +3 -0
- package/dist/editor-theme.js +18 -1
- package/dist/module.d.ts +18 -1
- package/dist/module.js +95 -7
- package/dist/routes.js +16 -0
- package/dist/runtime/app/edit-button.d.ts +7 -0
- package/dist/runtime/app/edit-button.js +56 -0
- package/dist/runtime/app/preview.client.js +12 -5
- package/dist/runtime/app/useCmsCollection.d.ts +24 -0
- package/dist/runtime/app/useCmsCollection.js +74 -0
- package/dist/runtime/app/useCmsSeo.d.ts +7 -0
- package/dist/runtime/app/useCmsSeo.js +31 -0
- package/dist/runtime/collections.d.ts +25 -0
- package/dist/runtime/collections.js +81 -0
- package/dist/runtime/editor-link.d.ts +19 -0
- package/dist/runtime/editor-link.js +31 -0
- package/dist/runtime/fields.d.ts +33 -1
- package/dist/runtime/fields.js +143 -7
- package/dist/runtime/pages.d.ts +11 -2
- package/dist/runtime/pages.js +37 -7
- package/dist/runtime/preview.d.ts +5 -2
- package/dist/runtime/preview.js +2 -2
- package/dist/runtime/schema.d.ts +187 -13
- package/dist/runtime/schema.js +115 -1
- package/dist/runtime/seo.d.ts +22 -0
- package/dist/runtime/seo.js +33 -0
- package/dist/runtime/server/access.get.d.ts +4 -0
- package/dist/runtime/server/access.get.js +8 -0
- package/dist/runtime/server/access.js +1 -1
- package/dist/runtime/server/collection.get.d.ts +12 -0
- package/dist/runtime/server/collection.get.js +28 -0
- package/dist/runtime/server/dev-images.d.ts +4 -1
- package/dist/runtime/server/dev-images.js +28 -2
- package/dist/runtime/server/entries.d.ts +53 -0
- package/dist/runtime/server/entries.js +83 -1
- package/dist/runtime/server/entry.delete.d.ts +4 -0
- package/dist/runtime/server/entry.delete.js +31 -0
- package/dist/runtime/server/entry.get.js +6 -6
- package/dist/runtime/server/entry.put.d.ts +1 -0
- package/dist/runtime/server/entry.put.js +20 -8
- package/dist/runtime/server/file-store.d.ts +14 -3
- package/dist/runtime/server/file-store.js +44 -9
- package/dist/runtime/server/image.delete.d.ts +4 -0
- package/dist/runtime/server/image.delete.js +24 -0
- package/dist/runtime/server/images.get.d.ts +5 -0
- package/dist/runtime/server/images.get.js +11 -0
- package/dist/runtime/server/library.d.ts +14 -0
- package/dist/runtime/server/library.js +72 -0
- package/dist/runtime/server/links.get.d.ts +7 -0
- package/dist/runtime/server/links.get.js +35 -0
- package/dist/runtime/server/media.d.ts +74 -0
- package/dist/runtime/server/media.js +88 -0
- package/dist/runtime/server/schema.get.d.ts +8 -0
- package/dist/runtime/server/schema.get.js +17 -7
- package/dist/runtime/server/store.d.ts +11 -2
- package/dist/runtime/server/store.js +110 -20
- package/dist/runtime/server/upload.post.js +3 -2
- package/dist/runtime/server/versions.get.d.ts +20 -0
- package/dist/runtime/server/versions.get.js +36 -0
- package/package.json +3 -2
- package/dist/editor/assets/Button-Dai6Ph2c.js +0 -6
- package/dist/editor/assets/RichTextInput-CdL9ZFoP.js +0 -271
- package/dist/editor/assets/Toast-BaUcosq6.js +0 -13
- package/dist/editor/assets/index-CP6dGIyl.css +0 -2
- package/dist/editor/assets/index-Du-lvx2V.js +0 -16
package/dist/runtime/schema.js
CHANGED
|
@@ -21,6 +21,56 @@ function toggle(value = false, options = {}) {
|
|
|
21
21
|
...options
|
|
22
22
|
};
|
|
23
23
|
}
|
|
24
|
+
function number(value = null, options = {}) {
|
|
25
|
+
return {
|
|
26
|
+
type: "number",
|
|
27
|
+
default: value,
|
|
28
|
+
required: value !== null,
|
|
29
|
+
...options
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
function date(value = null, options = {}) {
|
|
33
|
+
const time = options.time === true;
|
|
34
|
+
for (const [name, given] of [
|
|
35
|
+
["value", value],
|
|
36
|
+
["min", options.min],
|
|
37
|
+
["max", options.max]
|
|
38
|
+
]) if (typeof given === "string" && !isCmsDate(given, time)) throw new Error(`date(): ${name} ${JSON.stringify(given)} isn't ${dateFormat(time)}`);
|
|
39
|
+
return {
|
|
40
|
+
type: "date",
|
|
41
|
+
default: value,
|
|
42
|
+
required: value !== null,
|
|
43
|
+
...options
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
const dateFormat = (time) => time ? "YYYY-MM-DDTHH:mm" : "YYYY-MM-DD";
|
|
47
|
+
/**
|
|
48
|
+
* Whether `value` is a day that exists (`2026-02-30` isn't) in the field's format, and with `time`
|
|
49
|
+
* a time of day (`24:00` isn't). Written alike, two values compare as strings.
|
|
50
|
+
*/
|
|
51
|
+
function isCmsDate(value, time = false) {
|
|
52
|
+
if (typeof value !== "string") return false;
|
|
53
|
+
const match = (time ? /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/ : /^(\d{4})-(\d{2})-(\d{2})$/).exec(value);
|
|
54
|
+
if (!match) return false;
|
|
55
|
+
const [year, month, day, hour = 0, minute = 0] = match.slice(1).map(Number);
|
|
56
|
+
const parsed = new Date(Date.UTC(year, month - 1, day, hour, minute));
|
|
57
|
+
return parsed.getUTCFullYear() === year && parsed.getUTCMonth() === month - 1 && parsed.getUTCDate() === day && parsed.getUTCHours() === hour && parsed.getUTCMinutes() === minute;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* One of a few values, picked from a menu; the page gets the value:
|
|
61
|
+
* `select(['cut', 'color'], 'cut')` or with labels, `select([{ value: 'cut', label: 'Haircut' }])`.
|
|
62
|
+
* Without a value the first option is the default.
|
|
63
|
+
*/
|
|
64
|
+
function select(options, value, fieldOptions = {}) {
|
|
65
|
+
const all = options.map((option) => typeof option === "string" ? { value: option } : option);
|
|
66
|
+
if (!all.length) throw new Error("select() needs at least one option");
|
|
67
|
+
return {
|
|
68
|
+
type: "select",
|
|
69
|
+
options: all,
|
|
70
|
+
default: value ?? all[0].value,
|
|
71
|
+
...fieldOptions
|
|
72
|
+
};
|
|
73
|
+
}
|
|
24
74
|
function link(value = {
|
|
25
75
|
label: "",
|
|
26
76
|
href: ""
|
|
@@ -49,6 +99,31 @@ function list(item, value = [], options = {}) {
|
|
|
49
99
|
...options
|
|
50
100
|
};
|
|
51
101
|
}
|
|
102
|
+
/** Like a nested object, with a label in the editor: `group({ show: toggle(), text: text() }, { label: 'Notice' })`. */
|
|
103
|
+
function group(fields, options = {}) {
|
|
104
|
+
return {
|
|
105
|
+
type: "group",
|
|
106
|
+
fields,
|
|
107
|
+
...options
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* How the page shows up in search results and when it's shared: its title, description and
|
|
112
|
+
* image, editable like any other field. `useCmsSeo(key)` on the page turns them into its
|
|
113
|
+
* `<title>` and meta tags; an empty one leaves the page's own.
|
|
114
|
+
*/
|
|
115
|
+
function seo(value = {}, options = {}) {
|
|
116
|
+
return {
|
|
117
|
+
type: "group",
|
|
118
|
+
fields: {
|
|
119
|
+
title: text(value.title),
|
|
120
|
+
description: text(value.description, { multiline: true }),
|
|
121
|
+
image: value.image ? image(value.image) : image(null)
|
|
122
|
+
},
|
|
123
|
+
seo: true,
|
|
124
|
+
...options
|
|
125
|
+
};
|
|
126
|
+
}
|
|
52
127
|
/**
|
|
53
128
|
* The content of one page, read with `useCms(key)`:
|
|
54
129
|
*
|
|
@@ -71,4 +146,43 @@ function defineCmsPage(key, fields, options = {}) {
|
|
|
71
146
|
function isCmsPage(value) {
|
|
72
147
|
return typeof value === "object" && value !== null && "__cmsPage" in value;
|
|
73
148
|
}
|
|
74
|
-
|
|
149
|
+
/** Names the items get besides their fields. */
|
|
150
|
+
const ITEM_KEYS = ["slug", "path"];
|
|
151
|
+
/**
|
|
152
|
+
* Many items of one kind, such as blog posts or events, each saved on its own and with a page of
|
|
153
|
+
* its own when the collection has a `path`. Read with `useCmsCollection(key)` and
|
|
154
|
+
* `useCmsItem(key, slug)`:
|
|
155
|
+
*
|
|
156
|
+
* ```ts
|
|
157
|
+
* // cms/posts.ts
|
|
158
|
+
* export default defineCmsCollection(
|
|
159
|
+
* 'posts',
|
|
160
|
+
* { title: text('', { required: true }), date: date(), body: richText() },
|
|
161
|
+
* { label: 'Blog', path: '/blog/[slug]', sort: '-date' },
|
|
162
|
+
* )
|
|
163
|
+
* ```
|
|
164
|
+
*/
|
|
165
|
+
function defineCmsCollection(key, fields, options = {}) {
|
|
166
|
+
for (const name of ITEM_KEYS) if (name in fields) throw new Error(`defineCmsCollection('${key}'): \`${name}\` is the item's own, name the field differently`);
|
|
167
|
+
if (key.includes("/")) throw new Error(`defineCmsCollection('${key}'): a collection key is one word, without \`/\``);
|
|
168
|
+
if (options.path !== void 0 && !options.path.includes("[slug]")) throw new Error(`defineCmsCollection('${key}'): path needs \`[slug]\`, like '/blog/[slug]'`);
|
|
169
|
+
const titleField = options.titleField ?? firstTextField(fields);
|
|
170
|
+
if (options.titleField !== void 0) {
|
|
171
|
+
const field = fields[options.titleField];
|
|
172
|
+
if (!field || field.type !== "text") throw new Error(`defineCmsCollection('${key}'): titleField \`${options.titleField}\` isn't a text() field`);
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
__cmsCollection: true,
|
|
176
|
+
key,
|
|
177
|
+
fields,
|
|
178
|
+
...options,
|
|
179
|
+
...titleField ? { titleField } : {}
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
function firstTextField(fields) {
|
|
183
|
+
return Object.entries(fields).find(([, field]) => field.type === "text")?.[0];
|
|
184
|
+
}
|
|
185
|
+
function isCmsCollection(value) {
|
|
186
|
+
return typeof value === "object" && value !== null && "__cmsCollection" in value;
|
|
187
|
+
}
|
|
188
|
+
export { date, defineCmsCollection, defineCmsPage, group, image, isCmsCollection, isCmsDate, isCmsPage, link, list, number, richText, select, seo, text, toggle };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { CmsFields, CmsImage } from "./schema.js";
|
|
2
|
+
/** A `seo()` field as the page gets it. */
|
|
3
|
+
export interface SeoValue {
|
|
4
|
+
title: string;
|
|
5
|
+
description: string;
|
|
6
|
+
image: CmsImage | null;
|
|
7
|
+
}
|
|
8
|
+
/** The name of the page's `seo()` field, if it has one. */
|
|
9
|
+
export declare function seoFieldName(fields: CmsFields | undefined): string | undefined;
|
|
10
|
+
/**
|
|
11
|
+
* The meta tags for `value`, for `useSeoMeta`. Empty is `undefined`, so the page's own title and
|
|
12
|
+
* description stay when nobody wrote one here.
|
|
13
|
+
*/
|
|
14
|
+
export declare function seoMeta(value: SeoValue | undefined, origin: string): {
|
|
15
|
+
title: string | undefined;
|
|
16
|
+
ogTitle: string | undefined;
|
|
17
|
+
description: string | undefined;
|
|
18
|
+
ogDescription: string | undefined;
|
|
19
|
+
ogImage: string | undefined;
|
|
20
|
+
ogImageAlt: string | undefined;
|
|
21
|
+
twitterCard: "summary_large_image" | undefined;
|
|
22
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { isField } from "./fields.js";
|
|
2
|
+
// src/runtime/seo.ts
|
|
3
|
+
/** The name of the page's `seo()` field, if it has one. */
|
|
4
|
+
function seoFieldName(fields) {
|
|
5
|
+
for (const [name, field] of Object.entries(fields ?? {})) if (isField(field) && field.type === "group" && field.seo) return name;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* The meta tags for `value`, for `useSeoMeta`. Empty is `undefined`, so the page's own title and
|
|
9
|
+
* description stay when nobody wrote one here.
|
|
10
|
+
*/
|
|
11
|
+
function seoMeta(value, origin) {
|
|
12
|
+
const title = value?.title.trim() || void 0;
|
|
13
|
+
const description = value?.description.trim() || void 0;
|
|
14
|
+
const image = value?.image ? absolute(value.image.src, origin) : void 0;
|
|
15
|
+
return {
|
|
16
|
+
title,
|
|
17
|
+
ogTitle: title,
|
|
18
|
+
description,
|
|
19
|
+
ogDescription: description,
|
|
20
|
+
ogImage: image,
|
|
21
|
+
ogImageAlt: image && value?.image?.alt || void 0,
|
|
22
|
+
twitterCard: image ? "summary_large_image" : void 0
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function absolute(src, origin) {
|
|
26
|
+
try {
|
|
27
|
+
const url = new URL(src, origin);
|
|
28
|
+
return /^https?:$/.test(url.protocol) ? url.href : void 0;
|
|
29
|
+
} catch {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export { seoFieldName, seoMeta };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { requireEditor } from "./access.js";
|
|
2
|
+
import { defineEventHandler } from "nuxt/server";
|
|
3
|
+
// src/runtime/server/access.get.ts
|
|
4
|
+
var access_get_default = defineEventHandler((event) => {
|
|
5
|
+
requireEditor(event);
|
|
6
|
+
return { editor: true };
|
|
7
|
+
});
|
|
8
|
+
export { access_get_default as default };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { useWervtUser } from "@wervt/nuxt/server";
|
|
2
1
|
import { createError, useRuntimeConfig } from "nuxt/server";
|
|
2
|
+
import { useWervtUser } from "@wervt/nuxt/server";
|
|
3
3
|
// src/runtime/server/access.ts
|
|
4
4
|
function requireEditor(event) {
|
|
5
5
|
const user = useWervtUser(event);
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { itemOf, itemPath, sortItems } from "../collections.js";
|
|
2
|
+
import { resolveValue } from "../fields.js";
|
|
3
|
+
import { collections } from "../pages.js";
|
|
4
|
+
import { serverImages } from "./images.js";
|
|
5
|
+
import { readEntriesUnder } from "./store.js";
|
|
6
|
+
import { createError, defineEventHandler, getRouterParam } from "nuxt/server";
|
|
7
|
+
// src/runtime/server/collection.get.ts
|
|
8
|
+
var collection_get_default = defineEventHandler(async (event) => {
|
|
9
|
+
const collection = collections.get(getRouterParam(event, "key") ?? "");
|
|
10
|
+
if (!collection) throw createError({
|
|
11
|
+
status: 404,
|
|
12
|
+
message: "No such collection"
|
|
13
|
+
});
|
|
14
|
+
const items = (await readEntriesUnder(`${collection.key}/`)).flatMap((entry) => {
|
|
15
|
+
const item = itemOf(collections, entry.key);
|
|
16
|
+
if (!item) return [];
|
|
17
|
+
const path = itemPath(collection, item.slug);
|
|
18
|
+
return [{
|
|
19
|
+
key: entry.key,
|
|
20
|
+
slug: item.slug,
|
|
21
|
+
...path ? { path } : {},
|
|
22
|
+
value: resolveValue(collection.fields, entry.value, serverImages),
|
|
23
|
+
updatedAt: entry.updatedAt
|
|
24
|
+
}];
|
|
25
|
+
});
|
|
26
|
+
return { items: sortItems(collection, items) };
|
|
27
|
+
});
|
|
28
|
+
export { collection_get_default as default };
|
|
@@ -1,2 +1,5 @@
|
|
|
1
|
+
import { MediaStore } from "./media.js";
|
|
1
2
|
/** Writes the image and returns the path the app serves it at. */
|
|
2
|
-
export declare function saveDevImage(publicDir: string, data: Uint8Array, extension: string): Promise<string>;
|
|
3
|
+
export declare function saveDevImage(publicDir: string, data: Uint8Array, extension: string): Promise<string>;
|
|
4
|
+
/** The uploads in `public/cms/`, as the library lists them. */
|
|
5
|
+
export declare function devMedia(publicDir: string): MediaStore;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { mkdir, writeFile } from "node:fs/promises";
|
|
3
|
+
import { mkdir, readdir, stat, unlink, writeFile } from "node:fs/promises";
|
|
4
4
|
// src/runtime/server/dev-images.ts
|
|
5
5
|
/** Writes the image and returns the path the app serves it at. */
|
|
6
6
|
async function saveDevImage(publicDir, data, extension) {
|
|
@@ -9,4 +9,30 @@ async function saveDevImage(publicDir, data, extension) {
|
|
|
9
9
|
await writeFile(join(publicDir, "cms", name), data);
|
|
10
10
|
return `/cms/${name}`;
|
|
11
11
|
}
|
|
12
|
-
|
|
12
|
+
const DEV_NAME = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.(?:jpg|png|gif|webp|avif)$/;
|
|
13
|
+
/** The uploads in `public/cms/`, as the library lists them. */
|
|
14
|
+
function devMedia(publicDir) {
|
|
15
|
+
const dir = join(publicDir, "cms");
|
|
16
|
+
return {
|
|
17
|
+
async list() {
|
|
18
|
+
const names = await readdir(dir).catch((error) => {
|
|
19
|
+
if (error.code === "ENOENT") return [];
|
|
20
|
+
throw error;
|
|
21
|
+
});
|
|
22
|
+
return await Promise.all(names.filter((name) => DEV_NAME.test(name)).map(async (name) => {
|
|
23
|
+
const info = await stat(join(dir, name));
|
|
24
|
+
return {
|
|
25
|
+
name,
|
|
26
|
+
value: { src: `/cms/${name}` },
|
|
27
|
+
size: info.size,
|
|
28
|
+
uploadedAt: info.mtime.toISOString()
|
|
29
|
+
};
|
|
30
|
+
}));
|
|
31
|
+
},
|
|
32
|
+
async remove(name) {
|
|
33
|
+
if (!DEV_NAME.test(name)) throw new Error(`Not an upload: ${name}`);
|
|
34
|
+
await unlink(join(dir, name));
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
export { devMedia, saveDevImage };
|
|
@@ -14,6 +14,45 @@ export type EntriesFile = Record<string, {
|
|
|
14
14
|
* one changed last. On a tie the database wins, since that is the edit made on the live site.
|
|
15
15
|
*/
|
|
16
16
|
export declare function newerEntry(file: CmsEntry | undefined, db: CmsEntry | undefined): CmsEntry | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* What a deleted item is saved as. Not a missing row: the app's `cms/entries.json` and the
|
|
19
|
+
* database each win where they are newer, so a row that's simply gone would let the file's older
|
|
20
|
+
* copy back, and a key dropped from the file would leave the database's in place.
|
|
21
|
+
*/
|
|
22
|
+
export declare const DELETED: {
|
|
23
|
+
readonly $deleted: true;
|
|
24
|
+
};
|
|
25
|
+
export declare const isDeleted: (value: Record<string, unknown>) => boolean;
|
|
26
|
+
/** The entry unless it's deleted. */
|
|
27
|
+
export declare const live: (entry: CmsEntry | undefined) => CmsEntry | undefined;
|
|
28
|
+
/** The same moment, however Postgres and JSON spell it. No entry (`null`) only matches no entry. */
|
|
29
|
+
export declare function sameInstant(a: string | null | undefined, b: string | null | undefined): boolean;
|
|
30
|
+
/** One saved state of an entry; `by` is who saved it, when the store knows. */
|
|
31
|
+
export interface CmsVersion {
|
|
32
|
+
updatedAt: string;
|
|
33
|
+
value: Record<string, unknown>;
|
|
34
|
+
by: string | null;
|
|
35
|
+
}
|
|
36
|
+
/** Versions kept per entry; older ones are dropped as new ones are saved. */
|
|
37
|
+
export declare const KEPT_VERSIONS = 50;
|
|
38
|
+
/**
|
|
39
|
+
* The versions the stores know of an entry, newest first and each once. The current entry may
|
|
40
|
+
* not be in the history: the app's file is edited by hand and deployed, and entries saved before
|
|
41
|
+
* the history existed have none.
|
|
42
|
+
*/
|
|
43
|
+
export declare function mergeVersions(candidates: ((Omit<CmsVersion, 'by'> & {
|
|
44
|
+
by?: string | null;
|
|
45
|
+
}) | undefined)[]): CmsVersion[];
|
|
46
|
+
/**
|
|
47
|
+
* The top-level fields a version changed from the one before it, so the editor can say what each
|
|
48
|
+
* save was about; `null` for the oldest, which has nothing to compare with.
|
|
49
|
+
*/
|
|
50
|
+
export declare function changedFields(value: Record<string, unknown>, before: Record<string, unknown> | undefined): string[] | null;
|
|
51
|
+
/** An edit made on a version that is no longer the current one; `current` is what is there now. */
|
|
52
|
+
export declare class EntryConflict extends Error {
|
|
53
|
+
readonly current: CmsEntry | undefined;
|
|
54
|
+
constructor(current: CmsEntry | undefined);
|
|
55
|
+
}
|
|
17
56
|
/**
|
|
18
57
|
* Gives entries without `updatedAt` the time `now`. An agent editing the file drops the field
|
|
19
58
|
* instead of keeping a clock, so a missing time means "just changed".
|
|
@@ -22,6 +61,20 @@ export declare function stampEntries(file: EntriesFile, now: Date): {
|
|
|
22
61
|
file: EntriesFile;
|
|
23
62
|
changed: boolean;
|
|
24
63
|
};
|
|
64
|
+
/**
|
|
65
|
+
* The time a save is stamped with. `updatedAt` is also the version a save is checked against, so
|
|
66
|
+
* it has to move on even when two saves land in the same millisecond.
|
|
67
|
+
*/
|
|
68
|
+
export declare function nextVersion(previous: string | undefined, now: Date): string;
|
|
69
|
+
/** The file's entries whose key starts with `prefix`. */
|
|
70
|
+
export declare function fileEntriesUnder(file: EntriesFile, prefix: string): CmsEntry[];
|
|
71
|
+
/** Each key's newer entry, as `readEntry` picks it for one, deleted ones left out. */
|
|
72
|
+
export declare function mergeEntries(file: CmsEntry[], db: CmsEntry[]): CmsEntry[];
|
|
25
73
|
export declare function fileEntry(file: EntriesFile, key: string): CmsEntry | undefined;
|
|
74
|
+
/**
|
|
75
|
+
* The version an edit was made on: `If-Match: "<updatedAt>"`, or `If-None-Match: *` for an entry
|
|
76
|
+
* never saved. Without either the edit simply wins, as for scripts and agents.
|
|
77
|
+
*/
|
|
78
|
+
export declare function expectedVersion(headers: Headers): string | null | undefined;
|
|
26
79
|
/** Lowercase words joined by `-`, `_` or `/`, so a key is also safe as a property name. */
|
|
27
80
|
export declare function isEntryKey(key: string | undefined): key is string;
|
|
@@ -8,6 +8,61 @@ function newerEntry(file, db) {
|
|
|
8
8
|
return Date.parse(file.updatedAt) > Date.parse(db.updatedAt) ? file : db;
|
|
9
9
|
}
|
|
10
10
|
/**
|
|
11
|
+
* What a deleted item is saved as. Not a missing row: the app's `cms/entries.json` and the
|
|
12
|
+
* database each win where they are newer, so a row that's simply gone would let the file's older
|
|
13
|
+
* copy back, and a key dropped from the file would leave the database's in place.
|
|
14
|
+
*/
|
|
15
|
+
const DELETED = { $deleted: true };
|
|
16
|
+
const isDeleted = (value) => value.$deleted === true;
|
|
17
|
+
/** The entry unless it's deleted. */
|
|
18
|
+
const live = (entry) => entry && !isDeleted(entry.value) ? entry : void 0;
|
|
19
|
+
/** The same moment, however Postgres and JSON spell it. No entry (`null`) only matches no entry. */
|
|
20
|
+
function sameInstant(a, b) {
|
|
21
|
+
if (!a || !b) return !a && !b;
|
|
22
|
+
return Date.parse(a) === Date.parse(b);
|
|
23
|
+
}
|
|
24
|
+
/** Versions kept per entry; older ones are dropped as new ones are saved. */
|
|
25
|
+
const KEPT_VERSIONS = 50;
|
|
26
|
+
/**
|
|
27
|
+
* The versions the stores know of an entry, newest first and each once. The current entry may
|
|
28
|
+
* not be in the history: the app's file is edited by hand and deployed, and entries saved before
|
|
29
|
+
* the history existed have none.
|
|
30
|
+
*/
|
|
31
|
+
function mergeVersions(candidates) {
|
|
32
|
+
const byInstant = /* @__PURE__ */ new Map();
|
|
33
|
+
for (const candidate of candidates) {
|
|
34
|
+
if (!candidate) continue;
|
|
35
|
+
const at = Date.parse(candidate.updatedAt);
|
|
36
|
+
const known = byInstant.get(at);
|
|
37
|
+
if (known?.by) continue;
|
|
38
|
+
byInstant.set(at, {
|
|
39
|
+
updatedAt: new Date(at).toISOString(),
|
|
40
|
+
value: candidate.value,
|
|
41
|
+
by: candidate.by ?? known?.by ?? null
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
return [...byInstant.entries()].sort(([a], [b]) => b - a).slice(0, 50).map(([, version]) => version);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The top-level fields a version changed from the one before it, so the editor can say what each
|
|
48
|
+
* save was about; `null` for the oldest, which has nothing to compare with.
|
|
49
|
+
*/
|
|
50
|
+
function changedFields(value, before) {
|
|
51
|
+
if (!before) return null;
|
|
52
|
+
return [.../* @__PURE__ */ new Set([...Object.keys(value), ...Object.keys(before)])].filter((name) => canonical(value[name]) !== canonical(before[name]));
|
|
53
|
+
}
|
|
54
|
+
function canonical(value) {
|
|
55
|
+
return JSON.stringify(value, (_, v) => v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : v);
|
|
56
|
+
}
|
|
57
|
+
/** An edit made on a version that is no longer the current one; `current` is what is there now. */
|
|
58
|
+
var EntryConflict = class extends Error {
|
|
59
|
+
current;
|
|
60
|
+
constructor(current) {
|
|
61
|
+
super("The entry was changed since it was loaded");
|
|
62
|
+
this.current = current;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
11
66
|
* Gives entries without `updatedAt` the time `now`. An agent editing the file drops the field
|
|
12
67
|
* instead of keeping a clock, so a missing time means "just changed".
|
|
13
68
|
*/
|
|
@@ -27,6 +82,24 @@ function stampEntries(file, now) {
|
|
|
27
82
|
changed
|
|
28
83
|
};
|
|
29
84
|
}
|
|
85
|
+
/**
|
|
86
|
+
* The time a save is stamped with. `updatedAt` is also the version a save is checked against, so
|
|
87
|
+
* it has to move on even when two saves land in the same millisecond.
|
|
88
|
+
*/
|
|
89
|
+
function nextVersion(previous, now) {
|
|
90
|
+
const after = previous ? Date.parse(previous) + 1 : Number.NEGATIVE_INFINITY;
|
|
91
|
+
return new Date(Math.max(now.getTime(), after)).toISOString();
|
|
92
|
+
}
|
|
93
|
+
/** The file's entries whose key starts with `prefix`. */
|
|
94
|
+
function fileEntriesUnder(file, prefix) {
|
|
95
|
+
return Object.keys(file).filter((key) => key.startsWith(prefix)).map((key) => fileEntry(file, key)).filter((entry) => entry !== void 0);
|
|
96
|
+
}
|
|
97
|
+
/** Each key's newer entry, as `readEntry` picks it for one, deleted ones left out. */
|
|
98
|
+
function mergeEntries(file, db) {
|
|
99
|
+
const byKey = new Map(file.map((entry) => [entry.key, entry]));
|
|
100
|
+
for (const entry of db) byKey.set(entry.key, newerEntry(byKey.get(entry.key), entry));
|
|
101
|
+
return [...byKey.values()].filter((entry) => live(entry));
|
|
102
|
+
}
|
|
30
103
|
function fileEntry(file, key) {
|
|
31
104
|
const entry = Object.hasOwn(file, key) ? file[key] : void 0;
|
|
32
105
|
if (!entry?.updatedAt) return void 0;
|
|
@@ -36,9 +109,18 @@ function fileEntry(file, key) {
|
|
|
36
109
|
updatedAt: entry.updatedAt
|
|
37
110
|
};
|
|
38
111
|
}
|
|
112
|
+
/**
|
|
113
|
+
* The version an edit was made on: `If-Match: "<updatedAt>"`, or `If-None-Match: *` for an entry
|
|
114
|
+
* never saved. Without either the edit simply wins, as for scripts and agents.
|
|
115
|
+
*/
|
|
116
|
+
function expectedVersion(headers) {
|
|
117
|
+
const match = headers.get("if-match")?.trim();
|
|
118
|
+
if (match) return match.replace(/^"|"$/g, "");
|
|
119
|
+
if (headers.get("if-none-match")?.trim() === "*") return null;
|
|
120
|
+
}
|
|
39
121
|
const KEY = /^[a-z0-9][a-z0-9_-]*(?:\/[a-z0-9][a-z0-9_-]*)*$/;
|
|
40
122
|
/** Lowercase words joined by `-`, `_` or `/`, so a key is also safe as a property name. */
|
|
41
123
|
function isEntryKey(key) {
|
|
42
124
|
return key !== void 0 && key.length <= 200 && KEY.test(key);
|
|
43
125
|
}
|
|
44
|
-
export { fileEntry, isEntryKey, newerEntry, stampEntries };
|
|
126
|
+
export { DELETED, EntryConflict, KEPT_VERSIONS, changedFields, expectedVersion, fileEntriesUnder, fileEntry, isDeleted, isEntryKey, live, mergeEntries, mergeVersions, newerEntry, nextVersion, sameInstant, stampEntries };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { DELETED, EntryConflict, expectedVersion, isEntryKey, live } from "./entries.js";
|
|
2
|
+
import { itemOf } from "../collections.js";
|
|
3
|
+
import { collections } from "../pages.js";
|
|
4
|
+
import { requireEditor } from "./access.js";
|
|
5
|
+
import { readEntry, writeEntry } from "./store.js";
|
|
6
|
+
import { createError, defineEventHandler, getRouterParam } from "nuxt/server";
|
|
7
|
+
// src/runtime/server/entry.delete.ts
|
|
8
|
+
var entry_delete_default = defineEventHandler(async (event) => {
|
|
9
|
+
const user = requireEditor(event);
|
|
10
|
+
const key = getRouterParam(event, "key");
|
|
11
|
+
if (!isEntryKey(key) || !itemOf(collections, key)) throw createError({
|
|
12
|
+
status: 400,
|
|
13
|
+
message: "Only collection items can be deleted"
|
|
14
|
+
});
|
|
15
|
+
if (!live(await readEntry(key))) throw createError({
|
|
16
|
+
status: 404,
|
|
17
|
+
message: "No such item"
|
|
18
|
+
});
|
|
19
|
+
try {
|
|
20
|
+
await writeEntry(key, { ...DELETED }, expectedVersion(event.req.headers), user.email);
|
|
21
|
+
return { ok: true };
|
|
22
|
+
} catch (error) {
|
|
23
|
+
if (!(error instanceof EntryConflict)) throw error;
|
|
24
|
+
throw createError({
|
|
25
|
+
status: 412,
|
|
26
|
+
message: "Someone else saved this item since you opened it",
|
|
27
|
+
data: { updatedAt: error.current?.updatedAt ?? null }
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
export { entry_delete_default as default };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { isEntryKey } from "./entries.js";
|
|
1
|
+
import { isEntryKey, live } from "./entries.js";
|
|
2
2
|
import { resolveValue } from "../fields.js";
|
|
3
|
-
import {
|
|
3
|
+
import { fieldsOf } from "../pages.js";
|
|
4
4
|
import { serverImages } from "./images.js";
|
|
5
5
|
import { readEntry } from "./store.js";
|
|
6
6
|
import { createError, defineEventHandler, getRouterParam } from "nuxt/server";
|
|
@@ -11,12 +11,12 @@ var entry_get_default = defineEventHandler(async (event) => {
|
|
|
11
11
|
status: 400,
|
|
12
12
|
message: "Invalid key"
|
|
13
13
|
});
|
|
14
|
-
const entry = await readEntry(key);
|
|
15
|
-
const
|
|
16
|
-
if (!
|
|
14
|
+
const entry = live(await readEntry(key));
|
|
15
|
+
const fields = fieldsOf(key);
|
|
16
|
+
if (!fields) return entry ?? null;
|
|
17
17
|
return {
|
|
18
18
|
key,
|
|
19
|
-
value: resolveValue(
|
|
19
|
+
value: resolveValue(fields, entry?.value, serverImages),
|
|
20
20
|
updatedAt: entry?.updatedAt ?? null
|
|
21
21
|
};
|
|
22
22
|
});
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { isEntryKey } from "./entries.js";
|
|
1
|
+
import { EntryConflict, expectedVersion, isEntryKey } from "./entries.js";
|
|
2
2
|
import { InvalidValue, normalizeValue } from "../fields.js";
|
|
3
|
-
import {
|
|
3
|
+
import { fieldsOf, strayUnderCollection } from "../pages.js";
|
|
4
4
|
import { requireEditor } from "./access.js";
|
|
5
5
|
import { writeEntry } from "./store.js";
|
|
6
6
|
import { createError, defineEventHandler, getRouterParam, readBody } from "nuxt/server";
|
|
7
7
|
// src/runtime/server/entry.put.ts
|
|
8
8
|
var entry_put_default = defineEventHandler(async (event) => {
|
|
9
|
-
requireEditor(event);
|
|
9
|
+
const user = requireEditor(event);
|
|
10
10
|
const key = getRouterParam(event, "key");
|
|
11
|
-
if (!isEntryKey(key)) throw createError({
|
|
11
|
+
if (!isEntryKey(key) || strayUnderCollection(key)) throw createError({
|
|
12
12
|
status: 400,
|
|
13
13
|
message: "Invalid key"
|
|
14
14
|
});
|
|
@@ -17,10 +17,10 @@ var entry_put_default = defineEventHandler(async (event) => {
|
|
|
17
17
|
status: 400,
|
|
18
18
|
message: "Expected an object"
|
|
19
19
|
});
|
|
20
|
-
const
|
|
20
|
+
const fields = fieldsOf(key);
|
|
21
21
|
let value = body;
|
|
22
22
|
try {
|
|
23
|
-
if (
|
|
23
|
+
if (fields) value = normalizeValue(fields, body);
|
|
24
24
|
} catch (error) {
|
|
25
25
|
if (error instanceof InvalidValue) throw createError({
|
|
26
26
|
status: 400,
|
|
@@ -28,7 +28,19 @@ var entry_put_default = defineEventHandler(async (event) => {
|
|
|
28
28
|
});
|
|
29
29
|
throw error;
|
|
30
30
|
}
|
|
31
|
-
|
|
32
|
-
|
|
31
|
+
try {
|
|
32
|
+
const expected = expectedVersion(event.req.headers);
|
|
33
|
+
return {
|
|
34
|
+
ok: true,
|
|
35
|
+
updatedAt: await writeEntry(key, value, expected, user.email)
|
|
36
|
+
};
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (!(error instanceof EntryConflict)) throw error;
|
|
39
|
+
throw createError({
|
|
40
|
+
status: 412,
|
|
41
|
+
message: "Someone else saved this page since you opened it",
|
|
42
|
+
data: { updatedAt: error.current?.updatedAt ?? null }
|
|
43
|
+
});
|
|
44
|
+
}
|
|
33
45
|
});
|
|
34
46
|
export { entry_put_default as default };
|
|
@@ -1,3 +1,14 @@
|
|
|
1
|
-
import { CmsEntry } from "./entries.js";
|
|
2
|
-
export
|
|
3
|
-
|
|
1
|
+
import { CmsEntry, CmsVersion } from "./entries.js";
|
|
2
|
+
export interface FileStore {
|
|
3
|
+
/** `cms/entries.json`. */
|
|
4
|
+
entries: string;
|
|
5
|
+
/** Where earlier versions go; none are kept without it. */
|
|
6
|
+
history?: string;
|
|
7
|
+
}
|
|
8
|
+
export declare function readFileEntry(store: FileStore, key: string): Promise<CmsEntry | undefined>;
|
|
9
|
+
/** `expected`: see `writeEntry`. `by`: who saves, for the history. */
|
|
10
|
+
export declare function writeFileEntry(store: FileStore, key: string, value: Record<string, unknown>, expected?: string | null, by?: string | null): Promise<string>;
|
|
11
|
+
/** The entries whose key starts with `prefix`, deleted ones left out. */
|
|
12
|
+
export declare function readFileEntriesUnder(store: FileStore, prefix: string): Promise<CmsEntry[]>;
|
|
13
|
+
/** The entry's versions, newest first, the current one included. */
|
|
14
|
+
export declare function readFileVersions(store: FileStore, key: string): Promise<CmsVersion[]>;
|