@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,13 +0,0 @@
1
- <!doctype html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width, initial-scale=1" />
6
- <title>Article editor | edaha.md</title>
7
- <script type="module" crossorigin src="/_editor/assets/index-DtG7vi1d.js"></script>
8
- <link rel="stylesheet" crossorigin href="/_editor/assets/index-BbKEbPS8.css">
9
- </head>
10
- <body>
11
- <blog-editor></blog-editor>
12
- </body>
13
- </html>
@@ -1,62 +0,0 @@
1
- import { Hono } from "hono";
2
- /** The editor only listens on this computer's own address, so nothing else on the network can reach it */
3
- export declare const EDITOR_HOST = "127.0.0.1";
4
- /** The editor's default port */
5
- export declare const EDITOR_PORT = 5180;
6
- /** The URL path the editor page's own files (scripts, styles) are served under, apart from the site's static files */
7
- export declare const EDITOR_BASE = "/_editor/";
8
- /** The editor page's built files (`dist/client`, bundled by Vite). The path is the same from `dist/editor`. */
9
- export declare const CLIENT_DIR: string;
10
- /** Options for the article editor's server */
11
- export interface EditorServerOptions {
12
- /** The site folder (holds config.yml and articles/) */
13
- siteDir: string;
14
- /** The default theme folder that the site's templates and static files override. Default: THEME_DIR */
15
- themeDir?: string;
16
- /** The port to listen on. Default: EDITOR_PORT */
17
- port?: number;
18
- /** The editor page's built files. Default: CLIENT_DIR */
19
- clientDir?: string;
20
- /** Fetches extra data for embed previews (defaults to the global fetch) */
21
- fetch?: typeof fetch;
22
- }
23
- /** A running editor server */
24
- export interface EditorServer {
25
- /** The editor's address, e.g. "http://127.0.0.1:5180" */
26
- url: string;
27
- /** Stop the server */
28
- close: () => Promise<void>;
29
- }
30
- /**
31
- * The editor's address for a port.
32
- *
33
- * @example
34
- * editorUrl(5180); // "http://127.0.0.1:5180"
35
- */
36
- export declare const editorUrl: (port: number) => string;
37
- /**
38
- * The port an editor listens on: the given one, or EDITOR_PORT.
39
- *
40
- * @example
41
- * editorPort({ siteDir: "my-site" }); // 5180
42
- */
43
- export declare const editorPort: (options: EditorServerOptions) => number;
44
- /**
45
- * Create the article editor's web app: the editor page at `/`, its files under `EDITOR_BASE`, and the editor API,
46
- * previews and the site's static files (see createEditorApp) everywhere else.
47
- *
48
- * @example
49
- * const app = createEditorServer({ siteDir: "my-site" });
50
- * await app.request("/"); // the editor page
51
- */
52
- export declare const createEditorServer: (options: EditorServerOptions) => Hono;
53
- /**
54
- * Start the article editor on this computer only (`EDITOR_HOST`). Never deploy it: it reads and writes the site's
55
- * files.
56
- *
57
- * @example
58
- * const editor = await startEditor({ siteDir: "my-site" });
59
- * console.log(`Open ${editor.url}`);
60
- * await editor.close();
61
- */
62
- export declare const startEditor: (options: EditorServerOptions) => Promise<EditorServer>;
@@ -1,102 +0,0 @@
1
- import { readFile } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
- import { serve } from "@hono/node-server";
5
- import { Hono } from "hono";
6
- import mime from "mime-types";
7
- import { createEditorApp } from "../server/app/index.js";
8
- import { ArticleStore } from "../server/store/index.js";
9
- /** The editor only listens on this computer's own address, so nothing else on the network can reach it */
10
- export const EDITOR_HOST = "127.0.0.1";
11
- /** The editor's default port */
12
- export const EDITOR_PORT = 5180;
13
- /** The URL path the editor page's own files (scripts, styles) are served under, apart from the site's static files */
14
- export const EDITOR_BASE = "/_editor/";
15
- /** The editor page's built files (`dist/client`, bundled by Vite). The path is the same from `dist/editor`. */
16
- export const CLIENT_DIR = fileURLToPath(new URL("../client", import.meta.url));
17
- /**
18
- * The editor's address for a port.
19
- *
20
- * @example
21
- * editorUrl(5180); // "http://127.0.0.1:5180"
22
- */
23
- export const editorUrl = (port) => `http://${EDITOR_HOST}:${port}`;
24
- /**
25
- * The port an editor listens on: the given one, or EDITOR_PORT.
26
- *
27
- * @example
28
- * editorPort({ siteDir: "my-site" }); // 5180
29
- */
30
- export const editorPort = (options) => options.port ?? EDITOR_PORT;
31
- /**
32
- * Read one of the editor page's built files, or undefined if there is no such file or the path leaves the folder.
33
- */
34
- const clientFile = async (clientDir, path) => {
35
- const parts = path.split("/");
36
- if (parts.some((part) => part === "" || part.startsWith(".")))
37
- return undefined;
38
- try {
39
- return (await readFile(join(clientDir, ...parts)));
40
- }
41
- catch {
42
- return undefined;
43
- }
44
- };
45
- /**
46
- * Create the article editor's web app: the editor page at `/`, its files under `EDITOR_BASE`, and the editor API,
47
- * previews and the site's static files (see createEditorApp) everywhere else.
48
- *
49
- * @example
50
- * const app = createEditorServer({ siteDir: "my-site" });
51
- * await app.request("/"); // the editor page
52
- */
53
- export const createEditorServer = (options) => {
54
- const port = editorPort(options);
55
- const clientDir = options.clientDir ?? CLIENT_DIR;
56
- const store = new ArticleStore(options.siteDir, options.themeDir);
57
- const editorApp = createEditorApp(store, {
58
- allowedOrigins: [editorUrl(port)],
59
- fetch: options.fetch,
60
- });
61
- const app = new Hono();
62
- app.get("/", async (c) => {
63
- const html = await clientFile(clientDir, "index.html");
64
- if (!html)
65
- return c.text("The editor page is missing; build edaha.md with `pnpm build`", 500);
66
- return c.body(html, 200, {
67
- "Content-Type": "text/html; charset=utf-8",
68
- "Cache-Control": "no-store",
69
- });
70
- });
71
- app.get(`${EDITOR_BASE}*`, async (c) => {
72
- const path = decodeURIComponent(c.req.path.slice(EDITOR_BASE.length));
73
- const contents = await clientFile(clientDir, path);
74
- if (!contents)
75
- return c.json({ error: "File not found" }, 404);
76
- return c.body(contents, 200, {
77
- "Content-Type": mime.lookup(path) || "application/octet-stream",
78
- });
79
- });
80
- app.route("/", editorApp);
81
- return app;
82
- };
83
- /**
84
- * Start the article editor on this computer only (`EDITOR_HOST`). Never deploy it: it reads and writes the site's
85
- * files.
86
- *
87
- * @example
88
- * const editor = await startEditor({ siteDir: "my-site" });
89
- * console.log(`Open ${editor.url}`);
90
- * await editor.close();
91
- */
92
- export const startEditor = (options) => {
93
- const port = editorPort(options);
94
- const app = createEditorServer(options);
95
- return new Promise((resolve, reject) => {
96
- const server = serve({ fetch: app.fetch, hostname: EDITOR_HOST, port }, () => resolve({
97
- url: editorUrl(port),
98
- close: () => new Promise((done, fail) => server.close((error) => (error ? fail(error) : done()))),
99
- }));
100
- server.once("error", reject);
101
- });
102
- };
@@ -1,9 +0,0 @@
1
- import type { EmbedRenderer } from "../types/index.ts";
2
- /**
3
- * Embeds Bandcamp albums and tracks. Bandcamp URLs don't contain the album/track ID, so the page is fetched to find it.
4
- *
5
- * @example
6
- * await bandcamp.render(new URL("https://artist.bandcamp.com/album/name"), { fetch });
7
- */
8
- export declare const bandcamp: EmbedRenderer;
9
- export default bandcamp;
@@ -1,28 +0,0 @@
1
- /** Album or track pages, e.g. /album/<name> */
2
- const ITEM_PATH = /^\/(album|track)\/[^/]+/;
3
- /** The embedded player URL in a Bandcamp page's `og:video` meta tag, e.g. ".../EmbeddedPlayer/v=2/album=123/..." */
4
- const PLAYER_ITEM = /EmbeddedPlayer\/(?:v=\d+\/)?(album|track)=(\d+)/;
5
- /**
6
- * Embeds Bandcamp albums and tracks. Bandcamp URLs don't contain the album/track ID, so the page is fetched to find it.
7
- *
8
- * @example
9
- * await bandcamp.render(new URL("https://artist.bandcamp.com/album/name"), { fetch });
10
- */
11
- export const bandcamp = {
12
- name: "Bandcamp",
13
- match: (url) => url.hostname.endsWith(".bandcamp.com") && ITEM_PATH.test(url.pathname),
14
- render: async (url, { fetch }) => {
15
- const response = await fetch(url);
16
- if (!response.ok)
17
- throw new Error(`Fetching ${url} failed with ${response.status}`);
18
- const item = PLAYER_ITEM.exec(await response.text());
19
- if (!item)
20
- throw new Error(`No Bandcamp player found on ${url}`);
21
- const [, kind, id] = item;
22
- const size = kind === "album"
23
- ? 'width="350" height="470"'
24
- : 'width="350" height="442"';
25
- return `<iframe ${size} src="https://bandcamp.com/EmbeddedPlayer/${kind}=${id}/size=large/bgcol=ffffff/linkcol=0687f5/tracklist=false/transparent=true/" title="Bandcamp player" loading="lazy" seamless></iframe>`;
26
- },
27
- };
28
- export default bandcamp;
@@ -1,17 +0,0 @@
1
- import type { EmbedRenderer } from "../types/index.ts";
2
- /**
3
- * Get the video ID from any form of YouTube URL. Throws if there is none.
4
- *
5
- * @example
6
- * extractYouTubeId(new URL("https://youtu.be/aju_UB5VIf8")); // "aju_UB5VIf8"
7
- * extractYouTubeId(new URL("https://www.youtube.com/watch?v=aju_UB5VIf8")); // "aju_UB5VIf8"
8
- */
9
- export declare const extractYouTubeId: (url: URL) => string;
10
- /**
11
- * Embeds YouTube videos. Always uses youtube-nocookie.com, whatever form of YouTube URL is given.
12
- *
13
- * @example
14
- * await youtube.render(new URL("https://youtu.be/aju_UB5VIf8"), context); // '<iframe ... src="https://www.youtube-nocookie.com/embed/aju_UB5VIf8" ...>'
15
- */
16
- export declare const youtube: EmbedRenderer;
17
- export default youtube;
@@ -1,48 +0,0 @@
1
- import { escapeHtml } from "../../generator/format/index.js";
2
- const HOSTS = new Set([
3
- "youtu.be",
4
- "youtube.com",
5
- "www.youtube.com",
6
- "m.youtube.com",
7
- "youtube-nocookie.com",
8
- "www.youtube-nocookie.com",
9
- ]);
10
- /** YouTube video IDs are 11 URL-safe base64 characters */
11
- const VIDEO_ID = /^[A-Za-z0-9_-]{11}$/;
12
- /** Paths where the video ID follows the first segment, e.g. /embed/<id> */
13
- const ID_PATHS = new Set(["embed", "shorts", "live", "v"]);
14
- /**
15
- * Get the video ID from any form of YouTube URL. Throws if there is none.
16
- *
17
- * @example
18
- * extractYouTubeId(new URL("https://youtu.be/aju_UB5VIf8")); // "aju_UB5VIf8"
19
- * extractYouTubeId(new URL("https://www.youtube.com/watch?v=aju_UB5VIf8")); // "aju_UB5VIf8"
20
- */
21
- export const extractYouTubeId = (url) => {
22
- const [first = "", second = ""] = url.pathname.split("/").filter(Boolean);
23
- const id = url.hostname === "youtu.be"
24
- ? first
25
- : first === "watch"
26
- ? (url.searchParams.get("v") ?? "")
27
- : ID_PATHS.has(first)
28
- ? second
29
- : "";
30
- if (!VIDEO_ID.test(id))
31
- throw new Error(`No YouTube video ID in ${url}`);
32
- return id;
33
- };
34
- /**
35
- * Embeds YouTube videos. Always uses youtube-nocookie.com, whatever form of YouTube URL is given.
36
- *
37
- * @example
38
- * await youtube.render(new URL("https://youtu.be/aju_UB5VIf8"), context); // '<iframe ... src="https://www.youtube-nocookie.com/embed/aju_UB5VIf8" ...>'
39
- */
40
- export const youtube = {
41
- name: "YouTube",
42
- match: (url) => HOSTS.has(url.hostname),
43
- render: async (url) => {
44
- const src = `https://www.youtube-nocookie.com/embed/${extractYouTubeId(url)}`;
45
- return `<iframe width="560" height="315" src="${escapeHtml(src)}" title="YouTube video player" loading="lazy" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>`;
46
- },
47
- };
48
- export default youtube;
@@ -1,39 +0,0 @@
1
- import { Hono } from "hono";
2
- import { type ArticleStore } from "../store/index.ts";
3
- /** Options for the editor API */
4
- export interface EditorAppOptions {
5
- /** Origins allowed to change articles, e.g. "http://127.0.0.1:5180" */
6
- allowedOrigins: readonly string[];
7
- /** Fetches extra data for embed previews (defaults to the global fetch) */
8
- fetch?: typeof fetch | undefined;
9
- }
10
- /**
11
- * The Content Security Policy of preview pages and their files: like the website's news pages (its own files, YouTube
12
- * and Bandcamp embeds), but with no scripts, requests or forms at all. Previews are served from the editor's own
13
- * address, so this is what stops anything in an article from using the editor's API.
14
- */
15
- export declare const PREVIEW_CSP = "default-src 'self'; script-src 'none'; frame-src https://www.youtube-nocookie.com https://bandcamp.com; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'";
16
- /**
17
- * Create the article editor's local API. Requests that change files must come from the editor's own page (checked
18
- * with the Origin header), so other websites open in the same browser can't write articles.
19
- *
20
- * Routes:
21
- * - `GET /api/articles`: list articles
22
- * - `GET /api/types`: the article types from config.yml, with their labels
23
- * - `GET /api/templates/:type`: the template names an article of a type can use
24
- * - `POST /api/articles`: create an article
25
- * - `GET|PUT|DELETE /api/articles/:type/:slug`: load, save (and move) or delete an article
26
- * - `POST /api/articles/:type/:slug/files`: upload a file (multipart field "file")
27
- * - `GET /files/:type/:slug/:name`: an article's file, for previews in the editor
28
- * - `GET /api/embed?url=...`: render an embed URL as the website would, for previews in the editor
29
- * - `POST /api/convert/markdown` and `POST /api/convert/html`: convert an article body between editor HTML and Markdown
30
- * (`{ html | markdown, location? }`, where `location` is the saved article's, which relative URLs are relative to)
31
- * - `POST /api/preview`: remember unsaved article data (`{ data, location? }`) for a preview page, and give its URL
32
- * (`{ url }`); answers 400 if it can't be rendered
33
- * - `GET /preview/:id/`: render a remembered preview with its type's "single" template, and `GET /<path>`: one of the
34
- * blog's static files (e.g. `/site.css`), both with a Content Security Policy that forbids scripts (`PREVIEW_CSP`)
35
- *
36
- * @example
37
- * const app = createEditorApp(new ArticleStore("packages/blog"), { allowedOrigins: ["http://127.0.0.1:5180"] });
38
- */
39
- export declare const createEditorApp: (store: ArticleStore, { allowedOrigins, fetch: fetchFn, }: EditorAppOptions) => Hono;
@@ -1,138 +0,0 @@
1
- import { Hono } from "hono";
2
- import mime from "mime-types";
3
- import { EmbedResolver } from "../../embeds/index.js";
4
- import { editorHtmlToMarkdown, markdownToEditorHtml, } from "../convert/index.js";
5
- import { bodyBaseUrl, EditorError } from "../store/index.js";
6
- /**
7
- * The Content Security Policy of preview pages and their files: like the website's news pages (its own files, YouTube
8
- * and Bandcamp embeds), but with no scripts, requests or forms at all. Previews are served from the editor's own
9
- * address, so this is what stops anything in an article from using the editor's API.
10
- */
11
- export const PREVIEW_CSP = "default-src 'self'; script-src 'none'; frame-src https://www.youtube-nocookie.com https://bandcamp.com; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'";
12
- /**
13
- * Create the article editor's local API. Requests that change files must come from the editor's own page (checked
14
- * with the Origin header), so other websites open in the same browser can't write articles.
15
- *
16
- * Routes:
17
- * - `GET /api/articles`: list articles
18
- * - `GET /api/types`: the article types from config.yml, with their labels
19
- * - `GET /api/templates/:type`: the template names an article of a type can use
20
- * - `POST /api/articles`: create an article
21
- * - `GET|PUT|DELETE /api/articles/:type/:slug`: load, save (and move) or delete an article
22
- * - `POST /api/articles/:type/:slug/files`: upload a file (multipart field "file")
23
- * - `GET /files/:type/:slug/:name`: an article's file, for previews in the editor
24
- * - `GET /api/embed?url=...`: render an embed URL as the website would, for previews in the editor
25
- * - `POST /api/convert/markdown` and `POST /api/convert/html`: convert an article body between editor HTML and Markdown
26
- * (`{ html | markdown, location? }`, where `location` is the saved article's, which relative URLs are relative to)
27
- * - `POST /api/preview`: remember unsaved article data (`{ data, location? }`) for a preview page, and give its URL
28
- * (`{ url }`); answers 400 if it can't be rendered
29
- * - `GET /preview/:id/`: render a remembered preview with its type's "single" template, and `GET /<path>`: one of the
30
- * blog's static files (e.g. `/site.css`), both with a Content Security Policy that forbids scripts (`PREVIEW_CSP`)
31
- *
32
- * @example
33
- * const app = createEditorApp(new ArticleStore("packages/blog"), { allowedOrigins: ["http://127.0.0.1:5180"] });
34
- */
35
- export const createEditorApp = (store, { allowedOrigins, fetch: fetchFn = (...args) => fetch(...args), }) => {
36
- const app = new Hono();
37
- app.use(async (c, next) => {
38
- if (c.req.method !== "GET" && c.req.method !== "HEAD") {
39
- const origin = c.req.header("origin");
40
- if (!origin || !allowedOrigins.includes(origin))
41
- return c.json({ error: "Forbidden" }, 403);
42
- }
43
- await next();
44
- });
45
- app.onError((error, c) => error instanceof EditorError
46
- ? c.json({ error: error.message }, error.status)
47
- : c.json({ error: error.message }, 500));
48
- app.get("/api/articles", async (c) => c.json(await store.list()));
49
- app.get("/api/types", async (c) => c.json(await store.types()));
50
- app.get("/api/templates/:type", (c) => c.json(store.templates(c.req.param("type"))));
51
- app.get("/api/embed", async (c) => {
52
- const url = c.req.query("url") ?? "";
53
- const warnings = [];
54
- // A new resolver each time, so a fixed URL or a network failure isn't remembered
55
- const embeds = new EmbedResolver({
56
- fetch: fetchFn,
57
- logger: { warn: (message) => warnings.push(message) },
58
- });
59
- return c.json({
60
- html: await embeds.render(url, "Preview"),
61
- warnings,
62
- });
63
- });
64
- app.post("/api/convert/markdown", async (c) => {
65
- const { html, location } = await c.req.json();
66
- return c.json({
67
- markdown: editorHtmlToMarkdown(html, bodyBaseUrl(location)),
68
- });
69
- });
70
- app.post("/api/convert/html", async (c) => {
71
- const { markdown, location } = await c.req.json();
72
- return c.json({
73
- html: markdownToEditorHtml(markdown, bodyBaseUrl(location)),
74
- });
75
- });
76
- app.post("/api/preview", async (c) => {
77
- const { data, location } = await c.req.json();
78
- // A new resolver each time, so a fixed URL or a network failure isn't remembered
79
- const embeds = new EmbedResolver({
80
- fetch: fetchFn,
81
- logger: { warn: () => undefined },
82
- });
83
- // Rendered now to report problems (e.g. a missing file), then again each time the page is shown
84
- await store.preview(data, location, embeds);
85
- return c.json({
86
- url: `/preview/${store.rememberPreview(data, location)}/`,
87
- });
88
- });
89
- app.post("/api/articles", async (c) => {
90
- const data = await c.req.json();
91
- return c.json(await store.save(data), 201);
92
- });
93
- app.get("/api/articles/:type/:slug", async (c) => c.json(await store.read(c.req.param("type"), c.req.param("slug"))));
94
- app.put("/api/articles/:type/:slug", async (c) => {
95
- const data = await c.req.json();
96
- return c.json(await store.save(data, {
97
- type: c.req.param("type"),
98
- slug: c.req.param("slug"),
99
- }));
100
- });
101
- app.delete("/api/articles/:type/:slug", async (c) => {
102
- await store.remove(c.req.param("type"), c.req.param("slug"));
103
- return c.body(null, 204);
104
- });
105
- app.post("/api/articles/:type/:slug/files", async (c) => {
106
- const body = await c.req.parseBody();
107
- const file = body.file;
108
- if (!(file instanceof File))
109
- throw new EditorError(400, 'Expected a file in the "file" field');
110
- return c.json(await store.upload(c.req.param("type"), c.req.param("slug"), file.name, new Uint8Array(await file.arrayBuffer())), 201);
111
- });
112
- app.get("/files/:type/:slug/:name", async (c) => {
113
- const name = c.req.param("name");
114
- const contents = await store.file(c.req.param("type"), c.req.param("slug"), name);
115
- return c.body(contents, 200, {
116
- "Content-Type": mime.lookup(name) || "application/octet-stream",
117
- "Cache-Control": "no-store",
118
- });
119
- });
120
- // A remembered preview, rendered now, so template changes show when it reloads
121
- app.get("/preview/:id/", async (c) => {
122
- const html = await store.renderPreview(c.req.param("id"), new EmbedResolver({ fetch: fetchFn, logger: { warn: () => undefined } }));
123
- return c.html(html, 200, {
124
- "Cache-Control": "no-store",
125
- "Content-Security-Policy": PREVIEW_CSP,
126
- });
127
- });
128
- // The blog's static files (stylesheet, fonts), at the root as preview pages link them
129
- app.get("/*", async (c) => {
130
- const path = decodeURIComponent(c.req.path.slice(1));
131
- return c.body((await store.staticFile(path)), 200, {
132
- "Content-Type": mime.lookup(path) || "application/octet-stream",
133
- "Cache-Control": "no-store",
134
- "Content-Security-Policy": PREVIEW_CSP,
135
- });
136
- });
137
- return app;
138
- };
@@ -1,25 +0,0 @@
1
- /**
2
- * The URL the editor loads an article's files from, e.g. "/files/article/hello/".
3
- *
4
- * @example
5
- * filesUrl("article", "hello"); // "/files/article/hello/"
6
- */
7
- export declare const filesUrl: (type: string, slug: string) => string;
8
- /**
9
- * Convert article markdown to HTML for the editor: `<!-- readmore -->` becomes `<hr class="readmore">`,
10
- * embed blocks become `<div class="embed">URL</div>`, and relative URLs point at the editor's file URL.
11
- *
12
- * @example
13
- * markdownToEditorHtml("Intro <!-- readmore -->Rest", "/files/article/hello/");
14
- * // '<p>Intro</p>\n<hr class="readmore">\n<p>Rest</p>\n'
15
- */
16
- export declare const markdownToEditorHtml: (source: string, baseUrl: string) => string;
17
- /**
18
- * Convert editor HTML back to article markdown, turning the readmore and embed blocks back into their shortcodes and
19
- * the editor's file URLs back into relative URLs.
20
- *
21
- * @example
22
- * editorHtmlToMarkdown('<p>Hi</p><hr class="readmore"><p><img src="/files/article/a/b.png"></p>', "/files/article/a/");
23
- * // "Hi\n\n<!-- readmore -->\n\n![](b.png)"
24
- */
25
- export declare const editorHtmlToMarkdown: (html: string, baseUrl: string) => string;
@@ -1,125 +0,0 @@
1
- import TurndownService from "turndown";
2
- import { EMBED_BLOCK } from "../../embeds/index.js";
3
- import { READMORE } from "../../generator/article/index.js";
4
- import { escapeHtml } from "../../generator/format/index.js";
5
- import { createMarkdown, renderMarkdown, } from "../../generator/markdown/index.js";
6
- // Without typographer, so text converts back to the same markdown
7
- const markdown = createMarkdown({ typographer: false });
8
- /**
9
- * The URL the editor loads an article's files from, e.g. "/files/article/hello/".
10
- *
11
- * @example
12
- * filesUrl("article", "hello"); // "/files/article/hello/"
13
- */
14
- export const filesUrl = (type, slug) => `/files/${type}/${slug}/`;
15
- /**
16
- * Convert article markdown to HTML for the editor: `<!-- readmore -->` becomes `<hr class="readmore">`,
17
- * embed blocks become `<div class="embed">URL</div>`, and relative URLs point at the editor's file URL.
18
- *
19
- * @example
20
- * markdownToEditorHtml("Intro <!-- readmore -->Rest", "/files/article/hello/");
21
- * // '<p>Intro</p>\n<hr class="readmore">\n<p>Rest</p>\n'
22
- */
23
- export const markdownToEditorHtml = (source, baseUrl) => renderMarkdown(markdown, source
24
- .replace(READMORE, '\n\n<hr class="readmore">\n\n')
25
- .replace(EMBED_BLOCK, (_, url) => `\n\n<div class="embed">${escapeHtml(url.trim())}</div>\n\n`), baseUrl);
26
- /** HTML to markdown converter with rules for the readmore and embed blocks */
27
- const createTurndown = () => {
28
- const turndown = new TurndownService({
29
- headingStyle: "atx",
30
- codeBlockStyle: "fenced",
31
- bulletListMarker: "-",
32
- emDelimiter: "*",
33
- hr: "---",
34
- });
35
- turndown.addRule("readmore", {
36
- filter: (node) => node.nodeName === "HR" &&
37
- node.classList.contains("readmore"),
38
- replacement: () => "\n\n<!-- readmore -->\n\n",
39
- });
40
- turndown.addRule("embed", {
41
- filter: (node) => node.nodeName === "DIV" &&
42
- node.classList.contains("embed"),
43
- replacement: (_, node) => `\n\n<!-- embed -->${String(node.textContent).trim()}<!-- /embed -->\n\n`,
44
- });
45
- // Small and big text, and collapsible details blocks, stay HTML. A details block's summary stays HTML (Markdown
46
- // isn't read inside an HTML line) and its content becomes Markdown, between blank lines so it is read as Markdown.
47
- turndown.addRule("smallBig", {
48
- // `big` isn't in the DOM types' list of tag names, as HTML no longer recommends it
49
- filter: (node) => node.nodeName === "SMALL" || node.nodeName === "BIG",
50
- replacement: (content, node) => {
51
- const tag = node.nodeName.toLowerCase();
52
- return `<${tag}>${content}</${tag}>`;
53
- },
54
- });
55
- turndown.addRule("summary", { filter: "summary", replacement: () => "" });
56
- turndown.addRule("details", {
57
- filter: "details",
58
- replacement: (content, node) => {
59
- const summary = Array.from(node.childNodes).find((child) => child.nodeName === "SUMMARY");
60
- return `\n\n<details>\n<summary>${summary?.innerHTML.trim() ?? ""}</summary>\n\n${content.trim()}\n\n</details>\n\n`;
61
- },
62
- });
63
- // List items with a single space after the marker ("- item", "1. item")
64
- turndown.addRule("listItem", {
65
- filter: "li",
66
- replacement: (content, node) => {
67
- const parent = node.parentNode;
68
- const index = Array.prototype.indexOf.call(parent.children, node);
69
- const start = Number(parent.getAttribute("start") ?? 1);
70
- const prefix = parent.nodeName === "OL" ? `${start + index}. ` : "- ";
71
- const text = content
72
- .replace(/^\n+/, "")
73
- .replace(/\n+$/, "")
74
- // Indent continuation lines under the marker, leaving blank lines empty
75
- .replace(/\n(?!\n)/g, `\n${" ".repeat(prefix.length)}`);
76
- return `${prefix}${text}${node.nextSibling ? "\n" : ""}`;
77
- },
78
- });
79
- // Tables as GFM tables: the first row is the header row. Cells are kept to one line.
80
- turndown.addRule("tableCell", {
81
- filter: ["th", "td"],
82
- replacement: (content) => `| ${content
83
- .trim()
84
- .replace(/\s*\n+\s*/g, " ")
85
- .replace(/\|/g, "\\|")} `,
86
- });
87
- turndown.addRule("tableRow", {
88
- filter: "tr",
89
- replacement: (content, node) => {
90
- const row = `${content}|\n`;
91
- const table = node.closest("table");
92
- if (table.rows[0] !== node)
93
- return row;
94
- const separator = Array.from(node.cells, () => "| --- ").join("");
95
- return `${row}${separator}|\n`;
96
- },
97
- });
98
- turndown.addRule("tableSection", {
99
- filter: ["thead", "tbody", "tfoot"],
100
- replacement: (content) => content,
101
- });
102
- turndown.addRule("table", {
103
- filter: "table",
104
- replacement: (content) => `\n\n${content.trim()}\n\n`,
105
- });
106
- // Column widths from the editor aren't kept
107
- turndown.remove("colgroup");
108
- return turndown;
109
- };
110
- const turndown = createTurndown();
111
- /**
112
- * Convert editor HTML back to article markdown, turning the readmore and embed blocks back into their shortcodes and
113
- * the editor's file URLs back into relative URLs.
114
- *
115
- * @example
116
- * editorHtmlToMarkdown('<p>Hi</p><hr class="readmore"><p><img src="/files/article/a/b.png"></p>', "/files/article/a/");
117
- * // "Hi\n\n<!-- readmore -->\n\n![](b.png)"
118
- */
119
- export const editorHtmlToMarkdown = (html, baseUrl) => turndown
120
- .turndown(html)
121
- .replaceAll(`](${baseUrl}`, "](")
122
- // Turndown escapes "1." at the start of a line, which is only needed outside headings
123
- .replace(/^(#+ \d+)\\\./gm, "$1.")
124
- .replace(/\n{3,}/g, "\n\n")
125
- .trim();