@lvl99dotcom/edaha.md 0.1.0 → 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 (61) hide show
  1. package/LICENSE +183 -183
  2. package/README.md +7 -252
  3. package/dist/cli/index.d.ts +36 -6
  4. package/dist/cli/index.js +48 -9
  5. package/dist/embeds/blocks/index.d.ts +59 -0
  6. package/dist/embeds/blocks/index.js +103 -0
  7. package/dist/embeds/index.d.ts +122 -19
  8. package/dist/embeds/index.js +381 -41
  9. package/dist/embeds/types/index.d.ts +111 -8
  10. package/dist/generator/article/index.d.ts +52 -12
  11. package/dist/generator/article/index.js +94 -26
  12. package/dist/generator/build/index.d.ts +55 -23
  13. package/dist/generator/build/index.js +151 -81
  14. package/dist/generator/config/index.d.ts +45 -8
  15. package/dist/generator/config/index.js +152 -30
  16. package/dist/generator/configFile/index.d.ts +58 -0
  17. package/dist/generator/configFile/index.js +122 -0
  18. package/dist/generator/fields/index.d.ts +93 -0
  19. package/dist/generator/fields/index.js +186 -0
  20. package/dist/generator/format/index.d.ts +40 -0
  21. package/dist/generator/format/index.js +75 -0
  22. package/dist/generator/lists/index.d.ts +3 -3
  23. package/dist/generator/lists/index.js +9 -8
  24. package/dist/generator/markdown/index.d.ts +8 -3
  25. package/dist/generator/markdown/index.js +11 -4
  26. package/dist/generator/metadata/index.d.ts +150 -0
  27. package/dist/generator/metadata/index.js +361 -0
  28. package/dist/generator/metadataGroups/index.d.ts +45 -0
  29. package/dist/generator/metadataGroups/index.js +169 -0
  30. package/dist/generator/templates/index.d.ts +35 -3
  31. package/dist/generator/templates/index.js +72 -6
  32. package/dist/generator/types/index.d.ts +43 -18
  33. package/dist/generator/urls/index.d.ts +18 -8
  34. package/dist/generator/urls/index.js +22 -12
  35. package/dist/index.d.ts +5 -7
  36. package/dist/index.js +6 -7
  37. package/package.json +18 -47
  38. package/theme/static/{site.css → base.css} +132 -24
  39. package/theme/templates/article/list.njk +6 -6
  40. package/theme/templates/article/single.njk +13 -7
  41. package/theme/templates/layouts/html.njk +54 -32
  42. package/theme/templates/layouts/rssfeed.njk +7 -7
  43. package/theme/templates/page/home.njk +2 -7
  44. package/theme/templates/page/single.njk +2 -2
  45. package/dist/client/assets/index-BbKEbPS8.css +0 -1
  46. package/dist/client/assets/index-DtG7vi1d.js +0 -559
  47. package/dist/client/index.html +0 -13
  48. package/dist/editor/index.d.ts +0 -62
  49. package/dist/editor/index.js +0 -102
  50. package/dist/embeds/bandcamp/index.d.ts +0 -9
  51. package/dist/embeds/bandcamp/index.js +0 -28
  52. package/dist/embeds/youtube/index.d.ts +0 -17
  53. package/dist/embeds/youtube/index.js +0 -48
  54. package/dist/server/app/index.d.ts +0 -39
  55. package/dist/server/app/index.js +0 -138
  56. package/dist/server/convert/index.d.ts +0 -25
  57. package/dist/server/convert/index.js +0 -125
  58. package/dist/server/store/index.d.ts +0 -148
  59. package/dist/server/store/index.js +0 -411
  60. package/dist/server/types/index.d.ts +0 -76
  61. package/dist/server/types/index.js +0 -1
@@ -0,0 +1,186 @@
1
+ /** Operators comparing with one value */
2
+ const OPERATORS = ["=", "!=", ">", ">=", "<", "<="];
3
+ /** Operators comparing with a list of values */
4
+ const LIST_OPERATORS = ["in", "not-in"];
5
+ /** Whether a value can be compared by a condition */
6
+ const isConditionValue = (value) => value === null || ["string", "number", "boolean"].includes(typeof value);
7
+ /** Whether a value is one condition (rather than a list of groups) */
8
+ const isCondition = (value) => Array.isArray(value) && typeof value[0] === "string";
9
+ /** Whether conditions are a list of conditions and groups (rather than one condition or group) */
10
+ const isConditionList = (value) => Array.isArray(value) && !isCondition(value);
11
+ /**
12
+ * Check a field's `showWhen` or `hideWhen` is made of conditions and `and`/`or` groups. Throws an Error naming where
13
+ * the problem is.
14
+ *
15
+ * @example
16
+ * checkConditions({ or: [["layout", "=", "slim"], ["layout", "=", "large"]] }, '"showWhen"');
17
+ */
18
+ export const checkConditions = (value, what) => {
19
+ if (isCondition(value)) {
20
+ const [path, operator, compared] = value;
21
+ const valid = value.length === 3 &&
22
+ path !== "" &&
23
+ (OPERATORS.includes(operator)
24
+ ? isConditionValue(compared)
25
+ : LIST_OPERATORS.includes(operator) &&
26
+ Array.isArray(compared) &&
27
+ compared.every(isConditionValue));
28
+ if (!valid)
29
+ throw new Error(`${what} must be a condition like ["layout", "=", "large"] (operators: ${[...OPERATORS, ...LIST_OPERATORS].join(" ")}; "in" and "not-in" compare with a list of values), got ${JSON.stringify(value)}`);
30
+ return;
31
+ }
32
+ if (Array.isArray(value)) {
33
+ value.forEach((item, index) => checkConditions(item, `${what}.${index}`));
34
+ return;
35
+ }
36
+ const keys = value && typeof value === "object" ? Object.keys(value) : undefined;
37
+ if (keys?.length !== 1 || !["and", "or"].includes(keys[0]))
38
+ throw new Error(`${what} must be a condition, or a group with one "and" or "or" list of conditions, got ${JSON.stringify(value)}`);
39
+ checkConditions(value[keys[0]], `${what}.${keys[0]}`);
40
+ };
41
+ /**
42
+ * Check an `$edahaField`'s `defaultValue`, `showWhen` and `hideWhen`. Throws an Error naming where the problem is.
43
+ *
44
+ * @example
45
+ * checkFieldExtensions({ select: true, defaultValue: "large" }, '"metadata.layout.$edahaField"');
46
+ */
47
+ export const checkFieldExtensions = (field, what) => {
48
+ if (field.defaultValue !== undefined && !isConditionValue(field.defaultValue))
49
+ throw new Error(`${what}.defaultValue must be text, a number, true, false or null`);
50
+ for (const name of ["showWhen", "hideWhen"])
51
+ if (field[name] !== undefined)
52
+ checkConditions(field[name], `${what}.${name}`);
53
+ };
54
+ /**
55
+ * The value at a dot path inside values, e.g. "credit.name" or "images.0".
56
+ *
57
+ * @example
58
+ * valueAt({ credit: { name: "Ann" } }, "credit.name"); // "Ann"
59
+ */
60
+ export const valueAt = (values, path) => path
61
+ .split(".")
62
+ .reduce((value, key) => value && typeof value === "object"
63
+ ? value[key]
64
+ : undefined, values);
65
+ /** Compare a value with one value: equal (a missing value equals null), or in order (numbers or text only) */
66
+ const compare = (value, operator, compared) => {
67
+ const equal = value === compared || (value ?? null) === compared;
68
+ if (operator === "=")
69
+ return equal;
70
+ if (operator === "!=")
71
+ return !equal;
72
+ if (typeof value !== typeof compared ||
73
+ !["number", "string"].includes(typeof value))
74
+ return false;
75
+ const [a, b] = [value, compared];
76
+ return operator === ">"
77
+ ? a > b
78
+ : operator === ">="
79
+ ? a >= b
80
+ : operator === "<"
81
+ ? a < b
82
+ : a <= b;
83
+ };
84
+ /**
85
+ * Whether values match conditions: one condition, `and` (all match) or `or` (any match) groups, or a list (all match).
86
+ *
87
+ * @example
88
+ * matchesConditions({ layout: "slim" }, { or: [["layout", "=", "slim"], ["layout", "=", "large"]] }); // true
89
+ * matchesConditions({ layout: "slim" }, ["layout", "in", ["large"]]); // false
90
+ */
91
+ export const matchesConditions = (values, conditions) => {
92
+ if (isConditionList(conditions))
93
+ return conditions.every((item) => matchesConditions(values, item));
94
+ if (isCondition(conditions)) {
95
+ const [path, operator, compared] = conditions;
96
+ const value = valueAt(values, path);
97
+ if (operator !== "in" && operator !== "not-in")
98
+ return compare(value, operator, compared);
99
+ const included = compared.some((item) => compare(value, "=", item));
100
+ return operator === "in" ? included : !included;
101
+ }
102
+ if ("and" in conditions)
103
+ return matchesConditions(values, conditions.and);
104
+ const any = conditions.or;
105
+ return isConditionList(any)
106
+ ? any.some((item) => matchesConditions(values, item))
107
+ : matchesConditions(values, any);
108
+ };
109
+ /**
110
+ * Whether a field shows: its `showWhen` matches (or it has none), and its `hideWhen` doesn't (or it has none).
111
+ *
112
+ * @example
113
+ * fieldShown({ checkbox: true, showWhen: ["layout", "=", "large"] }, { layout: "slim" }); // false
114
+ */
115
+ export const fieldShown = (field, values) => (!field?.showWhen || matchesConditions(values, field.showWhen)) &&
116
+ !(field?.hideWhen && matchesConditions(values, field.hideWhen));
117
+ /** Every field in a map of fields, a group (map) before the fields in it; lists' items aren't included */
118
+ const fieldsIn = (schemas, parent = []) => Object.entries(schemas).flatMap(([name, schema]) => {
119
+ const field = { path: [...parent, name], schema };
120
+ return schema.type === "object" && schema.properties
121
+ ? [field, ...fieldsIn(schema.properties, field.path)]
122
+ : [field];
123
+ });
124
+ /** Set (or, for undefined, leave out) a value in a map at a path of keys, without changing the original */
125
+ const withValueAt = (values, [key, ...rest], value) => {
126
+ const current = values[key];
127
+ const next = rest.length
128
+ ? withValueAt(current && typeof current === "object"
129
+ ? current
130
+ : {}, rest, value)
131
+ : value;
132
+ return next === undefined
133
+ ? Object.fromEntries(Object.entries(values).filter(([name]) => name !== key))
134
+ : { ...values, [key]: next };
135
+ };
136
+ /**
137
+ * Apply fields' `defaultValue`, `showWhen` and `hideWhen` to values: shown fields without a value get their default,
138
+ * and hidden fields' values (and those of fields in a hidden group) are left out. Conditions are checked again until
139
+ * nothing changes, as hiding or filling in one value can show or hide another. The values are in the fields' order,
140
+ * then any values without a field.
141
+ *
142
+ * @example
143
+ * resolveFields(
144
+ * { layout: { type: "string", $edahaField: { select: true, defaultValue: "large" } },
145
+ * tracklist: { type: "boolean", $edahaField: { checkbox: true, hideWhen: ["layout", "=", "slim"] } } },
146
+ * { tracklist: true },
147
+ * ); // { values: { layout: "large", tracklist: true }, hidden: Set {} }
148
+ */
149
+ export const resolveFields = (schemas, values) => {
150
+ const fields = fieldsIn(schemas);
151
+ /** The values with some fields hidden, and the others' defaults filled in */
152
+ const apply = (hidden) => fields.reduce((result, { path, schema }) => {
153
+ const key = path.join(".");
154
+ const { defaultValue } = (schema.$edahaField ??
155
+ {});
156
+ if (hidden.has(key))
157
+ return valueAt(result, key) === undefined
158
+ ? result
159
+ : withValueAt(result, path, undefined);
160
+ return defaultValue !== undefined && valueAt(result, key) === undefined
161
+ ? withValueAt(result, path, defaultValue)
162
+ : result;
163
+ }, values);
164
+ /** The fields hidden by the conditions, checked on the values (with a hidden group's fields hidden too) */
165
+ const hiddenBy = (current) => fields.reduce((hidden, { path, schema }) => {
166
+ if (hidden.has(path.slice(0, -1).join(".")) ||
167
+ !fieldShown(schema.$edahaField, current))
168
+ hidden.add(path.join("."));
169
+ return hidden;
170
+ }, new Set());
171
+ // Each round starts again from the given values, so a value hidden in one round can show in the next. It stops when
172
+ // the same fields are hidden twice; the limit stops conditions that contradict each other going on forever.
173
+ let hidden = new Set();
174
+ let current = apply(hidden);
175
+ for (let round = 0; round <= fields.length; round++) {
176
+ const next = hiddenBy(current);
177
+ if ([...next].join("\0") === [...hidden].join("\0"))
178
+ break;
179
+ hidden = next;
180
+ current = apply(hidden);
181
+ }
182
+ // In the fields' order, then any other values
183
+ const order = Object.keys(schemas);
184
+ const ordered = Object.fromEntries(Object.entries(current).sort(([a], [b]) => (order.indexOf(a) + 1 || Infinity) - (order.indexOf(b) + 1 || Infinity)));
185
+ return { values: ordered, hidden };
186
+ };
@@ -50,3 +50,43 @@ export declare const cropText: (text: string, maxLength: number) => string;
50
50
  * isRelativeUrl("/news/"); // false
51
51
  */
52
52
  export declare const isRelativeUrl: (url: string) => boolean;
53
+ /**
54
+ * Blank out Markdown's code blocks and inline code with spaces, keeping every other character where it was, so
55
+ * markers like `<!-- readmore -->` can be found outside code only.
56
+ *
57
+ * @example
58
+ * maskCode("Intro `<!-- readmore -->` rest"); // "Intro rest"
59
+ */
60
+ export declare const maskCode: (markdown: string) => string;
61
+ /**
62
+ * Replace a pattern's matches in Markdown, except in code blocks and inline code. The replacer gets each match as
63
+ * `exec` gives it (from the original text, groups included).
64
+ *
65
+ * @example
66
+ * replaceOutsideCode("a <!-- x --> `<!-- x -->`", /<!-- x -->/g, () => "X"); // "a X `<!-- x -->`"
67
+ */
68
+ export declare const replaceOutsideCode: (markdown: string, pattern: RegExp, replacer: (match: RegExpExecArray) => string) => string;
69
+ /** A `<!-- raw -->...<!-- /raw -->` block, whose content is shown exactly as it is written */
70
+ export declare const RAW_BLOCK: RegExp;
71
+ /** A raw block's content, and whether it is a block (on its own lines) or inline (within a line) */
72
+ export interface RawContent {
73
+ content: string;
74
+ block: boolean;
75
+ }
76
+ /**
77
+ * Replace every raw block outside code in Markdown. A raw block on its own lines is a block, without the line breaks
78
+ * after its opening and before its closing marker; one within a line is inline.
79
+ *
80
+ * @example
81
+ * replaceRawBlocks("<!-- raw -->\n*a*\n<!-- /raw -->", ({ content }) => content); // "*a*"
82
+ */
83
+ export declare const replaceRawBlocks: (markdown: string, replacer: (raw: RawContent) => string) => string;
84
+ /**
85
+ * The HTML that shows a raw block's content exactly as it is written: in `<pre class="raw">` for a block (which keeps
86
+ * its spaces and line breaks whatever the stylesheet), or `<span class="raw">` inline, on one line. Line breaks and punctuation are written as character references, so
87
+ * Markdown, shortcodes and typography never act on it.
88
+ *
89
+ * @example
90
+ * rawHtml({ content: "*a*", block: false }); // '<span class="raw">&#42;a&#42;</span>'
91
+ */
92
+ export declare const rawHtml: ({ content, block }: RawContent) => string;
@@ -100,3 +100,78 @@ export const cropText = (text, maxLength) => {
100
100
  * isRelativeUrl("/news/"); // false
101
101
  */
102
102
  export const isRelativeUrl = (url) => url !== "" && !/^([a-z][a-z0-9+.-]*:|\/|#|\?)/i.test(url);
103
+ /**
104
+ * Fenced code blocks (``` or ~~~, to their closing fence or the end of the text) and inline code spans in Markdown
105
+ */
106
+ const MARKDOWN_CODE = /^ {0,3}(?<fence>`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^ {0,3}\k<fence>[`~]*[ \t]*$|(?![\s\S]))|(?<ticks>`+)(?:(?!\k<ticks>)[\s\S])+?\k<ticks>(?!`)/gm;
107
+ /**
108
+ * Blank out Markdown's code blocks and inline code with spaces, keeping every other character where it was, so
109
+ * markers like `<!-- readmore -->` can be found outside code only.
110
+ *
111
+ * @example
112
+ * maskCode("Intro `<!-- readmore -->` rest"); // "Intro rest"
113
+ */
114
+ export const maskCode = (markdown) => markdown.replace(MARKDOWN_CODE, (code) => " ".repeat(code.length));
115
+ /**
116
+ * Replace a pattern's matches in Markdown, except in code blocks and inline code. The replacer gets each match as
117
+ * `exec` gives it (from the original text, groups included).
118
+ *
119
+ * @example
120
+ * replaceOutsideCode("a <!-- x --> `<!-- x -->`", /<!-- x -->/g, () => "X"); // "a X `<!-- x -->`"
121
+ */
122
+ export const replaceOutsideCode = (markdown, pattern, replacer) => {
123
+ const single = new RegExp(pattern.source, pattern.flags.replace("g", ""));
124
+ let result = "";
125
+ let last = 0;
126
+ for (const { index, 0: text } of maskCode(markdown).matchAll(new RegExp(single.source, `${single.flags}g`))) {
127
+ const match = single.exec(markdown.slice(index, index + text.length));
128
+ result += markdown.slice(last, index) + replacer(match);
129
+ last = index + text.length;
130
+ }
131
+ return result + markdown.slice(last);
132
+ };
133
+ /** A `<!-- raw -->...<!-- /raw -->` block, whose content is shown exactly as it is written */
134
+ export const RAW_BLOCK = /<!--\s*raw\s*-->(?<rawContent>[\s\S]*?)<!--\s*\/raw\s*-->/;
135
+ /**
136
+ * Raw blocks and code, whichever starts first: code can show raw markers as they are, and raw blocks can hold code
137
+ */
138
+ const RAW_OR_CODE = new RegExp(`(?<raw>${RAW_BLOCK.source})|${MARKDOWN_CODE.source}`, "gm");
139
+ /**
140
+ * Replace every raw block outside code in Markdown. A raw block on its own lines is a block, without the line breaks
141
+ * after its opening and before its closing marker; one within a line is inline.
142
+ *
143
+ * @example
144
+ * replaceRawBlocks("<!-- raw -->\n*a*\n<!-- /raw -->", ({ content }) => content); // "*a*"
145
+ */
146
+ export const replaceRawBlocks = (markdown, replacer) => markdown.replace(RAW_OR_CODE, (...args) => {
147
+ const match = args[0];
148
+ const groups = args.at(-1);
149
+ if (groups.raw === undefined)
150
+ return match;
151
+ const offset = args.at(-3);
152
+ const block = /(?:^|\n)[ \t]*$/.test(markdown.slice(0, offset)) &&
153
+ /^[ \t]*(?:\r?\n|$)/.test(markdown.slice(offset + match.length));
154
+ const content = groups.rawContent;
155
+ return replacer({
156
+ block,
157
+ content: block
158
+ ? content.replace(/^[ \t]*\r?\n/, "").replace(/\r?\n[ \t]*$/, "")
159
+ : content,
160
+ });
161
+ });
162
+ /**
163
+ * The HTML that shows a raw block's content exactly as it is written: in `<pre class="raw">` for a block (which keeps
164
+ * its spaces and line breaks whatever the stylesheet), or `<span class="raw">` inline, on one line. Line breaks and punctuation are written as character references, so
165
+ * Markdown, shortcodes and typography never act on it.
166
+ *
167
+ * @example
168
+ * rawHtml({ content: "*a*", block: false }); // '<span class="raw">&#42;a&#42;</span>'
169
+ */
170
+ export const rawHtml = ({ content, block }) => {
171
+ const tag = block ? "pre" : "span";
172
+ const text = content
173
+ .replace(/\r\n?/g, "\n")
174
+ .replace(/[\n!-/:-@[-`{-~]/g, (char) => `&#${char.charCodeAt(0)};`);
175
+ const html = `<${tag} class="raw">${text}</${tag}>`;
176
+ return block ? `\n\n${html}\n\n` : html;
177
+ };
@@ -1,4 +1,4 @@
1
- import type { ListKind, TemplateDataArticle, TemplateDataBlog, TemplateDataList } from "../types/index.ts";
1
+ import type { ListKind, TemplateDataArticle, TemplateDataSite, TemplateDataList } from "../types/index.ts";
2
2
  /** Articles per list page */
3
3
  export declare const PAGE_SIZE = 20;
4
4
  /** A list of articles before pagination */
@@ -43,9 +43,9 @@ export declare const sortArticles: (articles: readonly TemplateDataArticle[]) =>
43
43
  * @param withIndex - article types that have an index article
44
44
  *
45
45
  * @example
46
- * collectLists(published, blog, new Set()).map((list) => list.url); // ["/news/", "/news/tags/art/", ...]
46
+ * collectLists(published, site, new Set()).map((list) => list.url); // ["/news/", "/news/tags/art/", ...]
47
47
  */
48
- export declare const collectLists: (articles: readonly TemplateDataArticle[], blog: TemplateDataBlog, withIndex: ReadonlySet<string>) => ListDefinition[];
48
+ export declare const collectLists: (articles: readonly TemplateDataArticle[], site: TemplateDataSite, withIndex: ReadonlySet<string>) => ListDefinition[];
49
49
  /**
50
50
  * The output file name of a list page.
51
51
  *
@@ -22,9 +22,9 @@ export const sortArticles = (articles) => [...articles].sort((a, b) => b.date.lo
22
22
  * @param withIndex - article types that have an index article
23
23
  *
24
24
  * @example
25
- * collectLists(published, blog, new Set()).map((list) => list.url); // ["/news/", "/news/tags/art/", ...]
25
+ * collectLists(published, site, new Set()).map((list) => list.url); // ["/news/", "/news/tags/art/", ...]
26
26
  */
27
- export const collectLists = (articles, blog, withIndex) => {
27
+ export const collectLists = (articles, site, withIndex) => {
28
28
  const lists = new Map();
29
29
  /** Get or create a list */
30
30
  const list = (definition) => {
@@ -33,7 +33,7 @@ export const collectLists = (articles, blog, withIndex) => {
33
33
  return existing;
34
34
  const created = {
35
35
  ...definition,
36
- url: `/${definition.dir}`,
36
+ url: `${site.baseUrl}/${definition.dir}`,
37
37
  articles: [],
38
38
  feedArticles: [],
39
39
  };
@@ -42,13 +42,13 @@ export const collectLists = (articles, blog, withIndex) => {
42
42
  };
43
43
  /** A type's own list */
44
44
  const typeList = (type) => {
45
- const config = blog.types[type];
45
+ const config = site.types[type];
46
46
  return list({
47
47
  kind: "type",
48
48
  name: config.labelPlural,
49
49
  slug: type,
50
50
  type,
51
- dir: config.url.slice(1),
51
+ dir: config.url.slice(site.baseUrl.length + 1),
52
52
  // An index article takes the place of the list's pages
53
53
  pages: config.generate.list && !withIndex.has(type),
54
54
  feed: false,
@@ -57,7 +57,7 @@ export const collectLists = (articles, blog, withIndex) => {
57
57
  for (const type of withIndex)
58
58
  typeList(type);
59
59
  for (const article of sortArticles(articles)) {
60
- const config = blog.types[article.type];
60
+ const config = site.types[article.type];
61
61
  const settings = config.generate;
62
62
  /** Add the article to a list, and to its feed if the type allows feeds */
63
63
  const add = (entry) => {
@@ -68,7 +68,7 @@ export const collectLists = (articles, blog, withIndex) => {
68
68
  };
69
69
  if (settings.list || settings.feed || withIndex.has(article.type))
70
70
  add(typeList(article.type));
71
- const typeDir = config.url.slice(1);
71
+ const typeDir = config.url.slice(site.baseUrl.length + 1);
72
72
  if (settings.tag)
73
73
  for (const tag of article.tags)
74
74
  add(list({
@@ -80,7 +80,8 @@ export const collectLists = (articles, blog, withIndex) => {
80
80
  pages: true,
81
81
  feed: false,
82
82
  }));
83
- if (settings.author)
83
+ // Articles without an author aren't in any author's list
84
+ if (settings.author && article.author)
84
85
  add(list({
85
86
  kind: "author",
86
87
  name: article.author.name,
@@ -3,7 +3,8 @@ import MarkdownIt from "markdown-it";
3
3
  export type Markdown = InstanceType<typeof MarkdownIt>;
4
4
  /**
5
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).
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.
7
8
  * Headings get IDs from their text (see `headingIds`), so they can be linked to, e.g. `#this-is-an-example`.
8
9
  * Typographer (curly quotes, dashes) is on for the website and off for the editor, so text round-trips unchanged.
9
10
  *
@@ -15,6 +16,10 @@ export declare const createMarkdown: ({ typographer }?: {
15
16
  typographer?: boolean | undefined;
16
17
  }) => Markdown;
17
18
  /**
18
- * Render markdown to HTML, resolving relative URLs against a folder URL.
19
+ * Render markdown to HTML, resolving relative URLs against a folder URL and putting root-relative ones under the
20
+ * website's base URL.
21
+ *
22
+ * @example
23
+ * renderMarkdown(markdown, "[Docs](/docs/)", "/edaha.md/news/hello/", "/edaha.md"); // '<p><a href="/edaha.md/docs/">Docs</a></p>\n'
19
24
  */
20
- export declare const renderMarkdown: (markdown: Markdown, source: string, baseUrl: string) => string;
25
+ export declare const renderMarkdown: (markdown: Markdown, source: string, baseUrl: string, siteBaseUrl?: string) => string;
@@ -3,7 +3,8 @@ import { isRelativeUrl } from "../format/index.js";
3
3
  import { headingIds } from "../slug/index.js";
4
4
  /**
5
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).
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.
7
8
  * Headings get IDs from their text (see `headingIds`), so they can be linked to, e.g. `#this-is-an-example`.
8
9
  * Typographer (curly quotes, dashes) is on for the website and off for the editor, so text round-trips unchanged.
9
10
  *
@@ -14,7 +15,7 @@ import { headingIds } from "../slug/index.js";
14
15
  export const createMarkdown = ({ typographer = true } = {}) => {
15
16
  const markdown = new MarkdownIt({ html: true, typographer });
16
17
  markdown.core.ruler.push("resolve_relative_urls", (state) => {
17
- const { baseUrl } = state.env;
18
+ const { baseUrl, siteBaseUrl } = state.env;
18
19
  for (const block of state.tokens) {
19
20
  for (const token of block.children ?? []) {
20
21
  const attribute = token.type === "image"
@@ -28,6 +29,8 @@ export const createMarkdown = ({ typographer = true } = {}) => {
28
29
  const url = String(token.attrGet(attribute));
29
30
  if (isRelativeUrl(url))
30
31
  token.attrSet(attribute, baseUrl + url);
32
+ else if (siteBaseUrl && /^\/(?!\/)/.test(url))
33
+ token.attrSet(attribute, siteBaseUrl + url);
31
34
  }
32
35
  }
33
36
  });
@@ -50,6 +53,10 @@ export const createMarkdown = ({ typographer = true } = {}) => {
50
53
  return markdown;
51
54
  };
52
55
  /**
53
- * Render markdown to HTML, resolving relative URLs against a folder URL.
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'
54
61
  */
55
- export const renderMarkdown = (markdown, source, baseUrl) => markdown.render(source, { baseUrl });
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;