@lvl99dotcom/edaha-editor 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,693 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdir, readdir, readFile, rename, rm, stat, writeFile, } from "node:fs/promises";
3
+ import { basename, extname, join } from "node:path";
4
+ import { stringify } from "yaml";
5
+ import { EMBED_PAGE_PARTS, } from "@lvl99dotcom/edaha.md/embeds";
6
+ import { DEFAULT_HEADER_FORMAT, headerFormat, loadArticle, parseArticleConfig, splitArticle, splitContent, } from "@lvl99dotcom/edaha.md/generator/article";
7
+ import { articlePageData, DEFAULT_SITE_URL, siteData, } from "@lvl99dotcom/edaha.md/generator/build";
8
+ import { defaultTypeConfig, RESERVED_TYPES, } from "@lvl99dotcom/edaha.md/generator/config";
9
+ import { loadSiteConfig, } from "@lvl99dotcom/edaha.md/generator/configFile";
10
+ import { createMarkdown, renderMarkdown, } from "@lvl99dotcom/edaha.md/generator/markdown";
11
+ import { Templates } from "@lvl99dotcom/edaha.md/generator/templates";
12
+ import { THEME_DIR } from "@lvl99dotcom/edaha.md/theme";
13
+ import { slugProblem } from "@lvl99dotcom/edaha.md/generator/urls";
14
+ import { isSlug, slugify } from "@lvl99dotcom/edaha.md/generator/slug";
15
+ import { editorHtmlToMarkdown, filesUrl, markdownToEditorHtml, } from "../convert/index.js";
16
+ import { articleMetadata, CORE_FIELDS, MetadataValidator, typeMetadataKeys, } from "@lvl99dotcom/edaha.md/generator/metadata";
17
+ import { metadataLayout } from "@lvl99dotcom/edaha.md/generator/metadataGroups";
18
+ import { ArticleIndex, articleFilters, queryArticles, recentArticles, RECENT_COUNT, } from "../articleIndex/index.js";
19
+ import { changeArticleReferences, fileFilters, fileReferences, queryFiles, } from "../files/index.js";
20
+ import { folderPath, folderUrl } from "@lvl99dotcom/edaha.md/generator/urls";
21
+ /** An editor request that can't be done, with the HTTP status to answer with */
22
+ export class EditorError extends Error {
23
+ status;
24
+ /** Problems with the article's custom metadata, when saving it was refused because of them */
25
+ problems;
26
+ constructor(status, message, problems) {
27
+ super(message);
28
+ this.status = status;
29
+ this.problems = problems;
30
+ }
31
+ }
32
+ /** How many previews the editor remembers (the newest) */
33
+ export const MAX_PREVIEWS = 20;
34
+ /** How many embed frames the editor remembers (the newest) */
35
+ export const MAX_EMBED_FRAMES = 200;
36
+ /** Whether a path exists */
37
+ const exists = (path) => stat(path).then(() => true, () => false);
38
+ /**
39
+ * Check an article type and slug are valid folder names. Throws a 400 EditorError if not.
40
+ */
41
+ export const checkLocation = (type, slug) => {
42
+ if (!isSlug(type) || RESERVED_TYPES.includes(type))
43
+ throw new EditorError(400, `Type "${type}" must be lowercase kebab-case and not ${RESERVED_TYPES.join(" or ")}`);
44
+ if (!isSlug(slug))
45
+ throw new EditorError(400, `Slug "${slug}" must be lowercase kebab-case`);
46
+ };
47
+ /**
48
+ * The URL relative URLs in an article's body point at in the editor: its saved folder's file URL, or "" for an article
49
+ * that isn't saved yet (and has no files).
50
+ *
51
+ * @example
52
+ * bodyBaseUrl({ type: "news", slug: "hello" }); // "/files/news/hello/"
53
+ * bodyBaseUrl(undefined); // ""
54
+ */
55
+ export const bodyBaseUrl = (location) => {
56
+ if (!location)
57
+ return "";
58
+ checkLocation(location.type, location.slug);
59
+ return filesUrl(location.type, location.slug);
60
+ };
61
+ /**
62
+ * Make an uploaded file name safe: a slug of its base name plus its lowercase extension.
63
+ *
64
+ * @example
65
+ * safeFileName("My Photo (1).JPG"); // "my-photo-1.jpg"
66
+ */
67
+ export const safeFileName = (name) => {
68
+ const extension = extname(name)
69
+ .toLowerCase()
70
+ .replace(/[^.a-z0-9]/g, "");
71
+ const base = slugify(name.slice(0, name.length - extname(name).length));
72
+ if (!base)
73
+ throw new EditorError(400, `"${name}" is not a usable file name`);
74
+ return base + extension;
75
+ };
76
+ /**
77
+ * Write an article's markdown source: the config header (YAML by default, or JSON), the title as an H1 and the body.
78
+ * The type (always the article's folder) and defaults (empty lists) are left out to keep the header short.
79
+ *
80
+ * @param format - the config header's format
81
+ *
82
+ * @example
83
+ * serializeArticle({ type: "article", slug: "hi", status: "published", date, title: "Hi", tags: [], attachments: [] }, "Body");
84
+ * serializeArticle(data, "Body", "json"); // '<!--json\n{\n "status": "published", ...'
85
+ */
86
+ export const serializeArticle = (data, body, format = DEFAULT_HEADER_FORMAT) => {
87
+ // No author is written as `false`; a name alone as just the name
88
+ const author = data.author === false
89
+ ? false
90
+ : data.author && (data.author.email || data.author.url)
91
+ ? Object.fromEntries(Object.entries(data.author).filter(([, value]) => value))
92
+ : data.author?.name;
93
+ const config = Object.fromEntries(Object.entries({
94
+ status: data.status,
95
+ date: data.date,
96
+ author,
97
+ template: data.template,
98
+ excerpt: data.excerpt,
99
+ thumbnail: data.thumbnail,
100
+ attachments: data.attachments.length
101
+ ? data.attachments.map((attachment) => Object.fromEntries(Object.entries(attachment).filter(([, value]) => value)))
102
+ : undefined,
103
+ tags: data.tags.length ? data.tags : undefined,
104
+ // Custom metadata and other settings, after the core ones
105
+ ...data.meta,
106
+ }).filter(([, value]) => value !== undefined && value !== ""));
107
+ const header = format === "json"
108
+ ? `${JSON.stringify(config, null, 2)}\n`
109
+ : stringify(config);
110
+ return `<!--${format}\n${header}-->\n\n# ${data.title.trim()}\n\n${body}\n`;
111
+ };
112
+ /**
113
+ * Reads and writes articles in the site's articles folder (`articlesDir`) for the editor, and renders previews with the site's
114
+ * templates over the default theme's. Articles are listed and searched from an in-memory index (see `ArticleIndex`),
115
+ * read on first use and kept up to date as the editor saves and deletes articles, and (unless `watch` is false) as their
116
+ * files change outside the editor. Call `close` to stop watching.
117
+ *
118
+ * @example
119
+ * const store = new ArticleStore(await loadSiteConfig({ siteDir: "my-site" }));
120
+ * await store.query({ search: "hello" });
121
+ * store.close();
122
+ */
123
+ export class ArticleStore {
124
+ articlesDir;
125
+ configFile;
126
+ /** The site's templates folder, relative to the site folder */
127
+ templatesDir;
128
+ /** The site's static files folder, relative to the site folder */
129
+ staticDir;
130
+ /** Previews' unsaved data by ID, the newest last (see `rememberPreview`) */
131
+ previews = new Map();
132
+ /** Embed blocks shown in the editor's body by ID, the newest last (see `rememberEmbedFrame`) */
133
+ embedFrames = new Map();
134
+ siteDir;
135
+ themeDir;
136
+ /** What custom metadata is checked with, once read from the config file */
137
+ metadataLoad;
138
+ /** When the config file had last changed when its custom metadata was read */
139
+ metadataChanged;
140
+ /** The article index, once its first load has started */
141
+ indexLoad;
142
+ indexOptions;
143
+ /**
144
+ * @param site - the site's config file, folder (which holds the articles, templates and static files folders) and
145
+ * settings
146
+ * @param themeDir - the default theme folder that the site's templates and static files override
147
+ * @param options - how the article index watches for changes
148
+ */
149
+ constructor(site, themeDir = THEME_DIR, options = {}) {
150
+ this.indexOptions = options;
151
+ this.configFile = site.configFile;
152
+ this.siteDir = site.siteDir;
153
+ this.themeDir = themeDir;
154
+ this.articlesDir = join(site.siteDir, site.config.articlesDir);
155
+ this.templatesDir = site.config.templatesDir;
156
+ this.staticDir = site.config.staticDir;
157
+ }
158
+ /** The site's templates over the theme's */
159
+ loadTemplates() {
160
+ return new Templates([join(this.siteDir, this.templatesDir), join(this.themeDir, "templates")], console);
161
+ }
162
+ /**
163
+ * Read the config file again (loading its embed plugin packages), so changes to it show without restarting the
164
+ * editor
165
+ */
166
+ async config() {
167
+ return (await loadSiteConfig({ configFile: this.configFile })).config;
168
+ }
169
+ /**
170
+ * The template names an article of a type can use (see Templates.names).
171
+ */
172
+ templates(type) {
173
+ return this.loadTemplates().names(type);
174
+ }
175
+ /**
176
+ * The config file's embed plugins (read again each time, so changes show without restarting the editor).
177
+ */
178
+ async plugins() {
179
+ return (await this.config()).plugins;
180
+ }
181
+ /**
182
+ * The website's name, the author of articles that don't name one (the config file's `author`, the website without
183
+ * one, or none for `false`), and the types with their own default author.
184
+ */
185
+ async site() {
186
+ const config = await this.config();
187
+ return {
188
+ name: config.name,
189
+ author: config.author === false
190
+ ? undefined
191
+ : (config.author ?? { name: config.name }),
192
+ types: Object.fromEntries(Object.entries(config.types).flatMap(([type, { author }]) => author === undefined ? [] : [[type, author]])),
193
+ };
194
+ }
195
+ /**
196
+ * The article types from the config file, with their labels.
197
+ */
198
+ async types() {
199
+ const config = await this.config();
200
+ return Object.fromEntries(Object.entries(config.types).map(([type, { labelSingle, labelPlural }]) => [
201
+ type,
202
+ { labelSingle, labelPlural },
203
+ ]));
204
+ }
205
+ /** An article's folder */
206
+ dir(type, slug) {
207
+ checkLocation(type, slug);
208
+ return join(this.articlesDir, type, slug);
209
+ }
210
+ /** Read an article's source, or throw a 404 EditorError */
211
+ async source(type, slug) {
212
+ try {
213
+ return await readFile(join(this.dir(type, slug), "article.md"), "utf8");
214
+ }
215
+ catch (error) {
216
+ if (error instanceof EditorError)
217
+ throw error;
218
+ throw new EditorError(404, `Article ${type}/${slug} not found`);
219
+ }
220
+ }
221
+ /**
222
+ * What articles' custom metadata is checked with, from the config file: a check giving an article's problems from its
223
+ * type and settings, and the context `loadArticle` reads a type's metadata with. It is read again when the config file
224
+ * changes, which checks every article again.
225
+ */
226
+ async metadata() {
227
+ // Read again when the config file changes, as the editor keeps running while it is edited
228
+ const changed = (await stat(this.configFile)).mtimeMs;
229
+ if (this.metadataLoad && changed === this.metadataChanged)
230
+ return this.metadataLoad;
231
+ this.metadataChanged = changed;
232
+ // Articles are checked again with the new settings
233
+ const oldIndex = this.indexLoad;
234
+ this.indexLoad = undefined;
235
+ void oldIndex?.then((index) => index.close());
236
+ this.metadataLoad = (async () => {
237
+ const config = await this.config();
238
+ const validator = new MetadataValidator(config.metadata);
239
+ const context = (type) => {
240
+ const typeConfig = config.types[type] ?? defaultTypeConfig(type);
241
+ return {
242
+ validator,
243
+ keys: typeMetadataKeys(config.metadata, typeConfig.metadata),
244
+ typeLabel: typeConfig.labelPlural,
245
+ };
246
+ };
247
+ const check = (type, settings) => {
248
+ const { keys, typeLabel } = context(type);
249
+ return articleMetadata(settings, keys, validator, typeLabel).problems;
250
+ };
251
+ return { config, check, context };
252
+ })();
253
+ return this.metadataLoad;
254
+ }
255
+ /**
256
+ * Read the config file's custom metadata and every article now, rather than on first use, so the editor starts with
257
+ * every article checked.
258
+ */
259
+ async load() {
260
+ await this.index();
261
+ }
262
+ /**
263
+ * The custom metadata fields, which fields each configured type uses, and the groups the article form shows settings
264
+ * in.
265
+ */
266
+ async metadataInfo() {
267
+ const { config } = await this.metadata();
268
+ return {
269
+ definitions: config.metadata,
270
+ groups: metadataLayout(config.metadata, config.metadataGroups),
271
+ types: Object.fromEntries(Object.entries(config.types).flatMap(([type, { metadata }]) => metadata === undefined ? [] : [[type, metadata]])),
272
+ };
273
+ }
274
+ /** The article index, read on first use (and then watched, unless turned off) */
275
+ async index() {
276
+ // Checking the config file first starts afresh when it has changed
277
+ const { check } = await this.metadata();
278
+ this.indexLoad ??= (async () => {
279
+ const index = new ArticleIndex(this.articlesDir, {
280
+ ...this.indexOptions,
281
+ check,
282
+ });
283
+ await index.load();
284
+ if (this.indexOptions.watch !== false)
285
+ index.watch();
286
+ return index;
287
+ })();
288
+ return this.indexLoad;
289
+ }
290
+ /**
291
+ * Find articles by title, type, author, tag and status, sorted by title or date, a page at a time (see
292
+ * `queryArticles`).
293
+ *
294
+ * @example
295
+ * await store.query({ search: "hello", sort: "title", page: 2 });
296
+ */
297
+ async query(query) {
298
+ return queryArticles((await this.index()).articles(), query);
299
+ }
300
+ /**
301
+ * Each type's most recently changed articles, for the editor's nav (see `recentArticles`).
302
+ */
303
+ async recent(count = RECENT_COUNT) {
304
+ return recentArticles((await this.index()).articles(), count);
305
+ }
306
+ /**
307
+ * The types, authors and tags articles use, for the article browser's filters.
308
+ */
309
+ async filters() {
310
+ return articleFilters((await this.index()).articles());
311
+ }
312
+ /**
313
+ * Where articles are on the website, from the config file: a function giving an article's path (e.g. "/news/hello/";
314
+ * an index article is at its type's path), and the website's address without a trailing slash, if it has one.
315
+ */
316
+ async articleUrls() {
317
+ const config = await this.config();
318
+ const typeUrl = (type) => folderUrl(folderPath(config.path, (config.types[type] ?? defaultTypeConfig(type)).path));
319
+ return {
320
+ articleUrl: (type, slug) => slug === "index" ? typeUrl(type) : `${typeUrl(type)}${slug}/`,
321
+ siteUrl: config.siteUrl?.replace(/\/+$/, ""),
322
+ };
323
+ }
324
+ /**
325
+ * Find files in the articles' folders by name, kind and article type, sorted by name, kind, size or location, a page
326
+ * at a time, with their paths on the website.
327
+ *
328
+ * @example
329
+ * await store.queryFiles({ kind: "image", sort: "size" });
330
+ */
331
+ async queryFiles(query) {
332
+ const { articleUrl } = await this.articleUrls();
333
+ const page = queryFiles((await this.index()).files(), query);
334
+ return {
335
+ ...page,
336
+ files: page.files.map((file) => ({
337
+ ...file,
338
+ url: articleUrl(file.type, file.slug) + file.name,
339
+ })),
340
+ };
341
+ }
342
+ /** The kinds of files and the article types they are in, for the file browser's filters */
343
+ async fileFilters() {
344
+ return fileFilters((await this.index()).files());
345
+ }
346
+ /** A file's path in an article's folder. Throws a 404 EditorError if there is no such file. */
347
+ async filePath(type, slug, name) {
348
+ if (name === "article.md" ||
349
+ name !== basename(name) ||
350
+ name.startsWith("."))
351
+ throw new EditorError(404, "File not found");
352
+ const path = join(this.dir(type, slug), name);
353
+ if (!(await exists(path)))
354
+ throw new EditorError(404, "File not found");
355
+ return path;
356
+ }
357
+ /**
358
+ * Change references to a file in every article (see `changeArticleReferences`), or only find them with `dryRun`.
359
+ * Returns the articles that refer to it.
360
+ */
361
+ async changeReferences(file, change, dryRun = false) {
362
+ const index = await this.index();
363
+ const { articleUrl, siteUrl } = await this.articleUrls();
364
+ const url = articleUrl(file.type, file.slug) + file.name;
365
+ const changed = [];
366
+ for (const { type, slug } of index.articles()) {
367
+ const references = fileReferences(file.name, url, siteUrl, type === file.type && slug === file.slug);
368
+ let source;
369
+ let next;
370
+ try {
371
+ source = await this.source(type, slug);
372
+ next = changeArticleReferences(source, references, change);
373
+ }
374
+ catch {
375
+ // Articles that can't be read are left alone
376
+ continue;
377
+ }
378
+ if (next === undefined)
379
+ continue;
380
+ changed.push({ type, slug });
381
+ if (!dryRun) {
382
+ await writeFile(join(this.dir(type, slug), "article.md"), next);
383
+ await index.update(type, slug);
384
+ }
385
+ }
386
+ return changed;
387
+ }
388
+ /**
389
+ * The articles that refer to a file, e.g. to say which will change before replacing or deleting it.
390
+ */
391
+ async fileReferences(type, slug, name) {
392
+ await this.filePath(type, slug, name);
393
+ return this.changeReferences({ type, slug, name }, { remove: true }, true);
394
+ }
395
+ /**
396
+ * Replace a file in an article's folder with an uploaded one. With the same (safe) name, the file is overwritten;
397
+ * with another, the new file is saved under its own name, references to the old one switch to it in every article,
398
+ * and the old file is removed. Throws a 409 EditorError if another file already has the new name.
399
+ */
400
+ async replaceFile(type, slug, name, fileName, contents) {
401
+ const oldPath = await this.filePath(type, slug, name);
402
+ const newName = safeFileName(fileName);
403
+ const newPath = join(this.dir(type, slug), newName);
404
+ if (newName !== name && (await exists(newPath)))
405
+ throw new EditorError(409, `A file called ${newName} is already in ${type}/${slug}`);
406
+ await writeFile(newPath, contents);
407
+ const articles = [];
408
+ if (newName !== name) {
409
+ articles.push(...(await this.changeReferences({ type, slug, name }, { rename: newName })));
410
+ await rm(oldPath);
411
+ }
412
+ await (await this.index()).update(type, slug);
413
+ return { name: newName, articles };
414
+ }
415
+ /**
416
+ * Delete a file from an article's folder, removing references to it in every article (images are removed, links keep
417
+ * their text, a thumbnail is cleared and attachments are removed).
418
+ */
419
+ async deleteFile(type, slug, name) {
420
+ const path = await this.filePath(type, slug, name);
421
+ const articles = await this.changeReferences({ type, slug, name }, { remove: true });
422
+ await rm(path);
423
+ await (await this.index()).update(type, slug);
424
+ return { articles };
425
+ }
426
+ /** Stop watching the articles folder for changes */
427
+ close() {
428
+ void this.indexLoad?.then((index) => index.close());
429
+ }
430
+ /**
431
+ * Load an article for editing. Throws a 404 EditorError if it doesn't exist, or 422 if it can't be read.
432
+ */
433
+ async read(type, slug) {
434
+ const source = await this.source(type, slug);
435
+ const { header, content } = splitArticle(source);
436
+ let config;
437
+ try {
438
+ config = parseArticleConfig(header, type, `${type}/${slug}`);
439
+ }
440
+ catch (error) {
441
+ throw new EditorError(422, error.message);
442
+ }
443
+ const parts = splitContent(content);
444
+ // The title is edited separately, so a leading H1 stays out of the body; the readmore marker stays in
445
+ const body = content.replace(/^\s*#[ \t]+.+(?:\r?\n|$)/, "").trim();
446
+ const files = (await readdir(this.dir(type, slug)))
447
+ .filter((name) => name !== "article.md")
448
+ .sort();
449
+ const settings = header;
450
+ const { check } = await this.metadata();
451
+ return {
452
+ type,
453
+ slug,
454
+ status: config.status,
455
+ date: config.date,
456
+ title: config.title ?? parts.heading ?? "",
457
+ template: config.template,
458
+ author: config.author,
459
+ excerpt: config.excerpt,
460
+ thumbnail: config.thumbnail,
461
+ tags: config.tags,
462
+ attachments: config.attachments,
463
+ bodyHtml: markdownToEditorHtml(body, filesUrl(type, slug)),
464
+ files,
465
+ meta: Object.fromEntries(Object.entries(settings).filter(([key]) => !CORE_FIELDS.includes(key))),
466
+ problems: check(type, settings),
467
+ };
468
+ }
469
+ /**
470
+ * Save an article. When its type or slug changed, its folder (with all its files) moves to the new location.
471
+ * Pass no `from` for a new article. Returns where the article now is.
472
+ */
473
+ async save(data, from) {
474
+ const dir = this.dir(data.type, data.slug);
475
+ // The slug must not clash with other URLs
476
+ const config = await this.config();
477
+ const problem = slugProblem(data.slug, data.type, config.path, {
478
+ [data.type]: defaultTypeConfig(data.type),
479
+ ...config.types,
480
+ }, config.reservedPaths);
481
+ if (problem)
482
+ throw new EditorError(400, `The slug can't be used: ${problem}`);
483
+ if (!data.title.trim())
484
+ throw new EditorError(400, "The article needs a title");
485
+ // Custom metadata values that aren't valid aren't saved
486
+ const errors = (await this.metadata())
487
+ .check(data.type, data.meta ?? {})
488
+ .filter(({ level }) => level === "error");
489
+ if (errors.length)
490
+ throw new EditorError(400, `Some values aren't valid: ${errors.map(({ path, message }) => `"${path}" ${message}`).join("; ")}`, errors);
491
+ const moving = !from || from.type !== data.type || from.slug !== data.slug;
492
+ if (moving && (await exists(dir)))
493
+ throw new EditorError(409, `Article ${data.type}/${data.slug} already exists`);
494
+ // A saved article keeps its config header's format; new ones get the default
495
+ const format = from
496
+ ? headerFormat(await this.source(from.type, from.slug))
497
+ : DEFAULT_HEADER_FORMAT;
498
+ const fromDir = from ? this.dir(from.type, from.slug) : undefined;
499
+ // Files referenced from the body keep working after a move, as they are saved relative to the folder
500
+ const body = editorHtmlToMarkdown(data.bodyHtml, filesUrl(from?.type ?? data.type, from?.slug ?? data.slug));
501
+ const source = serializeArticle(data, body, format);
502
+ try {
503
+ parseArticleConfig(splitArticle(source).header, data.type, `${data.type}/${data.slug}`);
504
+ }
505
+ catch (error) {
506
+ throw new EditorError(400, error.message);
507
+ }
508
+ if (fromDir && moving) {
509
+ await mkdir(join(this.articlesDir, data.type), { recursive: true });
510
+ await rename(fromDir, dir);
511
+ }
512
+ else
513
+ await mkdir(dir, { recursive: true });
514
+ await writeFile(join(dir, "article.md"), source);
515
+ const index = await this.index();
516
+ if (from && moving)
517
+ index.delete(from.type, from.slug);
518
+ await index.update(data.type, data.slug);
519
+ return { type: data.type, slug: data.slug };
520
+ }
521
+ /**
522
+ * Render an article from unsaved editor data as the website would, with its type's "single" template, for the
523
+ * editor's preview. Drafts are shown as if published. Its files come from its saved folder (`location`), if it has one,
524
+ * and are shown from the editor's file URLs. Throws a 400 EditorError if it can't be rendered (e.g. a file isn't in
525
+ * the article's folder).
526
+ *
527
+ * @param embeds - renders embed blocks
528
+ */
529
+ async preview(data, location, embeds) {
530
+ if (!isSlug(data.type))
531
+ throw new EditorError(400, `Type "${data.type}" must be lowercase kebab-case`);
532
+ const baseUrl = bodyBaseUrl(location);
533
+ const config = await this.config();
534
+ const site = siteData(config, { [data.type]: defaultTypeConfig(data.type), ...config.types }, DEFAULT_SITE_URL);
535
+ const source = serializeArticle({ ...data, status: "published", title: data.title.trim() || "Untitled" }, editorHtmlToMarkdown(data.bodyHtml, baseUrl));
536
+ const name = `${data.type}/${data.slug || "new"}`;
537
+ const markdown = createMarkdown();
538
+ const metadata = await this.metadata();
539
+ try {
540
+ // Published, so always rendered
541
+ const article = (await loadArticle(source, data.type, {
542
+ site,
543
+ // An unsaved article has no folder, so any file it names isn't found
544
+ dir: location
545
+ ? this.dir(location.type, location.slug)
546
+ : join(this.articlesDir, data.type, ".unsaved"),
547
+ slug: data.slug,
548
+ url: baseUrl,
549
+ typeUrl: site.types[data.type].url,
550
+ source: name,
551
+ replaceEmbeds: async (md) => embeds.replaceBlocks(md, name),
552
+ setEmbedHeadings: (html, headings) => embeds.setHeadings(html, headings),
553
+ renderMarkdown: (md, base) => renderMarkdown(markdown, md, base),
554
+ metadata: {
555
+ ...metadata.context(data.type),
556
+ // The editor shows problems itself
557
+ warn: () => undefined,
558
+ },
559
+ }));
560
+ const templates = this.loadTemplates();
561
+ return await embeds.renderPage(templates.render(templates.resolve(data.type, "single"), {
562
+ ...articlePageData(site, article),
563
+ embeds: EMBED_PAGE_PARTS,
564
+ }), name);
565
+ }
566
+ catch (error) {
567
+ throw new EditorError(400, error.message);
568
+ }
569
+ }
570
+ /**
571
+ * Delete an article and all its files.
572
+ */
573
+ async remove(type, slug) {
574
+ await this.source(type, slug);
575
+ await rm(this.dir(type, slug), { recursive: true });
576
+ (await this.index()).delete(type, slug);
577
+ }
578
+ /**
579
+ * Save an uploaded file into an article's folder (replacing a file with the same name).
580
+ */
581
+ async upload(type, slug, fileName, contents) {
582
+ await this.source(type, slug);
583
+ const name = safeFileName(fileName);
584
+ await writeFile(join(this.dir(type, slug), name), contents);
585
+ return { name, url: filesUrl(type, slug) + name };
586
+ }
587
+ /**
588
+ * Remember an article's unsaved data for its preview page, under a new ID. Only the newest `MAX_PREVIEWS` are kept,
589
+ * in memory: they're gone when the editor stops. Returns the ID.
590
+ *
591
+ * @example
592
+ * const id = store.rememberPreview(data, { type: "news", slug: "hello" }); // the editor shows it at /preview/<id>/
593
+ */
594
+ rememberPreview(data, location) {
595
+ const id = randomUUID();
596
+ this.previews.set(id, { data, location });
597
+ for (const old of [...this.previews.keys()].slice(0, -MAX_PREVIEWS))
598
+ this.previews.delete(old);
599
+ return id;
600
+ }
601
+ /**
602
+ * Remember an embed block for its frame in the editor's body, under an ID made from it (so the same block keeps its
603
+ * frame's URL). Only the newest `MAX_EMBED_FRAMES` are kept.
604
+ *
605
+ * @example
606
+ * const id = store.rememberEmbedFrame({ key: "youtube", content: "https://youtu.be/aju_UB5VIf8", options: {} }); // shown at /embed-frame/<id>/
607
+ */
608
+ rememberEmbedFrame(frame) {
609
+ const id = createHash("sha256")
610
+ .update(`${frame.key}\0${JSON.stringify(frame.options)}\0${frame.content}`)
611
+ .digest("hex")
612
+ .slice(0, 32);
613
+ this.embedFrames.delete(id);
614
+ this.embedFrames.set(id, frame);
615
+ for (const old of [...this.embedFrames.keys()].slice(0, -MAX_EMBED_FRAMES))
616
+ this.embedFrames.delete(old);
617
+ return id;
618
+ }
619
+ /**
620
+ * A remembered embed block (see `rememberEmbedFrame`). Throws a 404 EditorError if there is none with that ID (e.g.
621
+ * after the editor restarted).
622
+ */
623
+ embedFrame(id) {
624
+ const frame = this.embedFrames.get(id);
625
+ if (!frame)
626
+ throw new EditorError(404, "Embed not found");
627
+ return frame;
628
+ }
629
+ /**
630
+ * Render a remembered preview as the website would (see `preview`), so changes to templates show when it reloads.
631
+ * Throws a 404 EditorError if there is no preview with that ID (e.g. after the editor restarted).
632
+ *
633
+ * @param embeds - renders embed blocks
634
+ */
635
+ async renderPreview(id, embeds) {
636
+ const preview = this.previews.get(id);
637
+ if (!preview)
638
+ throw new EditorError(404, "Preview not found");
639
+ return this.preview(preview.data, preview.location, embeds);
640
+ }
641
+ /**
642
+ * Read a file at its path on the website, for previews and the article body: one of the static files published at
643
+ * the website's root (the site's `static/`, then the theme's), e.g. `site.css`, or else a file in an article's
644
+ * folder, e.g. `news/welcome/photo.png`. Throws a 404 EditorError if there is no such file, or the path leaves the
645
+ * folder or names a hidden file.
646
+ *
647
+ * @example
648
+ * await store.staticFile("fonts/my-font.woff2");
649
+ * await store.staticFile("news/welcome/photo.png");
650
+ */
651
+ async staticFile(path) {
652
+ const parts = path.split("/");
653
+ if (parts.some((part) => part === "" || part.startsWith(".")))
654
+ throw new EditorError(404, "File not found");
655
+ for (const dir of this.staticDirs) {
656
+ try {
657
+ return await readFile(join(dir, ...parts));
658
+ }
659
+ catch {
660
+ // Not in this folder
661
+ }
662
+ }
663
+ const { articleUrl } = await this.articleUrls();
664
+ const file = (await this.index())
665
+ .files()
666
+ .find(({ type, slug, name }) => articleUrl(type, slug) + name === `/${path}`);
667
+ if (!file)
668
+ throw new EditorError(404, "File not found");
669
+ return this.file(file.type, file.slug, file.name);
670
+ }
671
+ /** The static folders (stylesheet, fonts) published at the website's root: the site's, then the theme's */
672
+ get staticDirs() {
673
+ return [join(this.siteDir, this.staticDir), join(this.themeDir, "static")];
674
+ }
675
+ /**
676
+ * Read a file from an article's folder. Throws a 404 EditorError if there is no such file.
677
+ */
678
+ async file(type, slug, name) {
679
+ // Only plain file names in the article's folder (no sub-folders, parent folders or hidden files)
680
+ if (name === "article.md" ||
681
+ name !== basename(name) ||
682
+ name.startsWith("."))
683
+ throw new EditorError(404, "File not found");
684
+ try {
685
+ return await readFile(join(this.dir(type, slug), name));
686
+ }
687
+ catch (error) {
688
+ if (error instanceof EditorError)
689
+ throw error;
690
+ throw new EditorError(404, "File not found");
691
+ }
692
+ }
693
+ }