@lvl99dotcom/edaha.md 0.0.0-stage → 0.2.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.
Files changed (52) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +13 -2
  3. package/dist/cli/bin.d.ts +2 -0
  4. package/dist/cli/bin.js +9 -0
  5. package/dist/cli/index.d.ts +71 -0
  6. package/dist/cli/index.js +149 -0
  7. package/dist/embeds/blocks/index.d.ts +59 -0
  8. package/dist/embeds/blocks/index.js +103 -0
  9. package/dist/embeds/index.d.ts +143 -0
  10. package/dist/embeds/index.js +411 -0
  11. package/dist/embeds/types/index.d.ts +117 -0
  12. package/dist/embeds/types/index.js +1 -0
  13. package/dist/generator/article/index.d.ts +151 -0
  14. package/dist/generator/article/index.js +325 -0
  15. package/dist/generator/build/index.d.ts +109 -0
  16. package/dist/generator/build/index.js +363 -0
  17. package/dist/generator/config/index.d.ts +96 -0
  18. package/dist/generator/config/index.js +298 -0
  19. package/dist/generator/configFile/index.d.ts +58 -0
  20. package/dist/generator/configFile/index.js +122 -0
  21. package/dist/generator/fields/index.d.ts +93 -0
  22. package/dist/generator/fields/index.js +186 -0
  23. package/dist/generator/format/index.d.ts +92 -0
  24. package/dist/generator/format/index.js +177 -0
  25. package/dist/generator/lists/index.d.ts +63 -0
  26. package/dist/generator/lists/index.js +133 -0
  27. package/dist/generator/markdown/index.d.ts +25 -0
  28. package/dist/generator/markdown/index.js +62 -0
  29. package/dist/generator/metadata/index.d.ts +150 -0
  30. package/dist/generator/metadata/index.js +361 -0
  31. package/dist/generator/metadataGroups/index.d.ts +45 -0
  32. package/dist/generator/metadataGroups/index.js +169 -0
  33. package/dist/generator/slug/index.d.ts +26 -0
  34. package/dist/generator/slug/index.js +57 -0
  35. package/dist/generator/templates/index.d.ts +88 -0
  36. package/dist/generator/templates/index.js +175 -0
  37. package/dist/generator/types/index.d.ts +186 -0
  38. package/dist/generator/types/index.js +1 -0
  39. package/dist/generator/urls/index.d.ts +50 -0
  40. package/dist/generator/urls/index.js +77 -0
  41. package/dist/index.d.ts +8 -0
  42. package/dist/index.js +9 -0
  43. package/dist/theme/index.d.ts +8 -0
  44. package/dist/theme/index.js +9 -0
  45. package/package.json +64 -3
  46. package/theme/static/base.css +328 -0
  47. package/theme/templates/article/list.njk +69 -0
  48. package/theme/templates/article/single.njk +64 -0
  49. package/theme/templates/layouts/html.njk +72 -0
  50. package/theme/templates/layouts/rssfeed.njk +28 -0
  51. package/theme/templates/page/home.njk +16 -0
  52. package/theme/templates/page/single.njk +18 -0
@@ -0,0 +1,62 @@
1
+ import MarkdownIt from "markdown-it";
2
+ import { isRelativeUrl } from "../format/index.js";
3
+ import { headingIds } from "../slug/index.js";
4
+ /**
5
+ * Create the markdown renderer. Raw HTML is allowed, as articles are written by trusted authors and embeds are HTML.
6
+ * Relative link and image URLs are resolved against the article's URL, so they work on any page (e.g. lists), and
7
+ * root-relative ones (e.g. `/docs/`) are put under the website's base URL.
8
+ * Headings get IDs from their text (see `headingIds`), so they can be linked to, e.g. `#this-is-an-example`.
9
+ * Typographer (curly quotes, dashes) is on for the website and off for the editor, so text round-trips unchanged.
10
+ *
11
+ * @example
12
+ * const markdown = createMarkdown();
13
+ * renderMarkdown(markdown, "![A](a.png)", "/news/article/hello/"); // '<p><img src="/news/article/hello/a.png" alt="A"></p>\n'
14
+ */
15
+ export const createMarkdown = ({ typographer = true } = {}) => {
16
+ const markdown = new MarkdownIt({ html: true, typographer });
17
+ markdown.core.ruler.push("resolve_relative_urls", (state) => {
18
+ const { baseUrl, siteBaseUrl } = state.env;
19
+ for (const block of state.tokens) {
20
+ for (const token of block.children ?? []) {
21
+ const attribute = token.type === "image"
22
+ ? "src"
23
+ : token.type === "link_open"
24
+ ? "href"
25
+ : undefined;
26
+ if (!attribute)
27
+ continue;
28
+ // markdown-it always sets src on images and href on links
29
+ const url = String(token.attrGet(attribute));
30
+ if (isRelativeUrl(url))
31
+ token.attrSet(attribute, baseUrl + url);
32
+ else if (siteBaseUrl && /^\/(?!\/)/.test(url))
33
+ token.attrSet(attribute, siteBaseUrl + url);
34
+ }
35
+ }
36
+ });
37
+ markdown.core.ruler.push("heading_ids", (state) => {
38
+ const headings = state.tokens.flatMap((token, i) => token.type === "heading_open"
39
+ ? [{ token, inline: state.tokens[i + 1] }]
40
+ : []);
41
+ // A heading's text, without its formatting or HTML tags (a heading's inline token always has children)
42
+ const texts = headings.map(({ inline }) => inline.children
43
+ .filter((child) => child.type === "text" || child.type === "code_inline")
44
+ .map((child) => child.content)
45
+ .join(""));
46
+ const ids = headingIds(texts);
47
+ headings.forEach(({ token }, i) => {
48
+ const id = ids[i];
49
+ if (id)
50
+ token.attrSet("id", id);
51
+ });
52
+ });
53
+ return markdown;
54
+ };
55
+ /**
56
+ * Render markdown to HTML, resolving relative URLs against a folder URL and putting root-relative ones under the
57
+ * website's base URL.
58
+ *
59
+ * @example
60
+ * renderMarkdown(markdown, "[Docs](/docs/)", "/edaha.md/news/hello/", "/edaha.md"); // '<p><a href="/edaha.md/docs/">Docs</a></p>\n'
61
+ */
62
+ export const renderMarkdown = (markdown, source, baseUrl, siteBaseUrl = "") => markdown.render(source, { baseUrl, siteBaseUrl });
@@ -0,0 +1,150 @@
1
+ import { Ajv, type ErrorObject } from "ajv";
2
+ /** The kinds of field the editor can show for a metadata value (the key under `$edahaField` that configures it) */
3
+ export declare const FIELD_KINDS: readonly ["text", "email", "url", "tel", "color", "date", "time", "datetime-local", "number", "range", "textarea", "select", "checkbox", "radio", "file"];
4
+ /** A kind of field the editor can show */
5
+ export type FieldKind = (typeof FIELD_KINDS)[number];
6
+ /** A choice in a select or radio field */
7
+ export interface FieldChoice {
8
+ value: string | number | boolean;
9
+ title?: string | undefined;
10
+ description?: string | undefined;
11
+ }
12
+ /**
13
+ * How the editor shows a metadata value (`$edahaField`): an optional label, description and extra information, and
14
+ * exactly one field kind, set to `true` or to its options (e.g. `{ file: { accept: "image/*" } }`).
15
+ */
16
+ export interface EdahaField {
17
+ title?: string | undefined;
18
+ description?: string | undefined;
19
+ info?: string | undefined;
20
+ [kind: string]: unknown;
21
+ }
22
+ /** A custom metadata field's JSON Schema, with `$edahaField` saying how the editor shows it */
23
+ export interface MetadataSchema {
24
+ title?: string | undefined;
25
+ description?: string | undefined;
26
+ type?: string | string[] | undefined;
27
+ properties?: Record<string, MetadataSchema> | undefined;
28
+ items?: MetadataSchema | undefined;
29
+ required?: string[] | undefined;
30
+ enum?: unknown[] | undefined;
31
+ $edahaField?: EdahaField | undefined;
32
+ [keyword: string]: unknown;
33
+ }
34
+ /** Custom metadata fields' schemas, by the key their values are stored under in articles */
35
+ export type MetadataDefinitions = Record<string, MetadataSchema>;
36
+ /** The settings every article has, which custom metadata can't use as keys */
37
+ export declare const CORE_FIELDS: string[];
38
+ /** A problem with an article's metadata: an invalid value (an error) or a setting that isn't used (a warning) */
39
+ export interface MetadataProblem {
40
+ /** The value's path, e.g. "featured" or "images/2" */
41
+ path: string;
42
+ message: string;
43
+ level: "error" | "warning";
44
+ }
45
+ /**
46
+ * The kind of field an `$edahaField` configures.
47
+ *
48
+ * @example
49
+ * fieldKind({ title: "Image", file: { accept: "image/*" } }); // "file"
50
+ */
51
+ export declare const fieldKind: (field: EdahaField) => FieldKind;
52
+ /**
53
+ * Whether an `$edahaField` names a field kind (maps' and lists' may only set their group and labels).
54
+ *
55
+ * @example
56
+ * hasFieldKind({ group: "files" }); // false
57
+ */
58
+ export declare const hasFieldKind: (field: unknown) => boolean;
59
+ /**
60
+ * A field kind's options, e.g. `{ accept: "image/*" }` for `{ file: { accept: "image/*" } }` (none for `true`).
61
+ */
62
+ export declare const fieldOptions: (field: EdahaField) => Record<string, unknown>;
63
+ /**
64
+ * Check a schema has editor fields: objects need properties, lists need items (or one field for the whole list), and
65
+ * every value has an `$edahaField` with exactly one field kind. Objects' and lists' own `$edahaField` may set only their
66
+ * group, labels and conditions. Default values and conditions are checked too (see checkFieldExtensions). Throws an Error naming the schema's path.
67
+ *
68
+ * @example
69
+ * checkFieldSchema({ type: "string", $edahaField: { text: true } }, "metadata.subtitle");
70
+ */
71
+ export declare const checkFieldSchema: (schema: unknown, path: string) => void;
72
+ /**
73
+ * An ajv instance for metadata schemas: every error reported, formats like `uri` and `email` checked, and `$edahaField`
74
+ * allowed beside JSON Schema's own keywords.
75
+ */
76
+ export declare const createAjv: () => Ajv;
77
+ /**
78
+ * Read the config file's `metadata` setting: a map of keys to JSON Schemas with `$edahaField`s. Throws an Error if a
79
+ * key is a core field's name or isn't a usable name, or a schema has no editor fields or can't be compiled.
80
+ *
81
+ * @example
82
+ * parseMetadata({ featured: { type: "string", $edahaField: { file: { accept: "image/*" } } } });
83
+ */
84
+ export declare const parseMetadata: (value: unknown) => MetadataDefinitions;
85
+ /**
86
+ * The custom metadata fields an article type uses: those its `metadata` setting lists, none for `false`, or all when
87
+ * it has none.
88
+ *
89
+ * @example
90
+ * typeMetadataKeys({ featured: {...}, images: {...} }, ["featured"]); // ["featured"]
91
+ */
92
+ export declare const typeMetadataKeys: (definitions: MetadataDefinitions, typeMetadata: string[] | false | undefined) => string[];
93
+ /**
94
+ * Say what is wrong with a value in plain words, from an ajv error, e.g. "must be at most 10" or "must be an email
95
+ * address". Errors this doesn't know keep ajv's message.
96
+ *
97
+ * @example
98
+ * plainMessage({ keyword: "maximum", params: { limit: 10 }, ... }); // "must be at most 10"
99
+ */
100
+ export declare const plainMessage: (error: ErrorObject) => string;
101
+ /**
102
+ * Validates articles' custom metadata values against their schemas, compiling each schema once.
103
+ *
104
+ * @example
105
+ * const validator = new MetadataValidator(config.metadata);
106
+ * validator.validate("featured", 3); // [{ path: "featured", message: "must be string", level: "error" }]
107
+ */
108
+ export declare class MetadataValidator {
109
+ private readonly ajv;
110
+ private readonly compiled;
111
+ /** The custom metadata fields' schemas, by key */
112
+ readonly definitions: MetadataDefinitions;
113
+ constructor(definitions: MetadataDefinitions);
114
+ /** The problems with a value of a custom metadata field (none if it's valid) */
115
+ validate(key: string, value: unknown): MetadataProblem[];
116
+ }
117
+ /** An article's custom metadata: every value its type uses, and the problems found */
118
+ export interface ArticleMetadata {
119
+ /** The values of the custom fields the article's type uses (valid or not), by key */
120
+ values: Record<string, unknown>;
121
+ /** Invalid values (errors), and settings the type doesn't use or nobody defined (warnings) */
122
+ problems: MetadataProblem[];
123
+ }
124
+ /**
125
+ * Read an article's custom metadata from its settings: fill in default values and leave out hidden fields' values (see
126
+ * resolveFields), validate the values of the fields its type uses, and warn about values of fields its type doesn't use
127
+ * and settings that aren't core or defined.
128
+ *
129
+ * @param typeLabel - the type's plural label, for warnings, e.g. "News"
130
+ *
131
+ * @example
132
+ * articleMetadata({ date, featured: "a.png", oops: 1 }, ["featured"], validator, "News");
133
+ * // { values: { featured: "a.png" }, problems: [{ path: "oops", message: "isn't a known setting", level: "warning" }] }
134
+ */
135
+ export declare const articleMetadata: (settings: Record<string, unknown>, keys: string[], validator: MetadataValidator, typeLabel: string) => ArticleMetadata;
136
+ /**
137
+ * Make a value's file fields' relative file names into paths on the website (like `thumbnail`), following its
138
+ * schema's objects and lists.
139
+ *
140
+ * @example
141
+ * resolveFileFields({ $edahaField: { file: true } }, "photo.png", "/news/hello/"); // "/news/hello/photo.png"
142
+ */
143
+ export declare const resolveFileFields: (schema: MetadataSchema, value: unknown, articleUrl: string) => unknown;
144
+ /**
145
+ * An article's custom metadata for templates (`article.meta`): its type's valid values, with file fields as paths on
146
+ * the website. Values with errors are left out.
147
+ */
148
+ export declare const templateMetadata: (metadata: ArticleMetadata, definitions: MetadataDefinitions, articleUrl: string) => Record<string, unknown>;
149
+ /** Check a map key is used only for keys listed, for the type's `metadata` setting */
150
+ export declare const parseTypeMetadata: (value: unknown, what: string) => string[] | false | undefined;
@@ -0,0 +1,361 @@
1
+ import { Ajv } from "ajv";
2
+ import { fullFormats } from "ajv-formats/dist/formats.js";
3
+ import { checkFieldExtensions, resolveFields } from "../fields/index.js";
4
+ import { isRelativeUrl } from "../format/index.js";
5
+ /** The kinds of field the editor can show for a metadata value (the key under `$edahaField` that configures it) */
6
+ export const FIELD_KINDS = [
7
+ "text",
8
+ "email",
9
+ "url",
10
+ "tel",
11
+ "color",
12
+ "date",
13
+ "time",
14
+ "datetime-local",
15
+ "number",
16
+ "range",
17
+ "textarea",
18
+ "select",
19
+ "checkbox",
20
+ "radio",
21
+ "file",
22
+ ];
23
+ /** The settings every article has, which custom metadata can't use as keys */
24
+ export const CORE_FIELDS = [
25
+ "type",
26
+ "status",
27
+ "date",
28
+ "title",
29
+ "template",
30
+ "author",
31
+ "excerpt",
32
+ "thumbnail",
33
+ "attachments",
34
+ "tags",
35
+ ];
36
+ /** Metadata keys: a letter or underscore, then letters, digits, underscores or hyphens */
37
+ const KEY = /^[A-Za-z_][\w-]*$/;
38
+ /** Check a value is a map (not a list), throwing an Error naming it if not */
39
+ const asMap = (value, what) => {
40
+ if (!value || typeof value !== "object" || Array.isArray(value))
41
+ throw new Error(`${what} must be a map of settings`);
42
+ return value;
43
+ };
44
+ /**
45
+ * The kind of field an `$edahaField` configures.
46
+ *
47
+ * @example
48
+ * fieldKind({ title: "Image", file: { accept: "image/*" } }); // "file"
49
+ */
50
+ export const fieldKind = (field) => FIELD_KINDS.find((kind) => kind in field);
51
+ /**
52
+ * Whether an `$edahaField` names a field kind (maps' and lists' may only set their group and labels).
53
+ *
54
+ * @example
55
+ * hasFieldKind({ group: "files" }); // false
56
+ */
57
+ export const hasFieldKind = (field) => Boolean(field &&
58
+ typeof field === "object" &&
59
+ FIELD_KINDS.some((kind) => kind in field));
60
+ /**
61
+ * A field kind's options, e.g. `{ accept: "image/*" }` for `{ file: { accept: "image/*" } }` (none for `true`).
62
+ */
63
+ export const fieldOptions = (field) => {
64
+ const options = field[fieldKind(field)];
65
+ return options && typeof options === "object"
66
+ ? options
67
+ : {};
68
+ };
69
+ /**
70
+ * Check a schema has editor fields: objects need properties, lists need items (or one field for the whole list), and
71
+ * every value has an `$edahaField` with exactly one field kind. Objects' and lists' own `$edahaField` may set only their
72
+ * group, labels and conditions. Default values and conditions are checked too (see checkFieldExtensions). Throws an Error naming the schema's path.
73
+ *
74
+ * @example
75
+ * checkFieldSchema({ type: "string", $edahaField: { text: true } }, "metadata.subtitle");
76
+ */
77
+ export const checkFieldSchema = (schema, path) => {
78
+ const fields = asMap(schema, `"${path}"`);
79
+ if (fields.$edahaField !== undefined)
80
+ checkFieldExtensions(asMap(fields.$edahaField, `"${path}.$edahaField"`), `"${path}.$edahaField"`);
81
+ if (fields.type === "object") {
82
+ if (Array.isArray(fields.properties))
83
+ throw new Error(`"${path}.properties" must be a map of each property's name to its schema, not a list (remove the "-"s and put each schema under its property's name)`);
84
+ const properties = asMap(fields.properties, `"${path}.properties"`);
85
+ for (const [name, property] of Object.entries(properties))
86
+ checkFieldSchema(property, `${path}.properties.${name}`);
87
+ return;
88
+ }
89
+ // A list is edited item by item, unless one field edits it all (e.g. a select with `multiple`)
90
+ if (fields.type === "array" && !hasFieldKind(fields.$edahaField)) {
91
+ // A list of schemas describes each item in turn; the editor needs one schema for every item
92
+ if (Array.isArray(fields.items))
93
+ throw new Error(`"${path}.items" must be one schema for every item, not a list (remove the "-" before it)`);
94
+ checkFieldSchema(fields.items, `${path}.items`);
95
+ return;
96
+ }
97
+ const field = asMap(fields.$edahaField, `"${path}.$edahaField"`);
98
+ const kinds = FIELD_KINDS.filter((kind) => kind in field);
99
+ if (kinds.length !== 1)
100
+ throw new Error(`"${path}.$edahaField" must have exactly one field kind (${FIELD_KINDS.join(", ")}), not ${kinds.length ? kinds.join(" and ") : "none"}`);
101
+ };
102
+ /**
103
+ * An ajv instance for metadata schemas: every error reported, formats like `uri` and `email` checked, and `$edahaField`
104
+ * allowed beside JSON Schema's own keywords.
105
+ */
106
+ export const createAjv = () => {
107
+ const ajv = new Ajv({ allErrors: true, strict: false, formats: fullFormats });
108
+ ajv.addKeyword({ keyword: "$edahaField", schemaType: "object" });
109
+ return ajv;
110
+ };
111
+ /**
112
+ * Read the config file's `metadata` setting: a map of keys to JSON Schemas with `$edahaField`s. Throws an Error if a
113
+ * key is a core field's name or isn't a usable name, or a schema has no editor fields or can't be compiled.
114
+ *
115
+ * @example
116
+ * parseMetadata({ featured: { type: "string", $edahaField: { file: { accept: "image/*" } } } });
117
+ */
118
+ export const parseMetadata = (value) => {
119
+ if (value === undefined || value === null)
120
+ return {};
121
+ const definitions = asMap(value, '"metadata"');
122
+ const ajv = createAjv();
123
+ for (const [key, schema] of Object.entries(definitions)) {
124
+ if (CORE_FIELDS.includes(key))
125
+ throw new Error(`"metadata.${key}" can't be used: "${key}" is a core setting of every article`);
126
+ if (!KEY.test(key))
127
+ throw new Error(`"metadata.${key}" must start with a letter or "_" and have only letters, digits, "_" and "-"`);
128
+ checkFieldSchema(schema, `metadata.${key}`);
129
+ try {
130
+ ajv.compile(schema);
131
+ }
132
+ catch (error) {
133
+ throw new Error(`"metadata.${key}" isn't a valid JSON Schema: ${error.message}`, { cause: error });
134
+ }
135
+ }
136
+ return definitions;
137
+ };
138
+ /**
139
+ * The custom metadata fields an article type uses: those its `metadata` setting lists, none for `false`, or all when
140
+ * it has none.
141
+ *
142
+ * @example
143
+ * typeMetadataKeys({ featured: {...}, images: {...} }, ["featured"]); // ["featured"]
144
+ */
145
+ export const typeMetadataKeys = (definitions, typeMetadata) => typeMetadata === undefined
146
+ ? Object.keys(definitions)
147
+ : typeMetadata === false
148
+ ? []
149
+ : typeMetadata;
150
+ /** JSON types in plain words, e.g. "a number" */
151
+ const TYPE_NAMES = {
152
+ string: "text",
153
+ number: "a number",
154
+ integer: "a whole number",
155
+ boolean: "yes or no",
156
+ array: "a list",
157
+ object: "a group of settings",
158
+ null: "empty",
159
+ };
160
+ /** Formats in plain words, e.g. "an email address" */
161
+ const FORMAT_NAMES = {
162
+ email: "an email address",
163
+ uri: "a full web address, e.g. https://example.com",
164
+ url: "a full web address, e.g. https://example.com",
165
+ "uri-reference": "a web address or path",
166
+ date: "a date, e.g. 2026-11-19",
167
+ time: "a time, e.g. 14:30:00",
168
+ "date-time": "a date and time, e.g. 2026-11-19T14:30:00Z",
169
+ hostname: "a host name, e.g. example.com",
170
+ ipv4: "an IPv4 address",
171
+ ipv6: "an IPv6 address",
172
+ uuid: "a UUID",
173
+ regex: "a regular expression",
174
+ };
175
+ /** "1 item" or "3 items" */
176
+ const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
177
+ /** A value in a message: text in quotes, anything else as written */
178
+ const quote = (value) => typeof value === "string" ? `"${value}"` : JSON.stringify(value);
179
+ /**
180
+ * Say what is wrong with a value in plain words, from an ajv error, e.g. "must be at most 10" or "must be an email
181
+ * address". Errors this doesn't know keep ajv's message.
182
+ *
183
+ * @example
184
+ * plainMessage({ keyword: "maximum", params: { limit: 10 }, ... }); // "must be at most 10"
185
+ */
186
+ export const plainMessage = (error) => {
187
+ const params = error.params;
188
+ const limit = params.limit;
189
+ switch (error.keyword) {
190
+ case "type": {
191
+ const types = String(params.type).split(",");
192
+ // Schemas only compile with JSON's own types, which all have names
193
+ return `must be ${types.map((type) => TYPE_NAMES[type]).join(" or ")}`;
194
+ }
195
+ case "minimum":
196
+ return `must be at least ${limit}`;
197
+ case "maximum":
198
+ return `must be at most ${limit}`;
199
+ case "exclusiveMinimum":
200
+ return `must be more than ${limit}`;
201
+ case "exclusiveMaximum":
202
+ return `must be less than ${limit}`;
203
+ case "multipleOf":
204
+ return `must be a multiple of ${params.multipleOf}`;
205
+ case "minLength":
206
+ return limit === 1
207
+ ? "can't be empty"
208
+ : `must be at least ${plural(limit, "character")}`;
209
+ case "maxLength":
210
+ return `must be at most ${plural(limit, "character")}`;
211
+ case "pattern":
212
+ return "isn't in the right form";
213
+ case "format":
214
+ return `must be ${FORMAT_NAMES[params.format] ?? `a valid ${params.format}`}`;
215
+ case "enum":
216
+ return `must be one of ${params.allowedValues.map(quote).join(", ")}`;
217
+ case "const":
218
+ return `must be ${quote(params.allowedValue)}`;
219
+ case "required":
220
+ return "is required";
221
+ case "minItems":
222
+ return `must have at least ${plural(limit, "item")}`;
223
+ case "maxItems":
224
+ return `can have at most ${plural(limit, "item")}`;
225
+ case "uniqueItems":
226
+ return "can't have the same item twice";
227
+ case "additionalProperties":
228
+ return "isn't a known setting";
229
+ default:
230
+ // ajv always describes its errors
231
+ return error.message;
232
+ }
233
+ };
234
+ /**
235
+ * An ajv error as a problem with a value, in plain words (see `plainMessage`). A missing or unknown property is a
236
+ * problem with that property, so its field shows it.
237
+ */
238
+ const problem = (key, error) => {
239
+ const params = error.params;
240
+ const property = (params.missingProperty ?? params.additionalProperty);
241
+ return {
242
+ path: key + error.instancePath + (property ? `/${property}` : ""),
243
+ message: plainMessage(error),
244
+ level: "error",
245
+ };
246
+ };
247
+ /**
248
+ * Validates articles' custom metadata values against their schemas, compiling each schema once.
249
+ *
250
+ * @example
251
+ * const validator = new MetadataValidator(config.metadata);
252
+ * validator.validate("featured", 3); // [{ path: "featured", message: "must be string", level: "error" }]
253
+ */
254
+ export class MetadataValidator {
255
+ ajv = createAjv();
256
+ compiled = new Map();
257
+ /** The custom metadata fields' schemas, by key */
258
+ definitions;
259
+ constructor(definitions) {
260
+ this.definitions = definitions;
261
+ }
262
+ /** The problems with a value of a custom metadata field (none if it's valid) */
263
+ validate(key, value) {
264
+ let validate = this.compiled.get(key);
265
+ if (!validate) {
266
+ validate = this.ajv.compile(this.definitions[key]);
267
+ this.compiled.set(key, validate);
268
+ }
269
+ if (validate(value))
270
+ return [];
271
+ // A value that isn't valid always has errors
272
+ return validate.errors.map((error) => problem(key, error));
273
+ }
274
+ }
275
+ /**
276
+ * Read an article's custom metadata from its settings: fill in default values and leave out hidden fields' values (see
277
+ * resolveFields), validate the values of the fields its type uses, and warn about values of fields its type doesn't use
278
+ * and settings that aren't core or defined.
279
+ *
280
+ * @param typeLabel - the type's plural label, for warnings, e.g. "News"
281
+ *
282
+ * @example
283
+ * articleMetadata({ date, featured: "a.png", oops: 1 }, ["featured"], validator, "News");
284
+ * // { values: { featured: "a.png" }, problems: [{ path: "oops", message: "isn't a known setting", level: "warning" }] }
285
+ */
286
+ export const articleMetadata = (settings, keys, validator, typeLabel) => {
287
+ const given = {};
288
+ /** Settings that aren't used */
289
+ const problems = [];
290
+ for (const [key, value] of Object.entries(settings)) {
291
+ if (CORE_FIELDS.includes(key))
292
+ continue;
293
+ if (keys.includes(key))
294
+ given[key] = value;
295
+ else
296
+ problems.push({
297
+ path: key,
298
+ message: key in validator.definitions
299
+ ? `isn't used by ${typeLabel}`
300
+ : "isn't a known setting",
301
+ level: "warning",
302
+ });
303
+ }
304
+ const schemas = Object.fromEntries(keys.flatMap((key) => {
305
+ const schema = validator.definitions[key];
306
+ return schema ? [[key, schema]] : [];
307
+ }));
308
+ const { values } = resolveFields(schemas, given);
309
+ const errors = Object.entries(values).flatMap(([key, value]) => validator.validate(key, value));
310
+ return { values, problems: [...errors, ...problems] };
311
+ };
312
+ /**
313
+ * Make a value's file fields' relative file names into paths on the website (like `thumbnail`), following its
314
+ * schema's objects and lists.
315
+ *
316
+ * @example
317
+ * resolveFileFields({ $edahaField: { file: true } }, "photo.png", "/news/hello/"); // "/news/hello/photo.png"
318
+ */
319
+ export const resolveFileFields = (schema, value, articleUrl) => {
320
+ if (Array.isArray(value) && schema.items)
321
+ return value.map((item) => resolveFileFields(schema.items, item, articleUrl));
322
+ if (value && typeof value === "object" && schema.properties)
323
+ return Object.fromEntries(Object.entries(value).map(([name, item]) => {
324
+ const property = schema.properties?.[name];
325
+ return [
326
+ name,
327
+ property ? resolveFileFields(property, item, articleUrl) : item,
328
+ ];
329
+ }));
330
+ return typeof value === "string" &&
331
+ schema.$edahaField &&
332
+ "file" in schema.$edahaField &&
333
+ isRelativeUrl(value)
334
+ ? articleUrl + value
335
+ : value;
336
+ };
337
+ /**
338
+ * An article's custom metadata for templates (`article.meta`): its type's valid values, with file fields as paths on
339
+ * the website. Values with errors are left out.
340
+ */
341
+ export const templateMetadata = (metadata, definitions, articleUrl) => {
342
+ const invalid = new Set(metadata.problems
343
+ .filter((problem) => problem.level === "error")
344
+ .map((problem) => problem.path.split("/")[0]));
345
+ return Object.fromEntries(Object.entries(metadata.values)
346
+ .filter(([key]) => !invalid.has(key))
347
+ .map(([key, value]) => [
348
+ key,
349
+ resolveFileFields(definitions[key], value, articleUrl),
350
+ ]));
351
+ };
352
+ /** Check a map key is used only for keys listed, for the type's `metadata` setting */
353
+ export const parseTypeMetadata = (value, what) => {
354
+ if (value === undefined || value === null)
355
+ return undefined;
356
+ if (value === false)
357
+ return false;
358
+ if (!Array.isArray(value) || value.some((key) => typeof key !== "string"))
359
+ throw new Error(`${what} must be a list of metadata keys, or false for none`);
360
+ return value;
361
+ };
@@ -0,0 +1,45 @@
1
+ import type { MetadataDefinitions } from "../metadata/index.ts";
2
+ /** A group of settings in the editor, as the config file's `metadataGroups` defines it */
3
+ export interface MetadataGroupConfig {
4
+ /** The group's heading */
5
+ title: string;
6
+ /** Shown above the group's fields */
7
+ description?: string | undefined;
8
+ /** The group it comes after (by default, groups go at the end) */
9
+ after?: string | undefined;
10
+ /** Whether the group starts open. Default: false */
11
+ openedByDefault: boolean;
12
+ }
13
+ /** A group of settings in the editor: its heading, and its fields' keys in order */
14
+ export interface MetadataGroup {
15
+ key: string;
16
+ title: string;
17
+ description?: string | undefined;
18
+ openedByDefault: boolean;
19
+ /** Its core and custom fields' keys, in order ("uploaded" is the article folder's files) */
20
+ fields: string[];
21
+ }
22
+ /**
23
+ * The editor's own groups, in order, with their core settings. "slug" and "uploaded" (the files in the article's
24
+ * folder) aren't settings, but have their place too. Custom fields without a group go in "custom".
25
+ */
26
+ export declare const BUILT_IN_GROUPS: readonly MetadataGroup[];
27
+ /**
28
+ * Read the config file's `metadataGroups` setting: groups of settings for the editor, by key. Throws an Error if a key
29
+ * is a built-in group's or isn't usable, or a group's settings aren't valid.
30
+ *
31
+ * @example
32
+ * parseMetadataGroups({ seo: { title: "SEO", after: "info", openedByDefault: true } });
33
+ */
34
+ export declare const parseMetadataGroups: (value: unknown) => Record<string, MetadataGroupConfig>;
35
+ /**
36
+ * The editor's groups of settings in order, each with its fields in order: the built-in groups (and the custom groups,
37
+ * placed after the group they name or at the end), with every custom field in its group (after the field it names, or
38
+ * at the group's end). Throws an Error if a field's group doesn't exist, or a field or group names one to follow that
39
+ * isn't there.
40
+ *
41
+ * @example
42
+ * metadataLayout({ hero: { $edahaField: { group: { key: "files", after: "thumbnail" }, file: true } } }, {});
43
+ * // [..., { key: "files", fields: ["thumbnail", "hero", "attachments", "uploaded"], ... }, ...]
44
+ */
45
+ export declare const metadataLayout: (definitions: MetadataDefinitions, groups: Record<string, MetadataGroupConfig>) => MetadataGroup[];