@wervt/cms 0.0.5 → 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.
Files changed (72) hide show
  1. package/README.md +177 -18
  2. package/dist/editor/assets/Button-DrsXdow7.js +6 -0
  3. package/dist/editor/assets/RichTextInput-BrNTSUXL.js +271 -0
  4. package/dist/editor/assets/Toast-DsP3Sdxg.js +13 -0
  5. package/dist/editor/assets/index-CWQLsBfF.js +16 -0
  6. package/dist/editor/assets/index-esGfkiTV.css +2 -0
  7. package/dist/editor/index.html +3 -3
  8. package/dist/editor-theme.d.ts +3 -0
  9. package/dist/editor-theme.js +18 -1
  10. package/dist/module.d.ts +18 -1
  11. package/dist/module.js +95 -7
  12. package/dist/routes.js +16 -0
  13. package/dist/runtime/app/edit-button.d.ts +7 -0
  14. package/dist/runtime/app/edit-button.js +56 -0
  15. package/dist/runtime/app/preview.client.js +12 -5
  16. package/dist/runtime/app/useCmsCollection.d.ts +24 -0
  17. package/dist/runtime/app/useCmsCollection.js +74 -0
  18. package/dist/runtime/app/useCmsSeo.d.ts +7 -0
  19. package/dist/runtime/app/useCmsSeo.js +31 -0
  20. package/dist/runtime/collections.d.ts +25 -0
  21. package/dist/runtime/collections.js +81 -0
  22. package/dist/runtime/editor-link.d.ts +19 -0
  23. package/dist/runtime/editor-link.js +31 -0
  24. package/dist/runtime/fields.d.ts +33 -1
  25. package/dist/runtime/fields.js +143 -7
  26. package/dist/runtime/pages.d.ts +11 -2
  27. package/dist/runtime/pages.js +37 -7
  28. package/dist/runtime/preview.d.ts +5 -2
  29. package/dist/runtime/preview.js +2 -2
  30. package/dist/runtime/schema.d.ts +187 -13
  31. package/dist/runtime/schema.js +115 -1
  32. package/dist/runtime/seo.d.ts +22 -0
  33. package/dist/runtime/seo.js +33 -0
  34. package/dist/runtime/server/access.get.d.ts +4 -0
  35. package/dist/runtime/server/access.get.js +8 -0
  36. package/dist/runtime/server/access.js +1 -1
  37. package/dist/runtime/server/collection.get.d.ts +12 -0
  38. package/dist/runtime/server/collection.get.js +28 -0
  39. package/dist/runtime/server/dev-images.d.ts +4 -1
  40. package/dist/runtime/server/dev-images.js +28 -2
  41. package/dist/runtime/server/entries.d.ts +53 -0
  42. package/dist/runtime/server/entries.js +83 -1
  43. package/dist/runtime/server/entry.delete.d.ts +4 -0
  44. package/dist/runtime/server/entry.delete.js +31 -0
  45. package/dist/runtime/server/entry.get.js +6 -6
  46. package/dist/runtime/server/entry.put.d.ts +1 -0
  47. package/dist/runtime/server/entry.put.js +20 -8
  48. package/dist/runtime/server/file-store.d.ts +14 -3
  49. package/dist/runtime/server/file-store.js +44 -9
  50. package/dist/runtime/server/image.delete.d.ts +4 -0
  51. package/dist/runtime/server/image.delete.js +24 -0
  52. package/dist/runtime/server/images.get.d.ts +5 -0
  53. package/dist/runtime/server/images.get.js +11 -0
  54. package/dist/runtime/server/library.d.ts +14 -0
  55. package/dist/runtime/server/library.js +72 -0
  56. package/dist/runtime/server/links.get.d.ts +7 -0
  57. package/dist/runtime/server/links.get.js +35 -0
  58. package/dist/runtime/server/media.d.ts +74 -0
  59. package/dist/runtime/server/media.js +88 -0
  60. package/dist/runtime/server/schema.get.d.ts +8 -0
  61. package/dist/runtime/server/schema.get.js +17 -7
  62. package/dist/runtime/server/store.d.ts +11 -2
  63. package/dist/runtime/server/store.js +110 -20
  64. package/dist/runtime/server/upload.post.js +3 -2
  65. package/dist/runtime/server/versions.get.d.ts +20 -0
  66. package/dist/runtime/server/versions.get.js +36 -0
  67. package/package.json +3 -2
  68. package/dist/editor/assets/Button-Dai6Ph2c.js +0 -6
  69. package/dist/editor/assets/RichTextInput-CdL9ZFoP.js +0 -271
  70. package/dist/editor/assets/Toast-BaUcosq6.js +0 -13
  71. package/dist/editor/assets/index-CP6dGIyl.css +0 -2
  72. package/dist/editor/assets/index-Du-lvx2V.js +0 -16
@@ -1,4 +1,4 @@
1
- import { fileEntry, stampEntries } from "./entries.js";
1
+ import { EntryConflict, fileEntriesUnder, fileEntry, live, mergeVersions, nextVersion, sameInstant, stampEntries } from "./entries.js";
2
2
  import { dirname } from "node:path";
3
3
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
4
4
  // src/runtime/server/file-store.ts
@@ -23,21 +23,56 @@ async function save(path, file) {
23
23
  await writeFile(temporary, `${JSON.stringify(sorted, null, 2)}\n`);
24
24
  await rename(temporary, path);
25
25
  }
26
- function readFileEntry(path, key) {
26
+ function readFileEntry(store, key) {
27
27
  return serialized(async () => {
28
- const { file, changed } = stampEntries(await load(path), /* @__PURE__ */ new Date());
29
- if (changed) await save(path, file);
28
+ const { file, changed } = stampEntries(await load(store.entries), /* @__PURE__ */ new Date());
29
+ if (changed) await save(store.entries, file);
30
30
  return fileEntry(file, key);
31
31
  });
32
32
  }
33
- function writeFileEntry(path, key, value) {
33
+ /** `expected`: see `writeEntry`. `by`: who saves, for the history. */
34
+ function writeFileEntry(store, key, value, expected, by = null) {
34
35
  return serialized(async () => {
35
- const file = await load(path);
36
+ const { file } = stampEntries(await load(store.entries), /* @__PURE__ */ new Date());
37
+ const current = fileEntry(file, key);
38
+ if (expected !== void 0 && !sameInstant(live(current)?.updatedAt, expected)) throw new EntryConflict(live(current));
39
+ const updatedAt = nextVersion(current?.updatedAt, /* @__PURE__ */ new Date());
36
40
  file[key] = {
37
41
  value,
38
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
42
+ updatedAt
39
43
  };
40
- await save(path, file);
44
+ await save(store.entries, file);
45
+ if (store.history) {
46
+ const history = await load(store.history);
47
+ history[key] = mergeVersions([
48
+ {
49
+ updatedAt,
50
+ value,
51
+ by
52
+ },
53
+ current,
54
+ ...history[key] ?? []
55
+ ]);
56
+ await save(store.history, history);
57
+ }
58
+ return updatedAt;
41
59
  });
42
60
  }
43
- export { readFileEntry, writeFileEntry };
61
+ /** The entries whose key starts with `prefix`, deleted ones left out. */
62
+ function readFileEntriesUnder(store, prefix) {
63
+ return serialized(async () => {
64
+ const { file, changed } = stampEntries(await load(store.entries), /* @__PURE__ */ new Date());
65
+ if (changed) await save(store.entries, file);
66
+ return fileEntriesUnder(file, prefix).filter((entry) => live(entry));
67
+ });
68
+ }
69
+ /** The entry's versions, newest first, the current one included. */
70
+ function readFileVersions(store, key) {
71
+ return serialized(async () => {
72
+ const { file, changed } = stampEntries(await load(store.entries), /* @__PURE__ */ new Date());
73
+ if (changed) await save(store.entries, file);
74
+ const history = store.history ? await load(store.history) : {};
75
+ return mergeVersions([fileEntry(file, key), ...history[key] ?? []]);
76
+ });
77
+ }
78
+ export { readFileEntriesUnder, readFileEntry, readFileVersions, writeFileEntry };
@@ -0,0 +1,4 @@
1
+ declare const _default: import("nuxt/server").EventHandler<Promise<{
2
+ ok: boolean;
3
+ }>>;
4
+ export { _default as default };
@@ -0,0 +1,24 @@
1
+ import { requireEditor } from "./access.js";
2
+ import { ImageInUse, removeImage } from "./media.js";
3
+ import { mediaStore, savedUses } from "./library.js";
4
+ import { createError, defineEventHandler, getRouterParam } from "nuxt/server";
5
+ // src/runtime/server/image.delete.ts
6
+ var image_delete_default = defineEventHandler(async (event) => {
7
+ requireEditor(event);
8
+ const name = getRouterParam(event, "name") ?? "";
9
+ try {
10
+ if (!await removeImage(await mediaStore(), name, await savedUses())) throw createError({
11
+ status: 404,
12
+ message: "No such image"
13
+ });
14
+ } catch (error) {
15
+ if (!(error instanceof ImageInUse)) throw error;
16
+ throw createError({
17
+ status: 409,
18
+ message: "The image is still used",
19
+ data: { uses: error.uses }
20
+ });
21
+ }
22
+ return { ok: true };
23
+ });
24
+ export { image_delete_default as default };
@@ -0,0 +1,5 @@
1
+ import { LibraryImage } from "./media.js";
2
+ declare const _default: import("nuxt/server").EventHandler<Promise<{
3
+ images: LibraryImage[];
4
+ }>>;
5
+ export { _default as default };
@@ -0,0 +1,11 @@
1
+ import { requireEditor } from "./access.js";
2
+ import { buildLibrary } from "./media.js";
3
+ import { mediaStore, savedUses, showStored } from "./library.js";
4
+ import { defineEventHandler } from "nuxt/server";
5
+ // src/runtime/server/images.get.ts
6
+ var images_get_default = defineEventHandler(async (event) => {
7
+ requireEditor(event);
8
+ const [files, uses] = await Promise.all([(await mediaStore()).list(), savedUses()]);
9
+ return { images: buildLibrary(files, uses, showStored) };
10
+ });
11
+ export { images_get_default as default };
@@ -0,0 +1,14 @@
1
+ import { CmsImage, StoredImage } from "../schema.js";
2
+ import { MediaStore, MediaUse } from "./media.js";
3
+ /** The uploads as `upload.post` stores them: in `public/cms/` under `nuxt dev`, else the bucket. */
4
+ export declare function mediaStore(): Promise<MediaStore>;
5
+ /**
6
+ * Where saved content uses each image. A page never saved shows its defaults, so those count too.
7
+ * Older versions don't: restoring one after its image was deleted shows a broken image
8
+ * until another is chosen.
9
+ */
10
+ export declare function savedUses(): Promise<Map<string, MediaUse[]>>;
11
+ export declare function showStored(value: StoredImage): {
12
+ image: CmsImage;
13
+ thumb: string;
14
+ } | undefined;
@@ -0,0 +1,72 @@
1
+ import { itemOf, itemTitle } from "../collections.js";
2
+ import { resolveValue, staticImages } from "../fields.js";
3
+ import { collections, pages } from "../pages.js";
4
+ import { serverImages } from "./images.js";
5
+ import { readEntriesUnder } from "./store.js";
6
+ import { usesOf } from "./media.js";
7
+ import { imageUrl } from "@wervt/nuxt/server";
8
+ import { publicDir } from "#wervt-cms/entries";
9
+ import { useFileStorage } from "#imports";
10
+ // src/runtime/server/library.ts
11
+ /** The uploads as `upload.post` stores them: in `public/cms/` under `nuxt dev`, else the bucket. */
12
+ async function mediaStore() {
13
+ if (import.meta.dev && publicDir) {
14
+ const { devMedia } = await import("./dev-images.js");
15
+ return devMedia(publicDir);
16
+ }
17
+ const storage = useFileStorage();
18
+ return {
19
+ async list() {
20
+ const files = [];
21
+ for await (const file of storage.listAll("cms")) files.push({
22
+ name: file.id,
23
+ value: { id: file.id },
24
+ ...typeof file.customMetadata.fileName === "string" ? { fileName: file.customMetadata.fileName } : {},
25
+ size: file.size,
26
+ uploadedAt: new Date(file.uploadedAt).toISOString()
27
+ });
28
+ return files;
29
+ },
30
+ remove: (name) => storage.remove({
31
+ group: "cms",
32
+ id: name
33
+ })
34
+ };
35
+ }
36
+ /**
37
+ * Where saved content uses each image. A page never saved shows its defaults, so those count too.
38
+ * Older versions don't: restoring one after its image was deleted shows a broken image
39
+ * until another is chosen.
40
+ */
41
+ async function savedUses() {
42
+ const entries = await readEntriesUnder("");
43
+ const saved = new Set(entries.map((entry) => entry.key));
44
+ const contents = entries.map((entry) => {
45
+ const item = itemOf(collections, entry.key);
46
+ const title = item ? itemTitle(item.collection, item.slug, entry.value) : pages.get(entry.key)?.label ?? entry.key;
47
+ return {
48
+ key: entry.key,
49
+ title,
50
+ value: entry.value
51
+ };
52
+ });
53
+ for (const page of pages.values()) if (!saved.has(page.key)) contents.push({
54
+ key: page.key,
55
+ title: page.label ?? page.key,
56
+ value: resolveValue(page.fields, void 0, staticImages)
57
+ });
58
+ return usesOf(contents);
59
+ }
60
+ const THUMB_WIDTH = 640;
61
+ function showStored(value) {
62
+ const image = serverImages(value);
63
+ if (!image) return void 0;
64
+ return {
65
+ image,
66
+ thumb: "id" in value ? imageUrl({
67
+ group: "cms",
68
+ id: value.id
69
+ }, { width: THUMB_WIDTH }) : image.src
70
+ };
71
+ }
72
+ export { mediaStore, savedUses, showStored };
@@ -0,0 +1,7 @@
1
+ declare const _default: import("nuxt/server").EventHandler<Promise<{
2
+ pages: {
3
+ path: string;
4
+ label?: string | undefined;
5
+ }[];
6
+ }>>;
7
+ export { _default as default };
@@ -0,0 +1,35 @@
1
+ import { itemOf, itemPath, itemTitle } from "../collections.js";
2
+ import { collections, pages } from "../pages.js";
3
+ import { requireEditor } from "./access.js";
4
+ import { readEntriesUnder } from "./store.js";
5
+ import { defineEventHandler } from "nuxt/server";
6
+ import { file, routes } from "#wervt-cms/routes";
7
+ // src/runtime/server/links.get.ts
8
+ var links_get_default = defineEventHandler(async (event) => {
9
+ requireEditor(event);
10
+ const paths = file ? await readDevRoutes(file) : routes;
11
+ const labels = /* @__PURE__ */ new Map();
12
+ for (const page of pages.values()) if (page.path) labels.set(page.path, page.label ?? page.key);
13
+ for (const collection of collections.values()) {
14
+ if (!collection.path) continue;
15
+ for (const entry of await readEntriesUnder(`${collection.key}/`)) {
16
+ const item = itemOf(collections, entry.key);
17
+ const path = item && itemPath(collection, item.slug);
18
+ if (item && path) labels.set(path, itemTitle(collection, item.slug, entry.value));
19
+ }
20
+ }
21
+ for (const path of paths) if (!labels.has(path)) labels.set(path, void 0);
22
+ return { pages: [...labels].map(([path, label]) => ({
23
+ path,
24
+ ...label ? { label } : {}
25
+ })).sort((a, b) => a.path.localeCompare(b.path)) };
26
+ });
27
+ async function readDevRoutes(path) {
28
+ const { readFile } = await import("node:fs/promises");
29
+ try {
30
+ return JSON.parse(await readFile(path, "utf8"));
31
+ } catch {
32
+ return routes;
33
+ }
34
+ }
35
+ export { links_get_default as default };
@@ -0,0 +1,74 @@
1
+ import { CmsImage, StoredImage } from "../schema.js";
2
+ /** An image file the editor uploaded: in the app's bucket, or in `public/cms/` under `nuxt dev`. */
3
+ export interface MediaFile {
4
+ /** What the delete route takes: the bucket's file id, or the file's name in `public/cms/`. */
5
+ name: string;
6
+ value: StoredImage;
7
+ /** The name it had on the uploader's computer, when the store kept it. */
8
+ fileName?: string;
9
+ size: number;
10
+ uploadedAt: string;
11
+ }
12
+ /** Where uploads live, so listing and deleting work alike against the bucket and the dev folder. */
13
+ export interface MediaStore {
14
+ list(): Promise<MediaFile[]>;
15
+ remove(name: string): Promise<void>;
16
+ }
17
+ /** Where the library shows an image. */
18
+ export interface MediaUse {
19
+ key: string;
20
+ title: string;
21
+ alt?: string;
22
+ }
23
+ export interface LibraryImage {
24
+ /** Missing for images that ship with the app: they aren't uploads and can't be deleted. */
25
+ name?: string;
26
+ value: StoredImage;
27
+ image: CmsImage;
28
+ /** A small version for the grid. */
29
+ thumb: string;
30
+ fileName?: string;
31
+ size?: number;
32
+ uploadedAt?: string;
33
+ uses: MediaUse[];
34
+ }
35
+ /** One string per image, the same for its stored and its shown form. */
36
+ export declare const imageRef: (image: {
37
+ id?: unknown;
38
+ src?: unknown;
39
+ }) => string | undefined;
40
+ /** Images saved with the app or uploaded under `nuxt dev`. */
41
+ export declare const isUploadPath: (src: string) => boolean;
42
+ /**
43
+ * Every image a stored value points at, with its alt text. Walks the value as stored rather than
44
+ * by the schema: a field renamed or removed since keeps its value, and a page may get it back, so
45
+ * its images still count as used. Something that only looks like an image (a list item with an
46
+ * `id` field) can only make an image look used, never one in use look free.
47
+ */
48
+ export declare function imagesIn(value: unknown, found?: {
49
+ ref: string;
50
+ alt?: string;
51
+ }[]): {
52
+ ref: string;
53
+ alt?: string;
54
+ }[];
55
+ /** Where each image is used, by `imageRef`. */
56
+ export declare function usesOf(contents: {
57
+ key: string;
58
+ title: string;
59
+ value: unknown;
60
+ }[]): Map<string, MediaUse[]>;
61
+ /**
62
+ * The uploads, newest first, then images under `/cms/` that content uses but the store doesn't
63
+ * hold: in production those shipped with the app from `public/cms/`.
64
+ */
65
+ export declare function buildLibrary(files: MediaFile[], uses: Map<string, MediaUse[]>, show: (value: StoredImage) => {
66
+ image: CmsImage;
67
+ thumb: string;
68
+ } | undefined): LibraryImage[];
69
+ export declare class ImageInUse extends Error {
70
+ readonly uses: MediaUse[];
71
+ constructor(uses: MediaUse[]);
72
+ }
73
+ /** Deletes an upload nothing uses any more. Returns false when the store has no such file. */
74
+ export declare function removeImage(store: MediaStore, name: string, uses: Map<string, MediaUse[]>): Promise<boolean>;
@@ -0,0 +1,88 @@
1
+ // src/runtime/server/media.ts
2
+ /** One string per image, the same for its stored and its shown form. */
3
+ const imageRef = (image) => typeof image.id === "string" ? `id:${image.id}` : typeof image.src === "string" ? `src:${image.src}` : void 0;
4
+ /** Images saved with the app or uploaded under `nuxt dev`. */
5
+ const isUploadPath = (src) => src.startsWith("/cms/");
6
+ /**
7
+ * Every image a stored value points at, with its alt text. Walks the value as stored rather than
8
+ * by the schema: a field renamed or removed since keeps its value, and a page may get it back, so
9
+ * its images still count as used. Something that only looks like an image (a list item with an
10
+ * `id` field) can only make an image look used, never one in use look free.
11
+ */
12
+ function imagesIn(value, found = []) {
13
+ if (Array.isArray(value)) for (const item of value) imagesIn(item, found);
14
+ else if (typeof value === "object" && value !== null) {
15
+ const record = value;
16
+ const ref = imageRef(record);
17
+ if (ref) found.push({
18
+ ref,
19
+ ...typeof record.alt === "string" ? { alt: record.alt } : {}
20
+ });
21
+ for (const child of Object.values(record)) imagesIn(child, found);
22
+ }
23
+ return found;
24
+ }
25
+ /** Where each image is used, by `imageRef`. */
26
+ function usesOf(contents) {
27
+ const uses = /* @__PURE__ */ new Map();
28
+ for (const content of contents) for (const { ref, alt } of imagesIn(content.value)) {
29
+ const list = uses.get(ref) ?? [];
30
+ const there = list.find((use) => use.key === content.key);
31
+ if (!there) list.push({
32
+ key: content.key,
33
+ title: content.title,
34
+ ...alt ? { alt } : {}
35
+ });
36
+ else if (!there.alt && alt) there.alt = alt;
37
+ uses.set(ref, list);
38
+ }
39
+ return uses;
40
+ }
41
+ /**
42
+ * The uploads, newest first, then images under `/cms/` that content uses but the store doesn't
43
+ * hold: in production those shipped with the app from `public/cms/`.
44
+ */
45
+ function buildLibrary(files, uses, show) {
46
+ const library = [];
47
+ const held = /* @__PURE__ */ new Set();
48
+ for (const file of [...files].sort((a, b) => b.uploadedAt.localeCompare(a.uploadedAt))) {
49
+ const ref = imageRef(file.value);
50
+ held.add(ref);
51
+ const shown = show(file.value);
52
+ if (!shown) continue;
53
+ library.push({
54
+ ...file,
55
+ ...shown,
56
+ uses: uses.get(ref) ?? []
57
+ });
58
+ }
59
+ for (const [ref, used] of uses) {
60
+ if (held.has(ref) || !ref.startsWith("src:")) continue;
61
+ const src = ref.slice(4);
62
+ if (!isUploadPath(src)) continue;
63
+ const shown = show({ src });
64
+ if (shown) library.push({
65
+ value: { src },
66
+ ...shown,
67
+ uses: used
68
+ });
69
+ }
70
+ return library;
71
+ }
72
+ var ImageInUse = class extends Error {
73
+ uses;
74
+ constructor(uses) {
75
+ super("The image is still used");
76
+ this.uses = uses;
77
+ }
78
+ };
79
+ /** Deletes an upload nothing uses any more. Returns false when the store has no such file. */
80
+ async function removeImage(store, name, uses) {
81
+ const file = (await store.list()).find((f) => f.name === name);
82
+ if (!file) return false;
83
+ const used = uses.get(imageRef(file.value)) ?? [];
84
+ if (used.length) throw new ImageInUse(used);
85
+ await store.remove(name);
86
+ return true;
87
+ }
88
+ export { ImageInUse, buildLibrary, imageRef, imagesIn, isUploadPath, removeImage, usesOf };
@@ -6,5 +6,13 @@ declare const _default: import("nuxt/server").EventHandler<{
6
6
  path: string | undefined;
7
7
  fields: CmsFields;
8
8
  }[];
9
+ collections: {
10
+ key: string;
11
+ label: string | undefined;
12
+ path: string | undefined;
13
+ fields: CmsFields;
14
+ titleField: string | undefined;
15
+ sort: string | undefined;
16
+ }[];
9
17
  }>;
10
18
  export { _default as default };
@@ -1,10 +1,20 @@
1
- import { pages } from "../pages.js";
1
+ import { collections, pages } from "../pages.js";
2
2
  import { defineEventHandler } from "nuxt/server";
3
3
  // src/runtime/server/schema.get.ts
4
- var schema_get_default = defineEventHandler(() => ({ pages: [...pages.values()].map(({ key, label, path, fields }) => ({
5
- key,
6
- label,
7
- path,
8
- fields
9
- })) }));
4
+ var schema_get_default = defineEventHandler(() => ({
5
+ pages: [...pages.values()].map(({ key, label, path, fields }) => ({
6
+ key,
7
+ label,
8
+ path,
9
+ fields
10
+ })),
11
+ collections: [...collections.values()].map(({ key, label, path, fields, titleField, sort }) => ({
12
+ key,
13
+ label,
14
+ path,
15
+ fields,
16
+ titleField,
17
+ sort
18
+ }))
19
+ }));
10
20
  export { schema_get_default as default };
@@ -1,8 +1,17 @@
1
- import { CmsEntry } from "./entries.js";
1
+ import { CmsEntry, CmsVersion } from "./entries.js";
2
2
  /**
3
3
  * Under `nuxt dev` the entry lives in the app's `cms/entries.json`, so edits made while
4
4
  * building the app ship with it. Deployed, the file is what was built and the database holds
5
5
  * the edits made on the live site; the one changed last wins.
6
6
  */
7
7
  export declare function readEntry(key: string): Promise<CmsEntry | undefined>;
8
- export declare function writeEntry(key: string, value: Record<string, unknown>): Promise<void>;
8
+ /**
9
+ * Saves the entry and answers its new `updatedAt`. With `expected` (the `updatedAt` the editor
10
+ * loaded, `null` for none) it throws `EntryConflict` instead when someone saved in between.
11
+ * `by` is who saves, for the history.
12
+ */
13
+ export declare function writeEntry(key: string, value: Record<string, unknown>, expected?: string | null, by?: string | null): Promise<string>;
14
+ /** The entry's versions, newest first, the current one included. */
15
+ export declare function readVersions(key: string): Promise<CmsVersion[]>;
16
+ /** The entries whose key starts with `prefix`, deleted ones left out, in no particular order. */
17
+ export declare function readEntriesUnder(prefix: string): Promise<CmsEntry[]>;
@@ -1,26 +1,46 @@
1
- import { fileEntry, newerEntry } from "./entries.js";
1
+ import { EntryConflict, fileEntriesUnder, fileEntry, live, mergeEntries, mergeVersions, newerEntry, sameInstant } from "./entries.js";
2
2
  import { useDb } from "@wervt/nuxt/server";
3
- import { eq, sql } from "drizzle-orm";
4
- import { jsonb, pgTable, text, timestamp } from "drizzle-orm/pg-core";
5
- import { entries, file } from "#wervt-cms/entries";
3
+ import { and, desc, eq, sql } from "drizzle-orm";
4
+ import { jsonb, pgTable, primaryKey, text, timestamp } from "drizzle-orm/pg-core";
5
+ import { entries, file, history } from "#wervt-cms/entries";
6
6
  // src/runtime/server/store.ts
7
7
  const entries$1 = pgTable("cms_entries", {
8
8
  key: text().primaryKey(),
9
9
  value: jsonb().$type().notNull(),
10
10
  updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
11
11
  });
12
+ const versions = pgTable("cms_entry_versions", {
13
+ key: text().notNull(),
14
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull(),
15
+ value: jsonb().$type().notNull(),
16
+ savedBy: text("saved_by")
17
+ }, (table) => [primaryKey({ columns: [table.key, table.updatedAt] })]);
12
18
  let ready;
13
19
  function ensureTables() {
14
- ready ??= useDb().execute(sql`create table if not exists cms_entries (
20
+ ready ??= (async () => {
21
+ const db = useDb();
22
+ await db.execute(sql`create table if not exists cms_entries (
15
23
  key text primary key,
16
24
  value jsonb not null,
17
25
  updated_at timestamptz not null default now()
18
- )`).catch((e) => {
26
+ )`);
27
+ await db.execute(sql`create table if not exists cms_entry_versions (
28
+ key text not null,
29
+ updated_at timestamptz not null,
30
+ value jsonb not null,
31
+ saved_by text,
32
+ primary key (key, updated_at)
33
+ )`);
34
+ })().catch((e) => {
19
35
  ready = void 0;
20
36
  throw e;
21
37
  });
22
38
  return ready;
23
39
  }
40
+ const fileStore = () => import.meta.dev && file ? {
41
+ entries: file,
42
+ history
43
+ } : void 0;
24
44
  async function readDbEntry(key) {
25
45
  await ensureTables();
26
46
  const [row] = await useDb().select().from(entries$1).where(eq(entries$1.key, key));
@@ -36,27 +56,97 @@ async function readDbEntry(key) {
36
56
  * the edits made on the live site; the one changed last wins.
37
57
  */
38
58
  async function readEntry(key) {
39
- if (import.meta.dev && file) {
59
+ const store = fileStore();
60
+ if (store) {
40
61
  const { readFileEntry } = await import("./file-store.js");
41
- return readFileEntry(file, key);
62
+ return readFileEntry(store, key);
42
63
  }
43
64
  return newerEntry(fileEntry(entries, key), await readDbEntry(key));
44
65
  }
45
- async function writeEntry(key, value) {
46
- if (import.meta.dev && file) {
66
+ const nowSql = sql`date_trunc('milliseconds', now())`;
67
+ const nextVersionSql = sql`greatest(${nowSql}, date_trunc('milliseconds', ${entries$1.updatedAt}) + interval '1 millisecond')`;
68
+ /**
69
+ * Saves the entry and answers its new `updatedAt`. With `expected` (the `updatedAt` the editor
70
+ * loaded, `null` for none) it throws `EntryConflict` instead when someone saved in between.
71
+ * `by` is who saves, for the history.
72
+ */
73
+ async function writeEntry(key, value, expected, by = null) {
74
+ const store = fileStore();
75
+ if (store) {
47
76
  const { writeFileEntry } = await import("./file-store.js");
48
- return writeFileEntry(file, key, value);
77
+ return writeFileEntry(store, key, value, expected, by);
49
78
  }
50
79
  await ensureTables();
51
- await useDb().insert(entries$1).values({
52
- key,
53
- value
54
- }).onConflictDoUpdate({
55
- target: entries$1.key,
56
- set: {
80
+ let row;
81
+ if (expected !== void 0) {
82
+ row = await readDbEntry(key);
83
+ const current = live(newerEntry(fileEntry(entries, key), row));
84
+ if (!sameInstant(current?.updatedAt, expected)) throw new EntryConflict(current);
85
+ }
86
+ const updatedAt = await useDb().transaction(async (tx) => {
87
+ const insert = tx.insert(entries$1).values({
88
+ key,
89
+ value,
90
+ updatedAt: nowSql
91
+ });
92
+ const [written] = expected === void 0 ? await insert.onConflictDoUpdate({
93
+ target: entries$1.key,
94
+ set: {
95
+ value,
96
+ updatedAt: nextVersionSql
97
+ }
98
+ }).returning({ updatedAt: entries$1.updatedAt }) : row ? await tx.update(entries$1).set({
57
99
  value,
58
- updatedAt: sql`now()`
59
- }
100
+ updatedAt: nextVersionSql
101
+ }).where(and(eq(entries$1.key, key), sql`date_trunc('milliseconds', ${entries$1.updatedAt}) = ${row.updatedAt}::timestamptz`)).returning({ updatedAt: entries$1.updatedAt }) : await insert.onConflictDoNothing().returning({ updatedAt: entries$1.updatedAt });
102
+ if (!written) return void 0;
103
+ await tx.insert(versions).values({
104
+ key,
105
+ updatedAt: written.updatedAt,
106
+ value,
107
+ savedBy: by
108
+ });
109
+ await tx.execute(sql`delete from cms_entry_versions where key = ${key} and updated_at < (
110
+ select updated_at from cms_entry_versions where key = ${key}
111
+ order by updated_at desc offset ${49} limit 1
112
+ )`);
113
+ return written.updatedAt.toISOString();
60
114
  });
115
+ if (!updatedAt) throw new EntryConflict(live(await readEntry(key)));
116
+ return updatedAt;
117
+ }
118
+ /** The entry's versions, newest first, the current one included. */
119
+ async function readVersions(key) {
120
+ const store = fileStore();
121
+ if (store) {
122
+ const { readFileVersions } = await import("./file-store.js");
123
+ return readFileVersions(store, key);
124
+ }
125
+ await ensureTables();
126
+ const rows = await useDb().select().from(versions).where(eq(versions.key, key)).orderBy(desc(versions.updatedAt)).limit(50);
127
+ return mergeVersions([
128
+ fileEntry(entries, key),
129
+ await readDbEntry(key),
130
+ ...rows.map((row) => ({
131
+ updatedAt: row.updatedAt.toISOString(),
132
+ value: row.value,
133
+ by: row.savedBy
134
+ }))
135
+ ]);
136
+ }
137
+ /** The entries whose key starts with `prefix`, deleted ones left out, in no particular order. */
138
+ async function readEntriesUnder(prefix) {
139
+ const store = fileStore();
140
+ if (store) {
141
+ const { readFileEntriesUnder } = await import("./file-store.js");
142
+ return readFileEntriesUnder(store, prefix);
143
+ }
144
+ await ensureTables();
145
+ const rows = await useDb().select().from(entries$1).where(sql`starts_with(${entries$1.key}, ${prefix})`);
146
+ return mergeEntries(fileEntriesUnder(entries, prefix), rows.map((row) => ({
147
+ key: row.key,
148
+ value: row.value,
149
+ updatedAt: row.updatedAt.toISOString()
150
+ })));
61
151
  }
62
- export { readEntry, writeEntry };
152
+ export { readEntriesUnder, readEntry, readVersions, writeEntry };
@@ -3,8 +3,8 @@ import { requireEditor } from "./access.js";
3
3
  import { serverImages } from "./images.js";
4
4
  import { sniffImage } from "./sniff.js";
5
5
  import { createError, defineEventHandler } from "nuxt/server";
6
- import { randomUUID } from "node:crypto";
7
6
  import { publicDir } from "#wervt-cms/entries";
7
+ import { randomUUID } from "node:crypto";
8
8
  import { readUploadedFile, useFileStorage } from "#imports";
9
9
  // src/runtime/server/upload.post.ts
10
10
  var upload_post_default = defineEventHandler(async (event) => {
@@ -33,7 +33,8 @@ var upload_post_default = defineEventHandler(async (event) => {
33
33
  }
34
34
  const { id } = await useFileStorage().put("cms", upload.data, {
35
35
  contentType: sniffed.type,
36
- name: `${randomUUID()}.${sniffed.extension}`
36
+ name: `${randomUUID()}.${sniffed.extension}`,
37
+ customMetadata: { fileName: upload.name.slice(0, 200) }
37
38
  });
38
39
  const value = { id };
39
40
  return {