@sindingmind/cms-astro 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,61 @@
1
+ // Folds `isCmsEditing()` into a literal at every call site, at build time.
2
+ //
3
+ // `isCmsEditing()` is a function in `attrs.ts`. When two page scripts import it, Rolldown (Vite 8) puts it in a
4
+ // shared chunk (`var e=()=>!1`) and keeps the calls, so every script that checks it changes, and the production
5
+ // build is no longer what the site would be without the CMS. A function call cannot be replaced with Vite's
6
+ // `define`, so the integration's Vite plugin rewrites the calls instead: in every module that imports
7
+ // `isCmsEditing` from "@sindingmind/cms-astro/attrs", each call `isCmsEditing()` (also under an `as` name) becomes
8
+ // `false` in a build. The import is then unused, the bundler drops `attrs.ts`, and the minifier removes the dead
9
+ // branch, so the script is exactly what it would be with the check written as `false`.
10
+ //
11
+ // What is not folded (it still works, through the function): `isCmsEditing` used as a value (`const f =
12
+ // isCmsEditing`), a namespace import (`import * as attrs`), and a call with arguments.
13
+ export const ATTRS_SPECIFIER = "@sindingmind/cms-astro/attrs";
14
+ /**
15
+ * Returns `code` with every `isCmsEditing()` call replaced by `value` (as a literal), or undefined if the module does
16
+ * not import `isCmsEditing` from the attrs module (or there is nothing to replace).
17
+ */
18
+ export function foldEditingCalls(code, parse, value) {
19
+ if (!code.includes("isCmsEditing") || !code.includes(ATTRS_SPECIFIER))
20
+ return undefined;
21
+ const program = parse(code);
22
+ const names = new Set();
23
+ for (const stmt of program.body) {
24
+ if (stmt.type !== "ImportDeclaration" || stmt.source.value !== ATTRS_SPECIFIER)
25
+ continue;
26
+ for (const s of stmt.specifiers) {
27
+ const imported = s.imported;
28
+ if (s.type === "ImportSpecifier" && (imported?.name ?? imported?.value) === "isCmsEditing")
29
+ names.add(s.local.name);
30
+ }
31
+ }
32
+ if (!names.size)
33
+ return undefined;
34
+ const calls = [];
35
+ const visit = (node) => {
36
+ if (Array.isArray(node))
37
+ return node.forEach(visit);
38
+ if (!node || typeof node !== "object")
39
+ return;
40
+ const n = node;
41
+ if (n.type === "CallExpression" && n.arguments.length === 0 && !n.optional) {
42
+ const callee = n.callee;
43
+ if (callee.type === "Identifier" && names.has(callee.name)) {
44
+ calls.push(n);
45
+ return;
46
+ }
47
+ }
48
+ for (const key of Object.keys(n))
49
+ if (key !== "type" && key !== "start" && key !== "end" && key !== "range" && key !== "loc")
50
+ visit(n[key]);
51
+ };
52
+ visit(program.body);
53
+ if (!calls.length)
54
+ return undefined;
55
+ // Replace from the end so the earlier offsets stay valid. The literal is wrapped in parentheses, so it is an
56
+ // expression wherever the call was (`isCmsEditing().toString()` stays valid).
57
+ let out = code;
58
+ for (const call of calls.sort((a, b) => b.start - a.start))
59
+ out = `${out.slice(0, call.start)}(${value})${out.slice(call.end)}`;
60
+ return out;
61
+ }
@@ -0,0 +1,237 @@
1
+ export type TextField = {
2
+ kind: "text";
3
+ label: string;
4
+ help?: string;
5
+ max?: number;
6
+ multiline?: boolean;
7
+ /** May be missing or empty in the YAML. An empty value removes the key from the YAML. */
8
+ optional?: boolean;
9
+ /**
10
+ * Names the site replaces in this text, written as `{name}` (e.g. `["modul", "timepris"]` for "{modul}"). Only
11
+ * these may appear in the text; an unknown name or a stray brace is rejected. The YAML keeps them as written,
12
+ * and the preview shows the merged text because the site's own render merges them. Implies `inline: false`.
13
+ */
14
+ placeholders?: readonly string[];
15
+ /**
16
+ * `false`: the text cannot be typed on the page, only in the panel and the page form. Use it when the page
17
+ * shows something else than the stored text (merged placeholders, `{klammer}` turned into markup, ...).
18
+ */
19
+ inline?: boolean;
20
+ };
21
+ export type NumberField = {
22
+ kind: "number";
23
+ label: string;
24
+ help?: string;
25
+ min?: number;
26
+ max?: number;
27
+ optional?: boolean;
28
+ };
29
+ export type ImageField = {
30
+ kind: "image";
31
+ label: string;
32
+ help?: string;
33
+ ratio?: string;
34
+ /** Most characters in the alt text. Default `DEFAULT_ALT_MAX` (200). */
35
+ altMax?: number;
36
+ };
37
+ /** The alt text's length limit when the field sets none: room for a real description, short enough to listen to. */
38
+ export declare const DEFAULT_ALT_MAX = 200;
39
+ export declare const altMaxOf: (field: ImageField) => number;
40
+ export type GroupField = {
41
+ kind: "group";
42
+ label: string;
43
+ fields: Record<string, Field>;
44
+ };
45
+ export type ListField = {
46
+ kind: "list";
47
+ label: string;
48
+ itemLabel: string;
49
+ /** Plural of `itemLabel` for summaries ("2 spørgsmål"). Default: the same word. */
50
+ plural?: string;
51
+ item: Record<string, Field>;
52
+ min?: number;
53
+ max?: number;
54
+ /** Field shown as the item's name in the editor ("Slet spørgsmålet 'X'?") */
55
+ titleField?: string;
56
+ /**
57
+ * A list of plain strings (`- tekst` in YAML): set `scalar` (use `f.textList`) and leave `item` empty. The item
58
+ * itself is the text, so its ref is e.g. "hero.tillid.2".
59
+ */
60
+ scalar?: TextField;
61
+ /** Name of an id field that new and duplicated items get a fresh value for (Astro's file() loader needs `id`). */
62
+ idField?: string;
63
+ /**
64
+ * Values given to new items, after the placeholders: hidden fields the editor does not show (e.g.
65
+ * `{ kategori: "undervisning" }`) or a better start value for a shown field (e.g. `{ enhed: "kr." }`).
66
+ */
67
+ defaults?: Record<string, unknown>;
68
+ /** The list may be missing in the YAML. */
69
+ optional?: boolean;
70
+ /** A number field in each item that holds its 1-based position, kept in step after every add, copy, move and delete. */
71
+ orderField?: string;
72
+ };
73
+ export type Field = TextField | NumberField | ImageField | GroupField | ListField;
74
+ export type Collection = {
75
+ label: string;
76
+ dir: string;
77
+ /** The entry is this one file in `dir` (e.g. "forside.yaml"). Without it, every `*.yaml` in `dir` is an entry. */
78
+ file?: string;
79
+ /**
80
+ * "list": the file is a list at the top level (`- id: ...`). `fields` then has exactly one list field, and its key
81
+ * stands for the whole file in refs and data (e.g. "punkter.2.svar" is item 2 of the file).
82
+ */
83
+ root?: "list";
84
+ fields: Record<string, Field>;
85
+ };
86
+ export type CmsConfig = {
87
+ site: string;
88
+ collections: Record<string, Collection>;
89
+ };
90
+ /** Image value as stored in YAML. `src` is relative to the YAML file, as Astro's image() expects. */
91
+ export type ImageValue = {
92
+ src: string;
93
+ alt: string;
94
+ fokus?: {
95
+ x: number;
96
+ y: number;
97
+ };
98
+ };
99
+ /** An image value with its `src` as `Img`. */
100
+ export type ImageData<Img = string> = {
101
+ src: Img;
102
+ alt: string;
103
+ fokus?: {
104
+ x: number;
105
+ y: number;
106
+ };
107
+ };
108
+ type IsOptional<F> = F extends {
109
+ optional: true;
110
+ } ? true : false;
111
+ /** The position number of a list with `orderField`, optional in the CMS's own schema (the site may require it). */
112
+ export type OrderData<L> = L extends {
113
+ orderField: infer O extends string;
114
+ } ? (string extends O ? {} : {
115
+ [K in O]?: number;
116
+ }) : {};
117
+ type Simplify<T> = {
118
+ [K in keyof T]: T[K];
119
+ } & {};
120
+ /** The value of one field. */
121
+ export type FieldValue<F, Img = string> = F extends {
122
+ kind: "text";
123
+ } ? string : F extends {
124
+ kind: "number";
125
+ } ? number : F extends {
126
+ kind: "image";
127
+ } ? ImageData<Img> : F extends {
128
+ kind: "group";
129
+ fields: infer G;
130
+ } ? FieldsValue<G, Img> : F extends {
131
+ kind: "list";
132
+ scalar: object;
133
+ } ? string[] : F extends {
134
+ kind: "list";
135
+ item: infer I;
136
+ } ? Simplify<FieldsValue<I, Img> & OrderData<F>>[] : unknown;
137
+ /** The value of a record of fields: an optional field (`optional: true`) is an optional key. */
138
+ export type FieldsValue<G, Img = string> = Simplify<{
139
+ -readonly [K in keyof G as IsOptional<G[K]> extends true ? never : K]: FieldValue<G[K], Img>;
140
+ } & {
141
+ -readonly [K in keyof G as IsOptional<G[K]> extends true ? K : never]?: FieldValue<G[K], Img>;
142
+ }>;
143
+ /** The list field of a `root: "list"` collection. */
144
+ export type RootList<C> = C extends {
145
+ root: "list";
146
+ fields: infer Fs;
147
+ } ? Fs[keyof Fs] : never;
148
+ /**
149
+ * The data of one Astro entry of a collection: the page, or for a root list one item (Astro's file() loader gives
150
+ * one entry per item). Without the fields `extend` adds.
151
+ */
152
+ export type CollectionData<C, Img = string> = C extends {
153
+ root: "list";
154
+ } ? RootList<C> extends {
155
+ item: infer I;
156
+ } ? Simplify<FieldsValue<I, Img> & OrderData<RootList<C>>> : never : C extends {
157
+ fields: infer Fs;
158
+ } ? FieldsValue<Fs, Img> : never;
159
+ type Opts<T> = Omit<T, "kind" | "label">;
160
+ type ListOpts = Partial<Omit<ListField, "kind" | "label" | "itemLabel" | "item">>;
161
+ /**
162
+ * Field builders. The options are `const` type parameters, so `optional: true` and `orderField: "order"` stay
163
+ * literal in the type; that is what makes a field optional or adds the position number in the data type.
164
+ */
165
+ export declare const f: {
166
+ text: <const O extends Opts<TextField> = {}>(label: string, o?: O) => TextField & O & {
167
+ kind: "text";
168
+ };
169
+ number: <const O extends Opts<NumberField> = {}>(label: string, o?: O) => NumberField & O & {
170
+ kind: "number";
171
+ };
172
+ image: <const O extends Opts<ImageField> = {}>(label: string, o?: O) => ImageField & O & {
173
+ kind: "image";
174
+ };
175
+ group: <const G extends Record<string, Field>>(label: string, fields: G) => Omit<GroupField, "fields"> & {
176
+ fields: G;
177
+ };
178
+ list: <const I extends Record<string, Field>, const O extends ListOpts = {}>(label: string, itemLabel: string, item: I, o?: O) => Omit<ListField, "item"> & O & {
179
+ item: I;
180
+ };
181
+ /** A list of plain strings. `scalar` options are those of a text field (max length per item, placeholders, ...). */
182
+ textList: <const S extends Opts<TextField> = {}, const O extends Omit<ListOpts, "scalar"> = {}>(label: string, itemLabel: string, scalar?: S, o?: O) => Omit<ListField, "item" | "scalar"> & O & {
183
+ item: {};
184
+ scalar: TextField & S;
185
+ };
186
+ };
187
+ /** The site's CMS config. Generic, so the collections keep their field types (see `CollectionData`). */
188
+ export declare const defineCms: <const C extends CmsConfig>(c: C) => C;
189
+ /** The one key of a `root: "list"` collection, or undefined for an ordinary collection. */
190
+ export declare function rootKey(c: Collection): string | undefined;
191
+ /** What the editor and the schemas see for a parsed YAML value: for a root list, the list under its key. */
192
+ export declare const toView: (c: Collection, js: unknown) => unknown;
193
+ /** Path inside the YAML document for a field path of the view (the root key is dropped for a root list). */
194
+ export declare const docPath: <T>(c: Collection, parts: T[]) => T[];
195
+ /**
196
+ * The entry of a collection with `file`, as the attribute helpers want it: `{ collection, id }`. Astro lower-cases
197
+ * ids, so `gratisSamtale.yaml` gives "gratissamtale". Use it for a root list, whose items are separate Astro entries
198
+ * but share one file: `item(entryOf(cms, "faq"), "punkter", i)`.
199
+ */
200
+ export declare function entryOf(config: CmsConfig, name: string): {
201
+ collection: string;
202
+ id: string;
203
+ };
204
+ /**
205
+ * "hero.titel" or "faq.punkter.2.svar" → the field definition at that path, or undefined if the path is
206
+ * not editable. A path ending in a list index ("faq.punkter.2") gives a group with the item's fields.
207
+ */
208
+ export declare function fieldAt(fields: Record<string, Field>, path: string): Field | undefined;
209
+ /**
210
+ * The items of a root list from Astro's getCollection(), in file order, each with its position in the file (the
211
+ * index the CMS refs use: `item(entryOf(cms, "faq"), "punkter", index)`). getCollection() does not keep the file's
212
+ * order, so the list needs `orderField`: the CMS keeps it equal to the position (1, 2, 3 …) after every change, and
213
+ * refuses to save or publish a file where it is not (see orderIssues()).
214
+ */
215
+ export declare function inFileOrder<T extends {
216
+ data: Record<string, unknown>;
217
+ }>(config: CmsConfig, name: string, entries: T[]): {
218
+ entry: T;
219
+ index: number;
220
+ }[];
221
+ /**
222
+ * Lists with `orderField` must number their items 1, 2, 3 … in the order they stand in the file, or the page (which
223
+ * sorts by the number) and the CMS (which edits by position) would point at different items. Returns Danish problems.
224
+ */
225
+ export declare function orderIssues(fields: Record<string, Field>, value: unknown): string[];
226
+ /** False for a text that must not be typed on the page (see `TextField.inline`). */
227
+ export declare const isInlineEditable: (field: Field | undefined) => boolean;
228
+ /** A placeholder name: letters, digits, "-" and "_" (e.g. "klippekort-5"). */
229
+ export declare const PLACEHOLDER_NAME: RegExp;
230
+ /** The placeholders written in a text, in order, without braces: "Pris {modul}, {timepris}" → ["modul", "timepris"]. */
231
+ export declare const placeholdersIn: (text: string) => string[];
232
+ /**
233
+ * Danish problems with the placeholders in a text, or [] if it is fine. Used by the schema (on save and in the
234
+ * build) and by the editor (while typing), so both say the same thing.
235
+ */
236
+ export declare function placeholderIssues(text: string, allowed: readonly string[]): string[];
237
+ export {};
package/dist/fields.js ADDED
@@ -0,0 +1,140 @@
1
+ // Field definitions without Zod, so the editor (browser) can import them too.
2
+ /** The alt text's length limit when the field sets none: room for a real description, short enough to listen to. */
3
+ export const DEFAULT_ALT_MAX = 200;
4
+ export const altMaxOf = (field) => field.altMax ?? DEFAULT_ALT_MAX;
5
+ /**
6
+ * Field builders. The options are `const` type parameters, so `optional: true` and `orderField: "order"` stay
7
+ * literal in the type; that is what makes a field optional or adds the position number in the data type.
8
+ */
9
+ export const f = {
10
+ text: (label, o) => ({ kind: "text", label, ...o }),
11
+ number: (label, o) => ({ kind: "number", label, ...o }),
12
+ image: (label, o) => ({ kind: "image", label, ...o }),
13
+ group: (label, fields) => ({ kind: "group", label, fields }),
14
+ list: (label, itemLabel, item, o) => ({ kind: "list", label, itemLabel, item, ...o }),
15
+ /** A list of plain strings. `scalar` options are those of a text field (max length per item, placeholders, ...). */
16
+ textList: (label, itemLabel, scalar, o) => ({ kind: "list", label, itemLabel, item: {}, scalar: { kind: "text", label: itemLabel, ...scalar }, ...o }),
17
+ };
18
+ /** The site's CMS config. Generic, so the collections keep their field types (see `CollectionData`). */
19
+ export const defineCms = (c) => c;
20
+ /** The one key of a `root: "list"` collection, or undefined for an ordinary collection. */
21
+ export function rootKey(c) {
22
+ if (c.root !== "list")
23
+ return undefined;
24
+ const keys = Object.keys(c.fields);
25
+ if (keys.length !== 1 || c.fields[keys[0]].kind !== "list")
26
+ throw new Error('A root: "list" collection needs exactly one field, and it must be a list');
27
+ return keys[0];
28
+ }
29
+ /** What the editor and the schemas see for a parsed YAML value: for a root list, the list under its key. */
30
+ export const toView = (c, js) => {
31
+ const key = rootKey(c);
32
+ return key ? { [key]: js } : js;
33
+ };
34
+ /** Path inside the YAML document for a field path of the view (the root key is dropped for a root list). */
35
+ export const docPath = (c, parts) => (rootKey(c) ? parts.slice(1) : parts);
36
+ /**
37
+ * The entry of a collection with `file`, as the attribute helpers want it: `{ collection, id }`. Astro lower-cases
38
+ * ids, so `gratisSamtale.yaml` gives "gratissamtale". Use it for a root list, whose items are separate Astro entries
39
+ * but share one file: `item(entryOf(cms, "faq"), "punkter", i)`.
40
+ */
41
+ export function entryOf(config, name) {
42
+ const c = Object.hasOwn(config.collections, name) ? config.collections[name] : undefined;
43
+ if (!c?.file)
44
+ throw new Error(`Collection "${name}" has no "file", so it has no single entry`);
45
+ return { collection: name, id: c.file.replace(/\.ya?ml$/i, "").toLowerCase() };
46
+ }
47
+ /**
48
+ * "hero.titel" or "faq.punkter.2.svar" → the field definition at that path, or undefined if the path is
49
+ * not editable. A path ending in a list index ("faq.punkter.2") gives a group with the item's fields.
50
+ */
51
+ export function fieldAt(fields, path) {
52
+ const parts = path.split(".");
53
+ let scope = fields;
54
+ let current;
55
+ for (let i = 0; i < parts.length; i++) {
56
+ // Own keys only, so "__proto__", "constructor" and the like never resolve to prototype members.
57
+ if (!scope || !Object.hasOwn(scope, parts[i]))
58
+ return undefined;
59
+ current = scope[parts[i]];
60
+ if (!current || typeof current !== "object")
61
+ return undefined;
62
+ if (current.kind === "group")
63
+ scope = current.fields;
64
+ else if (current.kind === "list") {
65
+ const idx = parts[i + 1];
66
+ if (idx === undefined)
67
+ return current;
68
+ if (!/^\d+$/.test(idx))
69
+ return undefined;
70
+ i++;
71
+ if (current.scalar)
72
+ return i === parts.length - 1 ? current.scalar : undefined;
73
+ if (i === parts.length - 1)
74
+ return { kind: "group", label: current.itemLabel, fields: current.item };
75
+ scope = current.item;
76
+ }
77
+ else
78
+ scope = undefined;
79
+ }
80
+ return current;
81
+ }
82
+ /**
83
+ * The items of a root list from Astro's getCollection(), in file order, each with its position in the file (the
84
+ * index the CMS refs use: `item(entryOf(cms, "faq"), "punkter", index)`). getCollection() does not keep the file's
85
+ * order, so the list needs `orderField`: the CMS keeps it equal to the position (1, 2, 3 …) after every change, and
86
+ * refuses to save or publish a file where it is not (see orderIssues()).
87
+ */
88
+ export function inFileOrder(config, name, entries) {
89
+ const c = Object.hasOwn(config.collections, name) ? config.collections[name] : undefined;
90
+ const key = c ? rootKey(c) : undefined;
91
+ const list = key ? c.fields[key] : undefined;
92
+ if (list?.kind !== "list" || !list.orderField) {
93
+ throw new Error(`inFileOrder("${name}"): needs a root list with orderField, because getCollection() does not keep the file order`);
94
+ }
95
+ const order = list.orderField;
96
+ return entries.map((entry) => ({ entry, index: Number(entry.data[order]) - 1 })).sort((a, b) => a.index - b.index);
97
+ }
98
+ /**
99
+ * Lists with `orderField` must number their items 1, 2, 3 … in the order they stand in the file, or the page (which
100
+ * sorts by the number) and the CMS (which edits by position) would point at different items. Returns Danish problems.
101
+ */
102
+ export function orderIssues(fields, value) {
103
+ const issues = [];
104
+ const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : undefined);
105
+ for (const [k, def] of Object.entries(fields)) {
106
+ const v = obj(value)?.[k];
107
+ if (def.kind === "group")
108
+ issues.push(...orderIssues(def.fields, v));
109
+ if (def.kind !== "list" || !Array.isArray(v))
110
+ continue;
111
+ if (def.orderField && v.some((item, i) => obj(item)?.[def.orderField] !== i + 1)) {
112
+ issues.push(`Rækkefølgen i "${def.label}" passer ikke med filen: ${def.orderField} skal være 1, 2, 3 … i den rækkefølge, de står. Kontakt Sinding Mind.`);
113
+ }
114
+ if (!def.scalar)
115
+ for (const item of v)
116
+ issues.push(...orderIssues(def.item, item));
117
+ }
118
+ return issues;
119
+ }
120
+ /** False for a text that must not be typed on the page (see `TextField.inline`). */
121
+ export const isInlineEditable = (field) => field?.kind === "text" && field.inline !== false && !field.placeholders?.length;
122
+ /** A placeholder name: letters, digits, "-" and "_" (e.g. "klippekort-5"). */
123
+ export const PLACEHOLDER_NAME = /^[A-Za-z0-9_-]+$/;
124
+ /** The placeholders written in a text, in order, without braces: "Pris {modul}, {timepris}" → ["modul", "timepris"]. */
125
+ export const placeholdersIn = (text) => [...text.matchAll(/\{([^{}]*)\}/g)].map((m) => m[1]);
126
+ /**
127
+ * Danish problems with the placeholders in a text, or [] if it is fine. Used by the schema (on save and in the
128
+ * build) and by the editor (while typing), so both say the same thing.
129
+ */
130
+ export function placeholderIssues(text, allowed) {
131
+ const issues = [];
132
+ const unknown = [...new Set(placeholdersIn(text).filter((n) => !allowed.includes(n)))];
133
+ if (unknown.length) {
134
+ issues.push(`Ukendt pladsholder: ${unknown.map((n) => `{${n}}`).join(", ")}. Brug kun ${allowed.map((n) => `{${n}}`).join(", ")}`);
135
+ }
136
+ // A brace that is not part of a {name} is most often a placeholder that lost its other half.
137
+ if (/[{}]/.test(text.replace(/\{[^{}]*\}/g, "")))
138
+ issues.push("Der er en { eller } for meget. En pladsholder skrives som {navn}");
139
+ return issues;
140
+ }
@@ -0,0 +1,16 @@
1
+ import type { AstroIntegration } from "astro";
2
+ export type CmsOptions = {
3
+ /** Origin of the editor that frames the preview. CMS_EDITOR_ORIGIN (set by the runner) takes precedence. */
4
+ editorOrigin?: string;
5
+ /**
6
+ * Keep CSS animations and transitions while editing. Default false: in the preview they finish at once (the
7
+ * end state is shown), so text does not move or fade while the customer clicks it.
8
+ */
9
+ keepMotion?: boolean;
10
+ };
11
+ /**
12
+ * The editing-mode stylesheet. Animations jump to their end state (fill-mode is kept, so a fade-in ends visible),
13
+ * transitions are instant, and smooth scrolling is off so the editor can scroll straight to a field.
14
+ */
15
+ export declare const EDITING_CSS: string;
16
+ export default function cms(options?: CmsOptions): AstroIntegration;
package/dist/index.js ADDED
@@ -0,0 +1,64 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { foldEditingCalls } from "./editing-flag.js";
3
+ const DEFAULT_EDITOR_ORIGIN = "http://localhost:4500";
4
+ /**
5
+ * The editing-mode stylesheet. Animations jump to their end state (fill-mode is kept, so a fade-in ends visible),
6
+ * transitions are instant, and smooth scrolling is off so the editor can scroll straight to a field.
7
+ */
8
+ export const EDITING_CSS = "html[data-cms-editing] *,html[data-cms-editing] *::before,html[data-cms-editing] *::after{" +
9
+ "animation-duration:0s!important;animation-delay:0s!important;animation-iteration-count:1!important;" +
10
+ "transition-duration:0s!important;transition-delay:0s!important;scroll-behavior:auto!important}";
11
+ export default function cms(options = {}) {
12
+ return {
13
+ name: "@sindingmind/cms-astro",
14
+ hooks: {
15
+ "astro:config:setup": ({ command, updateConfig, injectScript }) => {
16
+ const preview = command === "dev" && process.env.CMS_PREVIEW === "1";
17
+ updateConfig({ vite: { plugins: [virtualModule(preview), editingFlag(preview)] } });
18
+ if (!preview)
19
+ return;
20
+ const editorOrigin = originOf(process.env.CMS_EDITOR_ORIGIN || options.editorOrigin || DEFAULT_EDITOR_ORIGIN);
21
+ // Runs before the site's own scripts, so they can skip animations while editing (isCmsEditing() or the
22
+ // attribute), and before the first paint, so CSS motion is off from the start.
23
+ const motion = options.keepMotion ? "" : `var s=document.createElement("style");s.setAttribute("data-cms-editing-style","");s.textContent=${JSON.stringify(EDITING_CSS)};document.head.append(s);`;
24
+ injectScript("head-inline", `document.documentElement.setAttribute("data-cms-editing","");${motion}window.__CMS__=${JSON.stringify({ editorOrigin })};`);
25
+ // The bridge sits next to this module: bridge.js in the published package (dist/), bridge.ts from source.
26
+ const bridge = new URL(import.meta.url.endsWith(".ts") ? "./bridge.ts" : "./bridge.js", import.meta.url);
27
+ injectScript("page", `import ${JSON.stringify(fileURLToPath(bridge))};`);
28
+ },
29
+ },
30
+ };
31
+ }
32
+ /** Accepts only a bare origin ("http://localhost:4500"), because it ends up in an inline script. */
33
+ function originOf(value) {
34
+ const origin = new URL(value).origin;
35
+ if (origin !== value.replace(/\/$/, ""))
36
+ throw new Error(`CMS editor origin must be a bare origin, got "${value}"`);
37
+ return origin;
38
+ }
39
+ /**
40
+ * In a build, every `isCmsEditing()` call in the site's code becomes the literal `false` (see editing-flag.ts), so
41
+ * the bundler can drop the check and `attrs.ts` even when several page scripts import it. Runs after the other
42
+ * plugins (`enforce: "post"`), so it sees JavaScript (TypeScript and .astro already compiled).
43
+ */
44
+ function editingFlag(preview) {
45
+ return {
46
+ name: "sinding-cms-editing-flag",
47
+ apply: "build",
48
+ enforce: "post",
49
+ transform(code, id) {
50
+ if (id.startsWith("\0") || id.includes("/node_modules/"))
51
+ return undefined;
52
+ const folded = foldEditingCalls(code, (c) => this.parse(c), preview);
53
+ return folded === undefined ? undefined : { code: folded, map: null };
54
+ },
55
+ };
56
+ }
57
+ function virtualModule(preview) {
58
+ const id = "virtual:sinding-cms";
59
+ return {
60
+ name: "sinding-cms-virtual",
61
+ resolveId: (s) => (s === id ? `\0${id}` : undefined),
62
+ load: (s) => (s === `\0${id}` ? `export const preview = ${preview};` : undefined),
63
+ };
64
+ }
@@ -0,0 +1,39 @@
1
+ import { z } from "astro/zod";
2
+ import { type Collection, type Field, type FieldValue, type RootList } from "./fields.ts";
3
+ export * from "./fields.ts";
4
+ export type ImageSchema = () => z.ZodTypeAny;
5
+ /** What an image's `src` becomes with this `image` helper: a string in the file API, image metadata in Astro. */
6
+ export type ImageOf<I> = I extends () => infer S ? (S extends z.ZodTypeAny ? z.output<S> : unknown) : unknown;
7
+ /** The schema of one field. */
8
+ export type ZodFor<F, Img> = F extends {
9
+ optional: true;
10
+ } ? z.ZodOptional<z.ZodType<FieldValue<F, Img>>> : z.ZodType<FieldValue<F, Img>>;
11
+ /** The shape of a ZodObject for a record of fields. */
12
+ export type ShapeOf<G, Img> = {
13
+ -readonly [K in keyof G]: ZodFor<G[K], Img>;
14
+ };
15
+ /** The position number's schema in a list item (`orderField`). */
16
+ type OrderShape<L> = L extends {
17
+ orderField: infer O extends string;
18
+ } ? (string extends O ? {} : {
19
+ [K in O]: z.ZodOptional<z.ZodNumber>;
20
+ }) : {};
21
+ /** The schema of a collection's Astro entry: the page, or one item of a root list. */
22
+ export type CollectionSchema<C, Img> = C extends {
23
+ root: "list";
24
+ } ? RootList<C> extends {
25
+ item: infer I;
26
+ } ? z.ZodObject<ShapeOf<I, Img> & OrderShape<RootList<C>>> : never : C extends {
27
+ fields: infer Fs;
28
+ } ? z.ZodObject<ShapeOf<Fs, Img>> : never;
29
+ /** The Zod schema of one field, typed from the definition. */
30
+ export declare function toZod<F extends Field, I extends ImageSchema>(field: F, image: I): ZodFor<F, ImageOf<I>>;
31
+ /** The ZodObject for a record of fields (a page, a group), typed from the definitions. */
32
+ export declare function objectOf<G extends Record<string, Field>, I extends ImageSchema>(fields: G, image: I, label?: string): z.ZodObject<ShapeOf<G, ImageOf<I>>>;
33
+ /**
34
+ * The schema Astro needs for one collection. A page (`file`, or a folder of files) is validated as a whole. A root
35
+ * list is loaded by Astro's file() loader, which validates each item on its own, so this is the item's schema.
36
+ * Fields the CMS does not show (ids, categories, flags) are not in it: add them with `.extend({...})`, or Zod drops
37
+ * them from the data.
38
+ */
39
+ export declare function schemaOf<C extends Collection, I extends ImageSchema>(collection: C, image: I): CollectionSchema<C, ImageOf<I>>;
package/dist/schema.js ADDED
@@ -0,0 +1,88 @@
1
+ // One field definition gives both the Zod schema (used by Astro at build and by the file API on save)
2
+ // and the UI metadata the editor needs. Definitions are plain JSON so they can be sent to the editor.
3
+ import { z } from "astro/zod";
4
+ import { altMaxOf, placeholderIssues, rootKey } from "./fields.js";
5
+ export * from "./fields.js";
6
+ /** Danish messages for a missing value or one of the wrong type (Zod's own are English). */
7
+ const typed = (label, what) => ({
8
+ error: (issue) => (issue.input === undefined ? `${label} mangler` : `${label} skal være ${what}`),
9
+ });
10
+ /** The Zod schema of one field, typed from the definition. */
11
+ export function toZod(field, image) {
12
+ return zodOf(field, image);
13
+ }
14
+ function zodOf(field, image) {
15
+ switch (field.kind) {
16
+ case "text": {
17
+ let s = z.string(typed(field.label, "tekst")).trim();
18
+ // An optional text may be missing or empty (the site then leaves it out); a required one may not be empty.
19
+ if (!field.optional)
20
+ s = s.min(1, `${field.label} må ikke være tom`);
21
+ if (field.max)
22
+ s = s.max(field.max, `${field.label} må højst være ${field.max} tegn`);
23
+ const allowed = field.placeholders;
24
+ if (allowed?.length) {
25
+ s = s.superRefine((value, ctx) => {
26
+ for (const message of placeholderIssues(value, allowed))
27
+ ctx.addIssue({ code: "custom", message: `${field.label}: ${message}` });
28
+ });
29
+ }
30
+ return field.optional ? s.optional() : s;
31
+ }
32
+ case "number": {
33
+ let s = z.number(typed(field.label, "et tal"));
34
+ if (field.min !== undefined)
35
+ s = s.min(field.min, `${field.label} skal være mindst ${field.min}`);
36
+ if (field.max !== undefined)
37
+ s = s.max(field.max, `${field.label} må højst være ${field.max}`);
38
+ return field.optional ? s.optional() : s;
39
+ }
40
+ case "image":
41
+ return z.object({
42
+ src: image(),
43
+ alt: z.string().trim().min(1, "Skriv en alt-tekst, der beskriver billedet")
44
+ .max(altMaxOf(field), `Alt-teksten til "${field.label}" må højst være ${altMaxOf(field)} tegn`),
45
+ // No default: "not chosen" (missing) is not the same as "the middle", and the CMS must never write a focus
46
+ // point the user did not set. fokus() in attrs.ts falls back to the middle for the page.
47
+ fokus: z.object({ x: z.number().min(0).max(100), y: z.number().min(0).max(100) }).optional(),
48
+ }, typed(field.label, "et billede"));
49
+ case "group":
50
+ return objectOfAny(field.fields, image, field.label);
51
+ case "list": {
52
+ let s = z.array(field.scalar ? zodOf(field.scalar, image) : itemOf(field, image), typed(`"${field.label}"`, "en liste"));
53
+ if (field.min !== undefined)
54
+ s = s.min(field.min, `Der skal være mindst ${field.min} i "${field.label}"`);
55
+ if (field.max !== undefined)
56
+ s = s.max(field.max, `Der må højst være ${field.max} i "${field.label}"`);
57
+ return field.optional ? s.optional() : s;
58
+ }
59
+ }
60
+ }
61
+ /** The ZodObject for a record of fields (a page, a group), typed from the definitions. */
62
+ export function objectOf(fields, image, label) {
63
+ return objectOfAny(fields, image, label);
64
+ }
65
+ function objectOfAny(fields, image, label) {
66
+ const shape = Object.fromEntries(Object.entries(fields).map(([k, v]) => [k, zodOf(v, image)]));
67
+ return label ? z.object(shape, typed(label, "en gruppe af felter")) : z.object(shape);
68
+ }
69
+ /** One item of a list of objects. The position number (`orderField`) is kept in the data, so the site can sort by it. */
70
+ function itemOf(list, image) {
71
+ const item = objectOfAny(list.item, image, list.itemLabel);
72
+ return list.orderField ? item.extend({ [list.orderField]: z.number().int().min(1).optional() }) : item;
73
+ }
74
+ /**
75
+ * The schema Astro needs for one collection. A page (`file`, or a folder of files) is validated as a whole. A root
76
+ * list is loaded by Astro's file() loader, which validates each item on its own, so this is the item's schema.
77
+ * Fields the CMS does not show (ids, categories, flags) are not in it: add them with `.extend({...})`, or Zod drops
78
+ * them from the data.
79
+ */
80
+ export function schemaOf(collection, image) {
81
+ const key = rootKey(collection);
82
+ if (!key)
83
+ return objectOfAny(collection.fields, image);
84
+ const list = collection.fields[key];
85
+ if (list.kind !== "list" || list.scalar)
86
+ throw new Error('Astro\'s file() loader needs a root list of objects (each with an "id")');
87
+ return itemOf(list, image);
88
+ }