@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.
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
package/dist/module.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { EditorTheme, EditorThemeColors } from "./editor-theme.js";
1
+ import { EditorLocale, EditorTheme, EditorThemeColors } from "./editor-theme.js";
2
+ import { EditButtonSide } from "./runtime/editor-link.js";
2
3
  export interface ModuleOptions {
3
4
  /**
4
5
  * Signed-in people with a confirmed address who may edit besides the app's owner, members and
@@ -8,6 +9,22 @@ export interface ModuleOptions {
8
9
  editor?: {
9
10
  /** The editor's look on this site; wervt's when missing. */
10
11
  theme?: EditorTheme;
12
+ /**
13
+ * Where the form sits beside the preview on wide screens, `left` when missing. Each editor
14
+ * can still switch it in the editor.
15
+ */
16
+ sidebar?: 'left' | 'right';
17
+ /**
18
+ * The editor's language. When missing: the site's `<html lang>` (`app.head.htmlAttrs.lang`)
19
+ * if the editor speaks it, otherwise the browser's.
20
+ */
21
+ locale?: EditorLocale;
22
+ /**
23
+ * The *Edit* button on the site's pages, in the bottom corner on this side, `left` when
24
+ * missing; `false` for none. It shows only in a browser where someone opened `/_cms` signed
25
+ * in as an editor, and opens the editor on the page it was pressed on.
26
+ */
27
+ button?: EditButtonSide | false;
11
28
  };
12
29
  }
13
30
  declare const _default: import("nuxt/schema").NuxtModule<ModuleOptions, ModuleOptions, false>;
package/dist/module.js CHANGED
@@ -1,7 +1,8 @@
1
- import { editorThemeHead } from "./editor-theme.js";
1
+ import { editorLocaleHead, editorSidebarHead, editorThemeHead } from "./editor-theme.js";
2
+ import { linkablePaths } from "./routes.js";
2
3
  import { stampEntries } from "./runtime/server/entries.js";
3
- import { existsSync, mkdirSync, readFileSync } from "node:fs";
4
- import { join, relative, resolve } from "node:path";
4
+ import { existsSync, mkdirSync, readFileSync, watch, writeFileSync } from "node:fs";
5
+ import { dirname, join, relative, resolve } from "node:path";
5
6
  import { addComponent, addImports, addPlugin, addServerHandler, addServerTemplate, addTemplate, addTypeTemplate, createResolver, defineNuxtModule, resolveFiles } from "nuxt/kit";
6
7
  // src/module.ts
7
8
  var module_default = defineNuxtModule({
@@ -21,8 +22,14 @@ var module_default = defineNuxtModule({
21
22
  editors: options.editors ?? "",
22
23
  ...config.cms
23
24
  };
25
+ const publicConfig = nuxt.options.runtimeConfig.public;
26
+ publicConfig.cms = {
27
+ editButton: options.editor?.button ?? "left",
28
+ ...publicConfig.cms
29
+ };
24
30
  const cmsDir = join(nuxt.options.rootDir, "cms");
25
31
  const file = join(cmsDir, "entries.json");
32
+ const historyFile = join(nuxt.options.rootDir, ".data", "cms-history.json");
26
33
  const publicDir = resolve(nuxt.options.rootDir, nuxt.options.dir.public);
27
34
  const schemaFiles = async () => (await resolveFiles(cmsDir, [
28
35
  "**/*.{ts,js,mjs}",
@@ -46,11 +53,13 @@ var module_default = defineNuxtModule({
46
53
  filename: "types/wervt-cms.d.ts",
47
54
  getContents: async () => {
48
55
  const dir = join(nuxt.options.buildDir, "types");
49
- const pages = (await schemaFiles()).map((path) => `PagesOf<typeof import(${JSON.stringify(relative(dir, path).replace(/\.[cm]?[jt]s$/, ""))})>`);
56
+ const modules = (await schemaFiles()).map((path) => `typeof import(${JSON.stringify(relative(dir, path).replace(/\.[cm]?[jt]s$/, ""))})`);
57
+ const extending = (of) => modules.length ? `extends ${modules.map((m) => `${of}<${m}>`).join(", ")} ` : "";
50
58
  return [
51
- `import type { PagesOf } from '@wervt/cms/schema'`,
59
+ `import type { CollectionsOf, PagesOf } from '@wervt/cms/schema'`,
52
60
  `declare module '@wervt/cms/schema' {`,
53
- ` interface CmsPages ${pages.length ? `extends ${pages.join(", ")} ` : ""}{}`,
61
+ ` interface CmsPages ${extending("PagesOf")}{}`,
62
+ ` interface CmsCollections ${extending("CollectionsOf")}{}`,
54
63
  `}`,
55
64
  `export {}`,
56
65
  ""
@@ -74,11 +83,28 @@ var module_default = defineNuxtModule({
74
83
  return [
75
84
  `export const entries = ${JSON.stringify(stamped)}`,
76
85
  `export const file = ${nuxt.options.dev ? JSON.stringify(file) : "undefined"}`,
86
+ `export const history = ${nuxt.options.dev ? JSON.stringify(historyFile) : "undefined"}`,
77
87
  `export const publicDir = ${nuxt.options.dev ? JSON.stringify(publicDir) : "undefined"}`,
78
88
  ""
79
89
  ].join("\n");
80
90
  }
81
91
  });
92
+ let routes = [];
93
+ const routesFile = join(nuxt.options.buildDir, "wervt-cms", "routes.json");
94
+ nuxt.hook("pages:resolved", (pages) => {
95
+ routes = linkablePaths(pages);
96
+ if (!nuxt.options.dev) return;
97
+ mkdirSync(dirname(routesFile), { recursive: true });
98
+ writeFileSync(routesFile, JSON.stringify(routes));
99
+ });
100
+ addServerTemplate({
101
+ filename: "#wervt-cms/routes",
102
+ getContents: () => [
103
+ `export const routes = ${JSON.stringify(routes)}`,
104
+ `export const file = ${nuxt.options.dev ? JSON.stringify(routesFile) : "undefined"}`,
105
+ ""
106
+ ].join("\n")
107
+ });
82
108
  addServerHandler({
83
109
  route: "/api/_cms/entries/**:key",
84
110
  method: "get",
@@ -89,6 +115,31 @@ var module_default = defineNuxtModule({
89
115
  method: "put",
90
116
  handler: resolver.resolve("./runtime/server/entry.put")
91
117
  });
118
+ addServerHandler({
119
+ route: "/api/_cms/entries/**:key",
120
+ method: "delete",
121
+ handler: resolver.resolve("./runtime/server/entry.delete")
122
+ });
123
+ addServerHandler({
124
+ route: "/api/_cms/collections/:key",
125
+ method: "get",
126
+ handler: resolver.resolve("./runtime/server/collection.get")
127
+ });
128
+ addServerHandler({
129
+ route: "/api/_cms/versions/**:key",
130
+ method: "get",
131
+ handler: resolver.resolve("./runtime/server/versions.get")
132
+ });
133
+ addServerHandler({
134
+ route: "/api/_cms/links",
135
+ method: "get",
136
+ handler: resolver.resolve("./runtime/server/links.get")
137
+ });
138
+ addServerHandler({
139
+ route: "/api/_cms/access",
140
+ method: "get",
141
+ handler: resolver.resolve("./runtime/server/access.get")
142
+ });
92
143
  addServerHandler({
93
144
  route: "/api/_cms/schema",
94
145
  method: "get",
@@ -99,10 +150,32 @@ var module_default = defineNuxtModule({
99
150
  method: "post",
100
151
  handler: resolver.resolve("./runtime/server/upload.post")
101
152
  });
153
+ addServerHandler({
154
+ route: "/api/_cms/images",
155
+ method: "get",
156
+ handler: resolver.resolve("./runtime/server/images.get")
157
+ });
158
+ addServerHandler({
159
+ route: "/api/_cms/images/:name",
160
+ method: "delete",
161
+ handler: resolver.resolve("./runtime/server/image.delete")
162
+ });
102
163
  addImports({
103
164
  name: "useCms",
104
165
  from: resolver.resolve("./runtime/app/useCms")
105
166
  });
167
+ addImports({
168
+ name: "useCmsCollection",
169
+ from: resolver.resolve("./runtime/app/useCmsCollection")
170
+ });
171
+ addImports({
172
+ name: "useCmsItem",
173
+ from: resolver.resolve("./runtime/app/useCmsCollection")
174
+ });
175
+ addImports({
176
+ name: "useCmsSeo",
177
+ from: resolver.resolve("./runtime/app/useCmsSeo")
178
+ });
106
179
  addComponent({
107
180
  name: "CmsRichText",
108
181
  filePath: resolver.resolve("./runtime/app/CmsRichText")
@@ -111,7 +184,11 @@ var module_default = defineNuxtModule({
111
184
  src: resolver.resolve("./runtime/app/preview.client"),
112
185
  mode: "client"
113
186
  });
114
- setupEditor(resolver.resolve("../dist/editor"), editorThemeHead(options.editor?.theme), nuxt);
187
+ setupEditor(resolver.resolve("../dist/editor"), [
188
+ editorThemeHead(options.editor?.theme),
189
+ editorSidebarHead(options.editor?.sidebar),
190
+ editorLocaleHead(options.editor?.locale, nuxt.options.app.head.htmlAttrs?.lang)
191
+ ].filter(Boolean).join("\n"), nuxt);
115
192
  }
116
193
  });
117
194
  /**
@@ -142,5 +219,16 @@ function setupEditor(dir, themeHead, nuxt) {
142
219
  method: "get",
143
220
  handler: createResolver(import.meta.url).resolve("./runtime/server/editor.get")
144
221
  });
222
+ if (nuxt.options.dev) {
223
+ let timer;
224
+ const watcher = watch(dir, { recursive: true }, () => {
225
+ clearTimeout(timer);
226
+ timer = setTimeout(() => void nuxt.callHook("restart"), 500);
227
+ });
228
+ nuxt.hook("close", () => {
229
+ clearTimeout(timer);
230
+ watcher.close();
231
+ });
232
+ }
145
233
  }
146
234
  export { module_default as default };
package/dist/routes.js ADDED
@@ -0,0 +1,16 @@
1
+ // src/routes.ts
2
+ /**
3
+ * The site's pages an editor can link to: every route without parameters (`/menu`, not
4
+ * `/menu/:id`), children joined to their parents, the CMS's and Nuxt's own (`/_…`, `/api`) left
5
+ * out.
6
+ */
7
+ function linkablePaths(routes, parent = "") {
8
+ const paths = /* @__PURE__ */ new Set();
9
+ for (const route of routes) {
10
+ const path = route.path.startsWith("/") ? route.path : `${parent.replace(/\/$/, "")}/${route.path}`.replace(/\/$/, "") || "/";
11
+ if (!/[:*(]/.test(path) && !/^\/(?:_|api(?:\/|$))/.test(path)) paths.add(path);
12
+ for (const child of linkablePaths(route.children ?? [], path)) paths.add(child);
13
+ }
14
+ return [...paths];
15
+ }
16
+ export { linkablePaths };
@@ -0,0 +1,7 @@
1
+ import { EditButtonSide } from "../editor-link.js";
2
+ export declare function isEditor(): boolean;
3
+ /**
4
+ * The *Edit* button in a corner of the site. In a shadow root with its own styles, so the
5
+ * site's CSS can't reach it and it can't reach the site's.
6
+ */
7
+ export declare function mountEditButton(side: EditButtonSide): HTMLElement;
@@ -0,0 +1,56 @@
1
+ import { editorMark, editorUrl } from "../editor-link.js";
2
+ // src/runtime/app/edit-button.ts
3
+ const labels = {
4
+ de: "Bearbeiten",
5
+ en: "Edit"
6
+ };
7
+ const pencil = "<svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z\"/><path d=\"m15 5 4 4\"/></svg>";
8
+ function isEditor() {
9
+ try {
10
+ return localStorage.getItem(editorMark) === "1";
11
+ } catch {
12
+ return false;
13
+ }
14
+ }
15
+ /**
16
+ * The *Edit* button in a corner of the site. In a shadow root with its own styles, so the
17
+ * site's CSS can't reach it and it can't reach the site's.
18
+ */
19
+ function mountEditButton(side) {
20
+ const host = document.createElement("wervt-cms-edit");
21
+ const root = host.attachShadow({ mode: "open" });
22
+ const lang = document.documentElement.lang.slice(0, 2).toLowerCase();
23
+ const link = document.createElement("a");
24
+ link.innerHTML = `${pencil}<span>${labels[lang] ?? labels.en}</span>`;
25
+ const follow = () => link.href = editorUrl(location.pathname + location.search + location.hash);
26
+ follow();
27
+ link.addEventListener("pointerdown", follow);
28
+ link.addEventListener("focus", follow);
29
+ const style = document.createElement("style");
30
+ style.textContent = `
31
+ a {
32
+ position: fixed;
33
+ ${side}: calc(16px + env(safe-area-inset-${side}));
34
+ bottom: calc(16px + env(safe-area-inset-bottom));
35
+ z-index: 2147483000;
36
+ display: inline-flex;
37
+ align-items: center;
38
+ gap: 6px;
39
+ padding: 8px 14px 8px 12px;
40
+ border-radius: 999px;
41
+ background: #18181b;
42
+ color: #fafafa;
43
+ font: 500 14px/20px system-ui, sans-serif;
44
+ text-decoration: none;
45
+ box-shadow: 0 1px 2px rgb(0 0 0 / 0.2), 0 4px 12px rgb(0 0 0 / 0.15);
46
+ opacity: 0.92;
47
+ }
48
+ a:hover { opacity: 1; }
49
+ a:focus-visible { outline: 2px solid #3b82f6; outline-offset: 2px; }
50
+ @media print { a { display: none; } }
51
+ `;
52
+ root.append(style, link);
53
+ document.body.append(host);
54
+ return host;
55
+ }
56
+ export { isEditor, mountEditButton };
@@ -1,10 +1,15 @@
1
1
  import { readMessage, siteMessage } from "../preview.js";
2
2
  import { drafts } from "./drafts.js";
3
- import { defineNuxtPlugin, useRouter } from "#app";
3
+ import { isEditor, mountEditButton } from "./edit-button.js";
4
+ import { defineNuxtPlugin, useRouter, useRuntimeConfig } from "#app";
4
5
  // src/runtime/app/preview.client.ts
5
6
  var preview_client_default = defineNuxtPlugin((nuxtApp) => {
6
7
  const parent = window.parent;
7
- if (parent === window) return;
8
+ if (parent === window) {
9
+ const side = useRuntimeConfig().public.cms?.editButton;
10
+ if ((side === "left" || side === "right") && isEditor()) nuxtApp.hook("app:mounted", () => void mountEditButton(side));
11
+ return;
12
+ }
8
13
  try {
9
14
  if (parent.location.origin !== location.origin || !parent.location.pathname.startsWith("/_cms")) return;
10
15
  } catch {
@@ -14,10 +19,12 @@ var preview_client_default = defineNuxtPlugin((nuxtApp) => {
14
19
  const report = (path) => parent.postMessage(siteMessage(path), location.origin);
15
20
  addEventListener("message", (event) => {
16
21
  const message = readMessage(event, parent, location.origin, "draft");
17
- if (message) drafts.value = {
18
- ...drafts.value,
22
+ if (!message) return;
23
+ const { [message.key]: _, ...others } = drafts.value;
24
+ drafts.value = message.value ? {
25
+ ...others,
19
26
  [message.key]: message.value
20
- };
27
+ } : others;
21
28
  });
22
29
  nuxtApp.hook("app:mounted", () => report(router.currentRoute.value.fullPath));
23
30
  router.afterEach((to) => {
@@ -0,0 +1,24 @@
1
+ import { CmsCollections, CmsFields, CmsItem } from "../schema.js";
2
+ import { ComputedRef, MaybeRefOrGetter } from "vue";
3
+ type ItemOf<K extends keyof CmsCollections> = CmsCollections[K] extends CmsFields ? CmsItem<CmsCollections[K]> : never;
4
+ /**
5
+ * The items of a collection defined in `cms/*.ts`, in its order and typed from its fields. Each
6
+ * has its `slug`, and its `path` when the collection has one. Awaited like `useFetch`, so a page
7
+ * navigated to shows its list at once instead of an empty one first:
8
+ *
9
+ * ```ts
10
+ * const posts = await useCmsCollection('news')
11
+ * ```
12
+ */
13
+ export declare function useCmsCollection<K extends Extract<keyof CmsCollections, string>>(key: K): Promise<ComputedRef<ItemOf<K>[]>>;
14
+ /**
15
+ * One item of a collection, by its slug (a route param, say); `null` when there is none, so the
16
+ * page can answer 404. Awaited, so that check sees the item:
17
+ *
18
+ * ```ts
19
+ * const post = await useCmsItem('news', () => String(route.params.slug))
20
+ * if (!post.value) throw createError({ status: 404, fatal: true })
21
+ * ```
22
+ */
23
+ export declare function useCmsItem<K extends Extract<keyof CmsCollections, string>>(key: K, slug: MaybeRefOrGetter<string>): Promise<ComputedRef<ItemOf<K> | null>>;
24
+ export {};
@@ -0,0 +1,74 @@
1
+ import { isSlug, itemKey, itemOf, itemPath, sortItems } from "../collections.js";
2
+ import { collections } from "../pages.js";
3
+ import { drafts } from "./drafts.js";
4
+ import { computed, toValue } from "vue";
5
+ import { useFetch } from "#app";
6
+ // src/runtime/app/useCmsCollection.ts
7
+ /**
8
+ * The items of a collection defined in `cms/*.ts`, in its order and typed from its fields. Each
9
+ * has its `slug`, and its `path` when the collection has one. Awaited like `useFetch`, so a page
10
+ * navigated to shows its list at once instead of an empty one first:
11
+ *
12
+ * ```ts
13
+ * const posts = await useCmsCollection('news')
14
+ * ```
15
+ */
16
+ async function useCmsCollection(key) {
17
+ const name = key;
18
+ const fetched = useFetch(`/api/_cms/collections/${name}`, { key: `wervt-cms-collection:${name}` });
19
+ const collection = collections.get(key);
20
+ const items = computed(() => {
21
+ const items = new Map((fetched.data.value?.items ?? []).map((item) => [item.slug, item]));
22
+ for (const [draftKey, value] of Object.entries(drafts.value)) {
23
+ const item = itemOf(collections, draftKey);
24
+ if (item?.collection.key !== key) continue;
25
+ const path = itemPath(item.collection, item.slug);
26
+ items.set(item.slug, {
27
+ slug: item.slug,
28
+ ...path ? { path } : {},
29
+ value
30
+ });
31
+ }
32
+ return (collection ? sortItems(collection, [...items.values()]) : [...items.values()]).map(({ slug, path, value }) => ({
33
+ ...value,
34
+ slug,
35
+ ...path ? { path } : {}
36
+ }));
37
+ });
38
+ await fetched;
39
+ return items;
40
+ }
41
+ /**
42
+ * One item of a collection, by its slug (a route param, say); `null` when there is none, so the
43
+ * page can answer 404. Awaited, so that check sees the item:
44
+ *
45
+ * ```ts
46
+ * const post = await useCmsItem('news', () => String(route.params.slug))
47
+ * if (!post.value) throw createError({ status: 404, fatal: true })
48
+ * ```
49
+ */
50
+ async function useCmsItem(key, slug) {
51
+ const name = key;
52
+ const entryKey = () => itemKey(name, toValue(slug));
53
+ const fetched = useFetch(() => `/api/_cms/entries/${entryKey()}`, {
54
+ key: () => `wervt-cms:${entryKey()}`,
55
+ immediate: isSlug(toValue(slug))
56
+ });
57
+ const collection = collections.get(name);
58
+ const item = computed(() => {
59
+ const current = toValue(slug);
60
+ if (!isSlug(current)) return null;
61
+ const data = fetched.data.value;
62
+ const value = drafts.value[entryKey()] ?? (data?.updatedAt ? data.value : void 0);
63
+ if (!value) return null;
64
+ const path = collection && itemPath(collection, current);
65
+ return {
66
+ ...value,
67
+ slug: current,
68
+ ...path ? { path } : {}
69
+ };
70
+ });
71
+ await fetched;
72
+ return item;
73
+ }
74
+ export { useCmsCollection, useCmsItem };
@@ -0,0 +1,7 @@
1
+ import { CmsPages } from "../schema.js";
2
+ /**
3
+ * The `<title>`, description and share image from the page's `seo()` field. Called by the page it
4
+ * describes, not inside `useCms`: a layout or footer reads content too, and mustn't retitle every
5
+ * page. What the editor leaves empty keeps the page's own.
6
+ */
7
+ export declare function useCmsSeo(key: Extract<keyof CmsPages, string>): void;
@@ -0,0 +1,31 @@
1
+ import { pages } from "../pages.js";
2
+ import { seoFieldName, seoMeta } from "../seo.js";
3
+ import { useCms } from "./useCms.js";
4
+ import { computed } from "vue";
5
+ import { useRequestURL, useSeoMeta } from "#app";
6
+ // src/runtime/app/useCmsSeo.ts
7
+ /**
8
+ * The `<title>`, description and share image from the page's `seo()` field. Called by the page it
9
+ * describes, not inside `useCms`: a layout or footer reads content too, and mustn't retitle every
10
+ * page. What the editor leaves empty keeps the page's own.
11
+ */
12
+ function useCmsSeo(key) {
13
+ const name = seoFieldName(pages.get(key)?.fields);
14
+ if (!name) {
15
+ if (import.meta.dev) console.warn(`[cms] useCmsSeo('${String(key)}'): the page has no seo() field`);
16
+ return;
17
+ }
18
+ const content = useCms(key);
19
+ const origin = useRequestURL({ xForwardedProto: true }).origin;
20
+ const meta = computed(() => seoMeta(content.value[name], origin));
21
+ useSeoMeta({
22
+ title: () => meta.value.title,
23
+ ogTitle: () => meta.value.ogTitle,
24
+ description: () => meta.value.description,
25
+ ogDescription: () => meta.value.ogDescription,
26
+ ogImage: () => meta.value.ogImage,
27
+ ogImageAlt: () => meta.value.ogImageAlt,
28
+ twitterCard: () => meta.value.twitterCard
29
+ }, { tagPriority: "high" });
30
+ }
31
+ export { useCmsSeo };
@@ -0,0 +1,25 @@
1
+ import { CmsCollection } from "./schema.js";
2
+ /** Lowercase letters, digits and single dashes inside: `summer-sale-2026`. */
3
+ export declare function isSlug(slug: unknown): slug is string;
4
+ /** A slug made from a title: `Café & Kuchen am Sonntag` is `cafe-kuchen-am-sonntag`. */
5
+ export declare function slugify(title: string): string;
6
+ /** A slug from `title` that none of `taken` has yet: `-2`, `-3` … when it's in use. */
7
+ export declare function freeSlug(title: string, taken: Iterable<string>): string;
8
+ /** The entry an item is saved as: `posts/summer-sale`. */
9
+ export declare const itemKey: (collection: string, slug: string) => string;
10
+ /** The collection and slug of an item's entry key, if it is one of `collections`. */
11
+ export declare function itemOf<C extends Pick<CmsCollection, 'key'>>(collections: Map<string, C>, key: string): {
12
+ collection: C;
13
+ slug: string;
14
+ } | undefined;
15
+ /** Where an item is on the site, if its collection has a `path`. */
16
+ export declare function itemPath(collection: Pick<CmsCollection, 'path'>, slug: string): string | undefined;
17
+ /** The slug in `path` if it is where an item of `collection` is. */
18
+ export declare function slugAt(collection: Pick<CmsCollection, 'path'>, path: string): string | undefined;
19
+ /** What the editor calls an item: its title, or its slug when that's empty. */
20
+ export declare function itemTitle(collection: Pick<CmsCollection, 'titleField'>, slug: string, value: Record<string, unknown>): string;
21
+ /** Items in the collection's order: by `sort`, by title without one, by slug when that's even. */
22
+ export declare function sortItems<T extends {
23
+ slug: string;
24
+ value: Record<string, unknown>;
25
+ }>(collection: Pick<CmsCollection, 'sort' | 'titleField'>, items: T[]): T[];
@@ -0,0 +1,81 @@
1
+ // src/runtime/collections.ts
2
+ const SLUG = /^[a-z0-9](?:[a-z0-9-]{0,98}[a-z0-9])?$/;
3
+ /** Lowercase letters, digits and single dashes inside: `summer-sale-2026`. */
4
+ function isSlug(slug) {
5
+ return typeof slug === "string" && SLUG.test(slug) && !slug.includes("--");
6
+ }
7
+ const SPELLED_OUT = {
8
+ ä: "ae",
9
+ ö: "oe",
10
+ ü: "ue",
11
+ ß: "ss",
12
+ æ: "ae",
13
+ ø: "o",
14
+ œ: "oe"
15
+ };
16
+ /** A slug made from a title: `Café & Kuchen am Sonntag` is `cafe-kuchen-am-sonntag`. */
17
+ function slugify(title) {
18
+ return title.toLowerCase().replace(/[äöüßæøœ]/g, (letter) => SPELLED_OUT[letter]).normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").slice(0, 80).replace(/^-+|-+$/g, "");
19
+ }
20
+ /** A slug from `title` that none of `taken` has yet: `-2`, `-3` … when it's in use. */
21
+ function freeSlug(title, taken) {
22
+ const base = slugify(title) || "item";
23
+ const used = new Set(taken);
24
+ if (!used.has(base)) return base;
25
+ for (let n = 2;; n++) if (!used.has(`${base}-${n}`)) return `${base}-${n}`;
26
+ }
27
+ /** The entry an item is saved as: `posts/summer-sale`. */
28
+ const itemKey = (collection, slug) => `${collection}/${slug}`;
29
+ /** The collection and slug of an item's entry key, if it is one of `collections`. */
30
+ function itemOf(collections, key) {
31
+ const at = key.indexOf("/");
32
+ if (at < 0) return void 0;
33
+ const collection = collections.get(key.slice(0, at));
34
+ const slug = key.slice(at + 1);
35
+ return collection && isSlug(slug) ? {
36
+ collection,
37
+ slug
38
+ } : void 0;
39
+ }
40
+ /** Where an item is on the site, if its collection has a `path`. */
41
+ function itemPath(collection, slug) {
42
+ return collection.path?.replace("[slug]", slug);
43
+ }
44
+ /** The slug in `path` if it is where an item of `collection` is. */
45
+ function slugAt(collection, path) {
46
+ if (!collection.path) return void 0;
47
+ const [before, after] = collection.path.split("[slug]");
48
+ const clean = path.replace(/[?#].*$/, "").replace(/(.)\/+$/, "$1");
49
+ if (!clean.startsWith(before) || !clean.endsWith(after)) return void 0;
50
+ const slug = clean.slice(before.length, clean.length - after.length);
51
+ return isSlug(slug) ? slug : void 0;
52
+ }
53
+ /** What the editor calls an item: its title, or its slug when that's empty. */
54
+ function itemTitle(collection, slug, value) {
55
+ const title = collection.titleField ? value[collection.titleField] : void 0;
56
+ return typeof title === "string" && title.trim() ? title.trim() : slug;
57
+ }
58
+ /** Items in the collection's order: by `sort`, by title without one, by slug when that's even. */
59
+ function sortItems(collection, items) {
60
+ const sort = collection.sort ?? collection.titleField;
61
+ const descending = sort?.startsWith("-") ?? false;
62
+ const field = descending ? sort.slice(1) : sort;
63
+ return [...items].sort((a, b) => {
64
+ const order = field ? compareValues(a.value[field], b.value[field]) : 0;
65
+ if (order === Infinity || order === -Infinity) return order > 0 ? 1 : -1;
66
+ return (descending ? -order : order) || a.slug.localeCompare(b.slug);
67
+ });
68
+ }
69
+ const collator = new Intl.Collator(void 0, {
70
+ numeric: true,
71
+ sensitivity: "base"
72
+ });
73
+ function compareValues(a, b) {
74
+ const empty = (v) => v === null || v === void 0 || v === "";
75
+ if (empty(a) || empty(b)) return empty(a) === empty(b) ? 0 : empty(a) ? Infinity : -Infinity;
76
+ if (typeof a === "number" && typeof b === "number") return a - b;
77
+ if (typeof a === "boolean" && typeof b === "boolean") return Number(a) - Number(b);
78
+ return collator.compare(asText(a), asText(b));
79
+ }
80
+ const asText = (value) => typeof value === "string" ? value : JSON.stringify(value);
81
+ export { freeSlug, isSlug, itemKey, itemOf, itemPath, itemTitle, slugAt, slugify, sortItems };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The way from the site into the editor: an *Edit* button on the site's pages that opens `/_cms`
3
+ * on the page it was pressed on. Shared by the site's plugin and the editor.
4
+ */
5
+ /**
6
+ * Set in the browser's storage once the editor confirmed the signed-in person may edit, removed
7
+ * when it found they may not. The site reads it to decide on the button without asking the
8
+ * server, so visitors cost nothing and the site's HTML stays the same for everyone.
9
+ */
10
+ export declare const editorMark = "wervt-cms:editor";
11
+ /** Where the editor opens on `path`. */
12
+ export declare const editorUrl: (path: string) => string;
13
+ /**
14
+ * `path` as the editor may show it in its preview: a page of this site (`origin`) outside the
15
+ * editor, with search and hash. Anything else, `undefined`: the query is anyone's to write, and an
16
+ * iframe would run `javascript:` or show another site inside the editor.
17
+ */
18
+ export declare function previewPath(path: string | null | undefined, origin: string): string | undefined;
19
+ export type EditButtonSide = 'left' | 'right';
@@ -0,0 +1,31 @@
1
+ // src/runtime/editor-link.ts
2
+ /**
3
+ * The way from the site into the editor: an *Edit* button on the site's pages that opens `/_cms`
4
+ * on the page it was pressed on. Shared by the site's plugin and the editor.
5
+ */
6
+ /**
7
+ * Set in the browser's storage once the editor confirmed the signed-in person may edit, removed
8
+ * when it found they may not. The site reads it to decide on the button without asking the
9
+ * server, so visitors cost nothing and the site's HTML stays the same for everyone.
10
+ */
11
+ const editorMark = "wervt-cms:editor";
12
+ /** Where the editor opens on `path`. */
13
+ const editorUrl = (path) => `/_cms?path=${encodeURIComponent(path)}`;
14
+ /**
15
+ * `path` as the editor may show it in its preview: a page of this site (`origin`) outside the
16
+ * editor, with search and hash. Anything else, `undefined`: the query is anyone's to write, and an
17
+ * iframe would run `javascript:` or show another site inside the editor.
18
+ */
19
+ function previewPath(path, origin) {
20
+ if (!path?.startsWith("/")) return void 0;
21
+ let url;
22
+ try {
23
+ url = new URL(path, origin);
24
+ } catch {
25
+ return;
26
+ }
27
+ if (url.origin !== origin || !/^https?:$/.test(url.protocol)) return void 0;
28
+ if (/^\/(?:_cms|api\/_cms)(?:\/|$)/.test(url.pathname)) return void 0;
29
+ return url.pathname + url.search + url.hash;
30
+ }
31
+ export { editorMark, editorUrl, previewPath };
@@ -1,4 +1,4 @@
1
- import { CmsField, CmsFields, CmsImage, StoredImage } from "./schema.js";
1
+ import { CmsField, CmsFields, CmsImage, ImageFocus, StoredImage } from "./schema.js";
2
2
  export declare function isField(value: CmsField | CmsFields): value is CmsField;
3
3
  type Plain = Record<string, unknown>;
4
4
  /** Turns a stored image into what the page shows; `undefined` when it can't be shown. */
@@ -12,6 +12,8 @@ export declare const staticImages: ImageResolver;
12
12
  * when a field is renamed back.
13
13
  */
14
14
  export declare function resolveValue(fields: CmsFields, stored: unknown, images: ImageResolver): Plain;
15
+ /** The image with `focus` and the `position` the page crops by, or without both. */
16
+ export declare function withFocus(image: CmsImage, focus: ImageFocus | undefined): CmsImage;
15
17
  export declare class InvalidValue extends Error {}
16
18
  /**
17
19
  * Checks an edit against the schema and brings it into the form it's stored in. Takes what GET
@@ -19,6 +21,36 @@ export declare class InvalidValue extends Error {}
19
21
  * signed URL is stored as its file again.
20
22
  */
21
23
  export declare function normalizeValue(fields: CmsFields, input: unknown, path?: string): Plain;
24
+ /** Why a value can't be saved as it is, beyond its type: what the page's `cms/` asks of it. */
25
+ export type FieldProblem = {
26
+ kind: 'required';
27
+ } | {
28
+ kind: 'tooLong';
29
+ max: number;
30
+ length: number;
31
+ } | {
32
+ kind: 'tooSmall';
33
+ min: number;
34
+ } | {
35
+ kind: 'tooLarge';
36
+ max: number;
37
+ } | {
38
+ kind: 'tooEarly';
39
+ min: string;
40
+ } | {
41
+ kind: 'tooLate';
42
+ max: string;
43
+ };
44
+ /** Characters as people count them: 👋🏽 is one, not four UTF-16 units. */
45
+ export declare function textLength(value: string): number;
46
+ /** The rule a field's value breaks, if any. Values of the wrong type are `normalizeValue`'s job. */
47
+ export declare function fieldProblem(field: CmsField, value: unknown): FieldProblem | undefined;
48
+ /** Every field in `value` that breaks its rule, with its path (`hero.title`, `hours[2].day`). */
49
+ export declare function findProblems(fields: CmsFields, value: unknown, path?: string): {
50
+ path: string;
51
+ problem: FieldProblem;
52
+ }[];
22
53
  /** An edited `href` is put on the live site as is, so only harmless schemes get through. */
23
54
  export declare function isSafeHref(href: string): boolean;
55
+ export declare function toFocus(input: unknown): ImageFocus | undefined;
24
56
  export {};