@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
@@ -1,5 +1,8 @@
1
- import { parse } from "yaml";
2
- import { isSlug } from "../slug/index.js";
1
+ import { isAbsolute, normalize, sep } from "node:path";
2
+ import { checkEmbedPlugins } from "../../embeds/index.js";
3
+ import { isSlug, slugify } from "../slug/index.js";
4
+ import { parseMetadata, parseTypeMetadata, } from "../metadata/index.js";
5
+ import { metadataLayout, parseMetadataGroups, } from "../metadataGroups/index.js";
3
6
  /** Settings under `generate` */
4
7
  const GENERATE_KEYS = [
5
8
  "article",
@@ -9,17 +12,31 @@ const GENERATE_KEYS = [
9
12
  "tag",
10
13
  ];
11
14
  /** Settings of an article type */
12
- const TYPE_KEYS = ["labelSingle", "labelPlural", "path", "generate"];
13
- /** Blog settings */
15
+ const TYPE_KEYS = [
16
+ "labelSingle",
17
+ "labelPlural",
18
+ "path",
19
+ "generate",
20
+ "metadata",
21
+ "author",
22
+ ];
23
+ /** The site's settings */
14
24
  const CONFIG_KEYS = [
15
25
  "name",
16
26
  "description",
17
27
  "path",
18
28
  "outputDir",
29
+ "articlesDir",
30
+ "templatesDir",
31
+ "staticDir",
19
32
  "publishDir",
20
33
  "siteUrl",
21
34
  "reservedPaths",
22
35
  "types",
36
+ "plugins",
37
+ "metadata",
38
+ "metadataGroups",
39
+ "author",
23
40
  ];
24
41
  /** List folders that can't be used as article types */
25
42
  export const RESERVED_TYPES = ["tags", "authors"];
@@ -47,7 +64,7 @@ export const defaultTypeConfig = (type) => {
47
64
  /** Check a value is a map, throwing a config error if not */
48
65
  const asMap = (value, what) => {
49
66
  if (!value || typeof value !== "object" || Array.isArray(value))
50
- throw new Error(`config.yml: ${what} must be a map`);
67
+ throw new Error(`${what} must be a map of settings`);
51
68
  return value;
52
69
  };
53
70
  /**
@@ -57,21 +74,21 @@ const parsePath = (value, what) => {
57
74
  if (value === undefined || value === null)
58
75
  return undefined;
59
76
  if (typeof value !== "string" || (value !== "" && !isSlug(value)))
60
- throw new Error(`config.yml: ${what} must be lowercase kebab-case, or "" for the root`);
77
+ throw new Error(`${what} must be lowercase kebab-case, or "" for the root`);
61
78
  return value;
62
79
  };
63
80
  /** Throw a config error for keys that aren't allowed */
64
81
  const checkKeys = (map, allowed, what) => {
65
82
  const unknown = Object.keys(map).filter((key) => !allowed.includes(key));
66
83
  if (unknown.length)
67
- throw new Error(`config.yml: unknown ${what} setting${unknown.length > 1 ? "s" : ""} ${unknown.map((key) => `"${key}"`).join(", ")}`);
84
+ throw new Error(`unknown ${what} setting${unknown.length > 1 ? "s" : ""} ${unknown.map((key) => `"${key}"`).join(", ")}`);
68
85
  };
69
86
  /**
70
87
  * Parse one article type's settings, filling in defaults.
71
88
  */
72
89
  const parseTypeConfig = (type, value) => {
73
90
  if (!isSlug(type) || RESERVED_TYPES.includes(type))
74
- throw new Error(`config.yml: type "${type}" must be lowercase kebab-case and not ${RESERVED_TYPES.join(" or ")}`);
91
+ throw new Error(`type "${type}" must be lowercase kebab-case and not ${RESERVED_TYPES.join(" or ")}`);
75
92
  const config = defaultTypeConfig(type);
76
93
  if (value === null || value === undefined)
77
94
  return config;
@@ -82,10 +99,12 @@ const parseTypeConfig = (type, value) => {
82
99
  if (text === undefined)
83
100
  continue;
84
101
  if (typeof text !== "string" || !text.trim())
85
- throw new Error(`config.yml: "types.${type}.${label}" must be a non-empty string`);
102
+ throw new Error(`"types.${type}.${label}" must be a non-empty string`);
86
103
  config[label] = text.trim();
87
104
  }
88
105
  config.path = parsePath(fields.path, `"types.${type}.path"`) ?? type;
106
+ config.author = parseAuthor(fields.author, `"types.${type}.author"`);
107
+ config.metadata = parseTypeMetadata(fields.metadata, `"types.${type}.metadata"`);
89
108
  const generate = fields.generate;
90
109
  if (generate === false)
91
110
  for (const key of GENERATE_KEYS)
@@ -98,7 +117,7 @@ const parseTypeConfig = (type, value) => {
98
117
  if (flag === undefined)
99
118
  continue;
100
119
  if (typeof flag !== "boolean")
101
- throw new Error(`config.yml: "types.${type}.generate.${key}" must be true or false`);
120
+ throw new Error(`"types.${type}.generate.${key}" must be true or false`);
102
121
  config.generate[key] = flag;
103
122
  }
104
123
  }
@@ -108,13 +127,45 @@ const parseTypeConfig = (type, value) => {
108
127
  config.generate[key] = false;
109
128
  return config;
110
129
  };
130
+ /**
131
+ * Read a default author: a name, a map with a `name` and optionally an `email` and `url` (like an article's), or `false`
132
+ * for none.
133
+ *
134
+ * @param what - the setting, for errors, e.g. '"author"'
135
+ *
136
+ * @example
137
+ * parseAuthor("Matt", '"author"'); // { name: "Matt" }
138
+ * parseAuthor(false, '"author"'); // false
139
+ */
140
+ const parseAuthor = (value, what) => {
141
+ if (value === undefined || value === null)
142
+ return undefined;
143
+ if (value === false)
144
+ return false;
145
+ const nameNeeded = `${what} needs a name with letters or numbers, or false for no author`;
146
+ if (typeof value === "string") {
147
+ if (!slugify(value))
148
+ throw new Error(nameNeeded);
149
+ return { name: value.trim() };
150
+ }
151
+ const fields = asMap(value, what);
152
+ checkKeys(fields, ["name", "email", "url"], what);
153
+ const name = optionalString(fields, "name");
154
+ if (!name || !slugify(name))
155
+ throw new Error(nameNeeded);
156
+ return {
157
+ name,
158
+ email: optionalString(fields, "email"),
159
+ url: optionalString(fields, "url"),
160
+ };
161
+ };
111
162
  /**
112
163
  * Read a required, non-empty string field from parsed YAML.
113
164
  */
114
165
  const requireString = (data, field) => {
115
166
  const value = data[field];
116
167
  if (typeof value !== "string" || value.trim() === "")
117
- throw new Error(`config.yml: "${field}" must be a non-empty string`);
168
+ throw new Error(`"${field}" must be a non-empty string`);
118
169
  return value.trim();
119
170
  };
120
171
  /**
@@ -129,48 +180,119 @@ const optionalString = (data, field) => data[field] === undefined || data[field]
129
180
  const parseSiteUrl = (data) => {
130
181
  const value = optionalString(data, "siteUrl");
131
182
  if (value !== undefined && !/^https?:\/\/[^/]/.test(value))
132
- throw new Error('config.yml: "siteUrl" must be an absolute http(s) URL, e.g. "https://example.com"');
183
+ throw new Error('"siteUrl" must be an absolute http(s) URL, e.g. "https://example.com"');
133
184
  return value;
134
185
  };
135
186
  /**
136
187
  * Read the optional list of reserved paths: URL path segments or file names, e.g. "app" or "jwks.json".
137
188
  */
189
+ /** The site's source folders' settings, with their defaults */
190
+ export const SOURCE_FOLDERS = {
191
+ articlesDir: "articles",
192
+ templatesDir: "templates",
193
+ staticDir: "static",
194
+ };
195
+ /**
196
+ * Read an optional source folder setting: a folder inside the site folder (not the site folder itself). Gives the folder
197
+ * with "/" separators.
198
+ */
199
+ const parseFolder = (data, field) => {
200
+ const value = optionalString(data, field) ?? SOURCE_FOLDERS[field];
201
+ const folder = normalize(value).split(sep).join("/").replace(/\/$/, "");
202
+ if (isAbsolute(value) || folder === "." || folder.split("/")[0] === "..")
203
+ throw new Error(`"${field}" must be a folder inside the site folder, got "${value}"`);
204
+ return folder;
205
+ };
206
+ /** Whether one folder (with "/" separators) is the other or inside it */
207
+ const overlaps = (a, b) => a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
208
+ /**
209
+ * Read the source folders (articles, templates and static files), which must be apart from each other.
210
+ */
211
+ const parseSourceFolders = (data) => {
212
+ const fields = Object.keys(SOURCE_FOLDERS);
213
+ const folders = Object.fromEntries(fields.map((field) => [field, parseFolder(data, field)]));
214
+ fields.forEach((a, i) => {
215
+ for (const b of fields.slice(i + 1))
216
+ if (overlaps(folders[a], folders[b]))
217
+ throw new Error(`"${a}" and "${b}" must be apart from each other, got "${folders[a]}" and "${folders[b]}"`);
218
+ });
219
+ return folders;
220
+ };
221
+ /**
222
+ * Read the optional embed plugins. Package names in the config file are loaded by loadSiteConfig before this, so only
223
+ * plugin objects are left.
224
+ */
225
+ const parsePlugins = (data) => {
226
+ const value = data.plugins;
227
+ if (value === undefined || value === null)
228
+ return [];
229
+ if (!Array.isArray(value))
230
+ throw new Error('"plugins" must be a list of embed plugin package names (or, in a JavaScript config file, embed plugins)');
231
+ if (value.some((plugin) => typeof plugin === "string"))
232
+ throw new Error('"plugins" package names are loaded by loadSiteConfig; pass embed plugins to parseConfig');
233
+ return checkEmbedPlugins(value);
234
+ };
138
235
  const parseReservedPaths = (data) => {
139
236
  const value = data.reservedPaths;
140
237
  if (value === undefined || value === null)
141
238
  return [];
142
239
  if (!Array.isArray(value) ||
143
240
  value.some((path) => typeof path !== "string" || !/^[a-z0-9][a-z0-9._-]*$/.test(path)))
144
- throw new Error('config.yml: "reservedPaths" must be a list of lowercase paths at the website\'s root, e.g. ["app", "api"]');
241
+ throw new Error('"reservedPaths" must be a list of lowercase paths at the website\'s root, e.g. ["app", "api"]');
145
242
  return value;
146
243
  };
147
244
  /**
148
- * Parse and validate the contents of the blog's `config.yml`.
149
- *
150
- * @example
151
- * parseConfig("name: News\ndescription: Updates\noutputDir: dist");
245
+ * Validate the settings read from the site's config file and fill in defaults.
152
246
  */
153
- export const parseConfig = (text) => {
154
- const data = parse(text);
155
- if (!data || typeof data !== "object" || Array.isArray(data))
156
- throw new Error("config.yml: expected a map of settings");
157
- const fields = data;
158
- checkKeys(fields, CONFIG_KEYS, "blog");
247
+ const validateConfig = (data) => {
248
+ const fields = asMap(data, "the config file");
249
+ checkKeys(fields, CONFIG_KEYS, "site");
159
250
  const types = fields.types === undefined || fields.types === null
160
251
  ? {}
161
252
  : asMap(fields.types, '"types"');
162
- const config = {
253
+ const metadata = parseMetadata(fields.metadata);
254
+ const metadataGroups = parseMetadataGroups(fields.metadataGroups);
255
+ // Every field's group, and what each field and group follows, must exist
256
+ metadataLayout(metadata, metadataGroups);
257
+ const typeConfigs = Object.fromEntries(Object.entries(types).map(([type, value]) => [
258
+ type,
259
+ parseTypeConfig(type, value),
260
+ ]));
261
+ // Types can only use custom metadata that is defined
262
+ for (const [type, { metadata: keys }] of Object.entries(typeConfigs))
263
+ for (const key of keys || [])
264
+ if (!(key in metadata))
265
+ throw new Error(`"types.${type}.metadata" lists "${key}", which isn't defined in "metadata"`);
266
+ return {
163
267
  name: requireString(fields, "name"),
164
268
  description: requireString(fields, "description"),
165
269
  path: parsePath(fields.path, '"path"') ?? "",
166
- outputDir: optionalString(fields, "outputDir") ?? "dist",
270
+ outputDir: optionalString(fields, "outputDir") ?? "build",
271
+ ...parseSourceFolders(fields),
167
272
  publishDir: optionalString(fields, "publishDir"),
168
273
  siteUrl: parseSiteUrl(fields),
169
274
  reservedPaths: parseReservedPaths(fields),
170
- types: Object.fromEntries(Object.entries(types).map(([type, value]) => [
171
- type,
172
- parseTypeConfig(type, value),
173
- ])),
275
+ plugins: parsePlugins(fields),
276
+ metadata,
277
+ metadataGroups,
278
+ author: parseAuthor(fields.author, '"author"'),
279
+ types: typeConfigs,
174
280
  };
175
- return config;
281
+ };
282
+ /**
283
+ * Validate the settings read from the site's config file (YAML, JSON or JavaScript) and fill in defaults. Errors start
284
+ * with the config file's name.
285
+ *
286
+ * @param source - the config file's name, for errors
287
+ *
288
+ * @example
289
+ * parseConfig({ name: "News", description: "Updates" }, "edaha.config.json");
290
+ */
291
+ export const parseConfig = (data, source = "config") => {
292
+ try {
293
+ return validateConfig(data);
294
+ }
295
+ catch (error) {
296
+ throw new Error(`${source}: ${error.message}`, { cause: error });
297
+ }
176
298
  };
@@ -0,0 +1,58 @@
1
+ import { type EdahaConfig } from "../config/index.ts";
2
+ import type { Logger } from "../types/index.ts";
3
+ /** Config file names (without extension), in the order they are looked for */
4
+ export declare const CONFIG_NAMES: string[];
5
+ /** Config file extensions, in the order they are looked for */
6
+ export declare const CONFIG_EXTENSIONS: string[];
7
+ /** Every config file name, in the order they are looked for */
8
+ export declare const CONFIG_FILES: string[];
9
+ /** A site's config file, its folder and its validated settings */
10
+ export interface SiteConfig {
11
+ /** The config file's absolute path */
12
+ configFile: string;
13
+ /** The site folder: the config file's folder, which the paths in its settings are relative to */
14
+ siteDir: string;
15
+ /** The validated settings */
16
+ config: EdahaConfig;
17
+ }
18
+ /** Options for finding and reading a site's config file */
19
+ export interface SiteConfigOptions {
20
+ /** The folder to look for a config file in, before the nearest package.json's folder. Default: the current folder */
21
+ siteDir?: string | undefined;
22
+ /** The config file to use instead of looking for one */
23
+ configFile?: string | undefined;
24
+ /** Where warnings go */
25
+ logger?: Logger | undefined;
26
+ }
27
+ /**
28
+ * The folder of the nearest package.json, from a folder up to the file system's root, or undefined if there is none.
29
+ *
30
+ * @example
31
+ * await packageDir("/projects/my-site/site"); // "/projects/my-site"
32
+ */
33
+ export declare const packageDir: (dir: string) => Promise<string | undefined>;
34
+ /**
35
+ * Find a site's config file: the first of CONFIG_FILES in a folder, then in the nearest package.json's folder. Warns
36
+ * when a folder has more than one. Throws if there is none.
37
+ *
38
+ * @example
39
+ * await findConfigFile("my-site"); // "/projects/my-site/edahaconfig.yml"
40
+ */
41
+ export declare const findConfigFile: (dir: string, logger?: Logger) => Promise<string>;
42
+ /**
43
+ * Read a config file's settings, by its extension: YAML (`.yml`, `.yaml`), JSON (`.json`), or JavaScript (`.js`, `.cjs`,
44
+ * `.mjs`) whose default export is the settings object. A changed JavaScript file is imported again. Throws, naming the
45
+ * file, if it can't be read.
46
+ *
47
+ * @example
48
+ * await readConfigFile("my-site/edaha.config.mjs"); // { name: "My site", ... }
49
+ */
50
+ export declare const readConfigFile: (file: string) => Promise<unknown>;
51
+ /**
52
+ * Find (or use the given) config file, read it and validate its settings. The site folder is the config file's folder.
53
+ * Embed plugin packages named in `plugins` are loaded from it.
54
+ *
55
+ * @example
56
+ * const { siteDir, config } = await loadSiteConfig({ siteDir: "my-site" });
57
+ */
58
+ export declare const loadSiteConfig: (options?: SiteConfigOptions) => Promise<SiteConfig>;
@@ -0,0 +1,122 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { readFile, stat } from "node:fs/promises";
10
+ import { basename, dirname, extname, join, resolve } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import { parse } from "yaml";
13
+ import { loadPlugins } from "../../embeds/index.js";
14
+ import { parseConfig } from "../config/index.js";
15
+ /** Config file names (without extension), in the order they are looked for */
16
+ export const CONFIG_NAMES = [
17
+ ".edahaconfigrc",
18
+ ".edahaconfig",
19
+ "edahaconfigrc",
20
+ "edahaconfig",
21
+ "edaha.config",
22
+ ];
23
+ /** Config file extensions, in the order they are looked for */
24
+ export const CONFIG_EXTENSIONS = ["yml", "yaml", "json", "js", "cjs", "mjs"];
25
+ /** Every config file name, in the order they are looked for */
26
+ export const CONFIG_FILES = CONFIG_NAMES.flatMap((name) => CONFIG_EXTENSIONS.map((extension) => `${name}.${extension}`));
27
+ /** A file's modification time, or undefined if it isn't a file */
28
+ const fileTime = (path) => stat(path).then((stats) => (stats.isFile() ? stats.mtimeMs : undefined), () => undefined);
29
+ /**
30
+ * The folder of the nearest package.json, from a folder up to the file system's root, or undefined if there is none.
31
+ *
32
+ * @example
33
+ * await packageDir("/projects/my-site/site"); // "/projects/my-site"
34
+ */
35
+ export const packageDir = async (dir) => {
36
+ for (let folder = resolve(dir);; folder = dirname(folder)) {
37
+ if ((await fileTime(join(folder, "package.json"))) !== undefined)
38
+ return folder;
39
+ if (dirname(folder) === folder)
40
+ return undefined;
41
+ }
42
+ };
43
+ /**
44
+ * Find a site's config file: the first of CONFIG_FILES in a folder, then in the nearest package.json's folder. Warns
45
+ * when a folder has more than one. Throws if there is none.
46
+ *
47
+ * @example
48
+ * await findConfigFile("my-site"); // "/projects/my-site/edahaconfig.yml"
49
+ */
50
+ export const findConfigFile = async (dir, logger) => {
51
+ const folders = [resolve(dir), await packageDir(dir)].filter((folder, index, all) => folder !== undefined && all.indexOf(folder) === index);
52
+ for (const folder of folders) {
53
+ const times = await Promise.all(CONFIG_FILES.map((name) => fileTime(join(folder, name))));
54
+ const found = CONFIG_FILES.filter((_, i) => times[i] !== undefined);
55
+ if (!found.length)
56
+ continue;
57
+ if (found.length > 1)
58
+ logger?.warn(`${folder} has several config files (${found.join(", ")}); using ${found[0]}`);
59
+ return join(folder, found[0]);
60
+ }
61
+ throw new Error(`No config file found in ${folders.join(" or ")}. Add one named ${CONFIG_NAMES.join(", ")} ending in .${CONFIG_EXTENSIONS.join(", .")}, or name it with --config.`);
62
+ };
63
+ /**
64
+ * Read a config file's settings, by its extension: YAML (`.yml`, `.yaml`), JSON (`.json`), or JavaScript (`.js`, `.cjs`,
65
+ * `.mjs`) whose default export is the settings object. A changed JavaScript file is imported again. Throws, naming the
66
+ * file, if it can't be read.
67
+ *
68
+ * @example
69
+ * await readConfigFile("my-site/edaha.config.mjs"); // { name: "My site", ... }
70
+ */
71
+ export const readConfigFile = async (file) => {
72
+ const path = resolve(file);
73
+ const extension = extname(path).slice(1);
74
+ try {
75
+ const time = await fileTime(path);
76
+ if (time === undefined)
77
+ throw new Error("file not found");
78
+ if (extension === "yml" || extension === "yaml")
79
+ return parse(await readFile(path, "utf8"));
80
+ if (extension === "json")
81
+ return JSON.parse(await readFile(path, "utf8"));
82
+ if (CONFIG_EXTENSIONS.includes(extension)) {
83
+ // The modification time makes a changed file a new module, rather than the one imported before
84
+ const url = `${pathToFileURL(path).href}?mtime=${time}`;
85
+ return (await import(__rewriteRelativeImportExtension(url))).default;
86
+ }
87
+ throw new Error(`config files must end in .${CONFIG_EXTENSIONS.join(", .")}`);
88
+ }
89
+ catch (error) {
90
+ throw new Error(`${basename(path)}: ${error.message}`, {
91
+ cause: error,
92
+ });
93
+ }
94
+ };
95
+ /**
96
+ * Find (or use the given) config file, read it and validate its settings. The site folder is the config file's folder.
97
+ * Embed plugin packages named in `plugins` are loaded from it.
98
+ *
99
+ * @example
100
+ * const { siteDir, config } = await loadSiteConfig({ siteDir: "my-site" });
101
+ */
102
+ export const loadSiteConfig = async (options = {}) => {
103
+ const configFile = options.configFile
104
+ ? resolve(options.configFile)
105
+ : await findConfigFile(options.siteDir ?? ".", options.logger);
106
+ const siteDir = dirname(configFile);
107
+ const data = await readConfigFile(configFile);
108
+ if (data && typeof data === "object" && "plugins" in data)
109
+ try {
110
+ data.plugins = await loadPlugins(data.plugins, siteDir);
111
+ }
112
+ catch (error) {
113
+ throw new Error(`${basename(configFile)}: ${error.message}`, {
114
+ cause: error,
115
+ });
116
+ }
117
+ return {
118
+ configFile,
119
+ siteDir,
120
+ config: parseConfig(data, basename(configFile)),
121
+ };
122
+ };
@@ -0,0 +1,93 @@
1
+ import type { MetadataSchema } from "../metadata/index.ts";
2
+ /** A value a condition compares with */
3
+ export type ConditionValue = string | number | boolean | null;
4
+ /** Operators comparing a value with one value */
5
+ export type ConditionOperator = "=" | "!=" | ">" | ">=" | "<" | "<=";
6
+ /** Operators checking whether a value is in a list of values */
7
+ export type ConditionListOperator = "in" | "not-in";
8
+ /**
9
+ * One condition: a value's path (dot notation from the top of the values, e.g. "credit.name" or "images.0"), an
10
+ * operator, and what it is compared with.
11
+ *
12
+ * @example
13
+ * ["layout", "=", "large"]
14
+ * ["layout", "in", ["slim", "large"]]
15
+ */
16
+ export type MatchCondition = readonly [string, ConditionOperator, ConditionValue] | readonly [string, ConditionListOperator, readonly ConditionValue[]];
17
+ /** Conditions that must all match (`and`), or any of which must match (`or`) */
18
+ export type MatchConditionsUnion = {
19
+ readonly and: FieldConditions;
20
+ } | {
21
+ readonly or: FieldConditions;
22
+ };
23
+ /** One group of conditions, or a list of conditions and groups that must all match */
24
+ export type MatchConditions = MatchConditionsUnion | readonly FieldConditions[];
25
+ /** A field's `showWhen` or `hideWhen`: one condition, or groups of them */
26
+ export type FieldConditions = MatchCondition | MatchConditions;
27
+ /** The settings `$edahaField` can have besides the field's kind and labels */
28
+ export interface EdahaFieldExtensions {
29
+ /** The value used when there is none (also saved by the editor) */
30
+ defaultValue?: ConditionValue | undefined;
31
+ /** Show the field (and keep its value) only when these match */
32
+ showWhen?: FieldConditions | undefined;
33
+ /** Hide the field (and leave out its value) when these match */
34
+ hideWhen?: FieldConditions | undefined;
35
+ }
36
+ /**
37
+ * Check a field's `showWhen` or `hideWhen` is made of conditions and `and`/`or` groups. Throws an Error naming where
38
+ * the problem is.
39
+ *
40
+ * @example
41
+ * checkConditions({ or: [["layout", "=", "slim"], ["layout", "=", "large"]] }, '"showWhen"');
42
+ */
43
+ export declare const checkConditions: (value: unknown, what: string) => void;
44
+ /**
45
+ * Check an `$edahaField`'s `defaultValue`, `showWhen` and `hideWhen`. Throws an Error naming where the problem is.
46
+ *
47
+ * @example
48
+ * checkFieldExtensions({ select: true, defaultValue: "large" }, '"metadata.layout.$edahaField"');
49
+ */
50
+ export declare const checkFieldExtensions: (field: Record<string, unknown>, what: string) => void;
51
+ /**
52
+ * The value at a dot path inside values, e.g. "credit.name" or "images.0".
53
+ *
54
+ * @example
55
+ * valueAt({ credit: { name: "Ann" } }, "credit.name"); // "Ann"
56
+ */
57
+ export declare const valueAt: (values: unknown, path: string) => unknown;
58
+ /**
59
+ * Whether values match conditions: one condition, `and` (all match) or `or` (any match) groups, or a list (all match).
60
+ *
61
+ * @example
62
+ * matchesConditions({ layout: "slim" }, { or: [["layout", "=", "slim"], ["layout", "=", "large"]] }); // true
63
+ * matchesConditions({ layout: "slim" }, ["layout", "in", ["large"]]); // false
64
+ */
65
+ export declare const matchesConditions: (values: unknown, conditions: FieldConditions) => boolean;
66
+ /**
67
+ * Whether a field shows: its `showWhen` matches (or it has none), and its `hideWhen` doesn't (or it has none).
68
+ *
69
+ * @example
70
+ * fieldShown({ checkbox: true, showWhen: ["layout", "=", "large"] }, { layout: "slim" }); // false
71
+ */
72
+ export declare const fieldShown: (field: EdahaFieldExtensions | undefined, values: unknown) => boolean;
73
+ /** Values with their fields' defaults and hidden fields applied, and which fields are hidden */
74
+ export interface ResolvedFields {
75
+ /** The values: a shown field without a value has its default, and a hidden field's value is left out */
76
+ values: Record<string, unknown>;
77
+ /** The hidden fields' paths, in dot notation, e.g. "credit.name" */
78
+ hidden: Set<string>;
79
+ }
80
+ /**
81
+ * Apply fields' `defaultValue`, `showWhen` and `hideWhen` to values: shown fields without a value get their default,
82
+ * and hidden fields' values (and those of fields in a hidden group) are left out. Conditions are checked again until
83
+ * nothing changes, as hiding or filling in one value can show or hide another. The values are in the fields' order,
84
+ * then any values without a field.
85
+ *
86
+ * @example
87
+ * resolveFields(
88
+ * { layout: { type: "string", $edahaField: { select: true, defaultValue: "large" } },
89
+ * tracklist: { type: "boolean", $edahaField: { checkbox: true, hideWhen: ["layout", "=", "slim"] } } },
90
+ * { tracklist: true },
91
+ * ); // { values: { layout: "large", tracklist: true }, hidden: Set {} }
92
+ */
93
+ export declare const resolveFields: (schemas: Record<string, MetadataSchema>, values: Record<string, unknown>) => ResolvedFields;