@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.
- package/LICENSE +201 -0
- package/README.md +13 -2
- package/dist/client/assets/index-BwcJ6yrI.js +1578 -0
- package/dist/client/assets/index-D2Y17Fm-.css +1 -0
- package/dist/client/index.html +21 -0
- package/dist/editor/index.d.ts +69 -0
- package/dist/editor/index.js +125 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +3 -0
- package/dist/server/app/index.d.ts +98 -0
- package/dist/server/app/index.js +390 -0
- package/dist/server/articleIndex/index.d.ts +126 -0
- package/dist/server/articleIndex/index.js +352 -0
- package/dist/server/convert/index.d.ts +38 -0
- package/dist/server/convert/index.js +180 -0
- package/dist/server/files/index.d.ts +66 -0
- package/dist/server/files/index.js +256 -0
- package/dist/server/store/index.d.ts +287 -0
- package/dist/server/store/index.js +693 -0
- package/dist/server/types/index.d.ts +251 -0
- package/dist/server/types/index.js +15 -0
- package/package.json +59 -3
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import mime from "mime-types";
|
|
3
|
+
import { EMBED_PAGE_PARTS, EMBED_SOURCE_KINDS, EmbedResolver, embedText, } from "@lvl99dotcom/edaha.md/embeds";
|
|
4
|
+
import { withPlugins } from "@lvl99dotcom/edaha.md/generator/build";
|
|
5
|
+
import { editorHtmlToMarkdown, markdownToEditorHtml, } from "../convert/index.js";
|
|
6
|
+
import { bodyBaseUrl, EditorError, } from "../store/index.js";
|
|
7
|
+
/** Read search parameters as text or numbers, undefined when empty or not a number */
|
|
8
|
+
const paramReader = (params) => ({
|
|
9
|
+
text: (name) => params.get(name) || undefined,
|
|
10
|
+
number: (name) => {
|
|
11
|
+
const value = Number(params.get(name) || NaN);
|
|
12
|
+
return Number.isFinite(value) ? value : undefined;
|
|
13
|
+
},
|
|
14
|
+
});
|
|
15
|
+
/** The kinds of files a file query can filter by */
|
|
16
|
+
const FILE_KINDS = [
|
|
17
|
+
"image",
|
|
18
|
+
"document",
|
|
19
|
+
"archive",
|
|
20
|
+
"video",
|
|
21
|
+
"audio",
|
|
22
|
+
"other",
|
|
23
|
+
];
|
|
24
|
+
/** The ways a file query can sort */
|
|
25
|
+
const FILE_SORTS = ["name", "kind", "size", "location"];
|
|
26
|
+
/**
|
|
27
|
+
* Read a file query from a URL's search parameters, e.g. "?search=photo&kind=image&sort=size&order=desc&page=2".
|
|
28
|
+
* Unknown kinds, sorts and orders, and pages that aren't numbers, are left out.
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* fileQuery(new URLSearchParams("kind=image&page=2")); // { kind: "image", page: 2 }
|
|
32
|
+
*/
|
|
33
|
+
export const fileQuery = (params) => {
|
|
34
|
+
const { text, number } = paramReader(params);
|
|
35
|
+
const kind = text("kind");
|
|
36
|
+
const sort = text("sort");
|
|
37
|
+
const order = text("order");
|
|
38
|
+
return Object.fromEntries(Object.entries({
|
|
39
|
+
search: text("search"),
|
|
40
|
+
kind: kind && FILE_KINDS.includes(kind) ? kind : undefined,
|
|
41
|
+
type: text("type"),
|
|
42
|
+
sort: sort && FILE_SORTS.includes(sort) ? sort : undefined,
|
|
43
|
+
order: order === "asc" || order === "desc" ? order : undefined,
|
|
44
|
+
page: number("page"),
|
|
45
|
+
perPage: number("perPage"),
|
|
46
|
+
}).filter(([, value]) => value !== undefined));
|
|
47
|
+
};
|
|
48
|
+
/** The ways an article query can sort */
|
|
49
|
+
const SORTS = [
|
|
50
|
+
"title",
|
|
51
|
+
"type",
|
|
52
|
+
"status",
|
|
53
|
+
"date",
|
|
54
|
+
"updated",
|
|
55
|
+
];
|
|
56
|
+
/** The statuses an article query can filter by */
|
|
57
|
+
const STATUSES = ["published", "draft", "unlisted"];
|
|
58
|
+
/**
|
|
59
|
+
* Read an article query from a URL's search parameters, e.g. "?search=hello&type=news&sort=title&order=desc&page=2".
|
|
60
|
+
* Unknown statuses, sorts and orders, and pages that aren't numbers, are left out.
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* articleQuery(new URLSearchParams("search=hello&page=2")); // { search: "hello", page: 2 }
|
|
64
|
+
*/
|
|
65
|
+
export const articleQuery = (params) => {
|
|
66
|
+
const { text, number } = paramReader(params);
|
|
67
|
+
const status = text("status");
|
|
68
|
+
const problems = text("problems");
|
|
69
|
+
const sort = text("sort");
|
|
70
|
+
const order = text("order");
|
|
71
|
+
return Object.fromEntries(Object.entries({
|
|
72
|
+
search: text("search"),
|
|
73
|
+
type: text("type"),
|
|
74
|
+
author: text("author"),
|
|
75
|
+
tag: text("tag"),
|
|
76
|
+
status: status && STATUSES.includes(status) ? status : undefined,
|
|
77
|
+
problems: problems === "errors" || problems === "warnings" || problems === "any"
|
|
78
|
+
? problems
|
|
79
|
+
: undefined,
|
|
80
|
+
sort: SORTS.includes(sort)
|
|
81
|
+
? sort
|
|
82
|
+
: undefined,
|
|
83
|
+
order: order === "asc" || order === "desc" ? order : undefined,
|
|
84
|
+
page: number("page"),
|
|
85
|
+
perPage: number("perPage"),
|
|
86
|
+
}).filter(([, value]) => value !== undefined));
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* The origin preview pages and embed frames are shown from, for an editor at an address: `localhost` instead of
|
|
90
|
+
* `127.0.0.1`, which is the same server but another origin and site.
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* previewOriginOf("http://127.0.0.1:5180"); // "http://localhost:5180"
|
|
94
|
+
*/
|
|
95
|
+
export const previewOriginOf = (editorOrigin) => {
|
|
96
|
+
const url = new URL(editorOrigin);
|
|
97
|
+
url.hostname = "localhost";
|
|
98
|
+
return url.origin;
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* An embed block sent to the API: its key, content and options (none when they aren't a map).
|
|
102
|
+
*
|
|
103
|
+
* @example
|
|
104
|
+
* await embedRequest(request); // { key: "bandcamp", content: "https://...", options: { layout: "large" } }
|
|
105
|
+
*/
|
|
106
|
+
const embedRequest = async (request) => {
|
|
107
|
+
const { key, content, options } = (await request.json());
|
|
108
|
+
return {
|
|
109
|
+
key: String(key ?? ""),
|
|
110
|
+
content: String(content ?? ""),
|
|
111
|
+
options: options && typeof options === "object" && !Array.isArray(options)
|
|
112
|
+
? options
|
|
113
|
+
: {},
|
|
114
|
+
};
|
|
115
|
+
};
|
|
116
|
+
/** A logger that leaves out warnings, for renders whose problems the editor shows itself (or doesn't need) */
|
|
117
|
+
const QUIET = { warn: () => undefined };
|
|
118
|
+
/** The kinds of embed sources, by the Content Security Policy directive that allows them */
|
|
119
|
+
const SOURCE_DIRECTIVES = {
|
|
120
|
+
frame: "frame-src",
|
|
121
|
+
script: "script-src 'self' 'unsafe-inline'",
|
|
122
|
+
style: "style-src 'self' 'unsafe-inline'",
|
|
123
|
+
font: "font-src 'self' data:",
|
|
124
|
+
// 'self' is replaced with the page's own address (see previewCsp)
|
|
125
|
+
connect: "connect-src",
|
|
126
|
+
};
|
|
127
|
+
/**
|
|
128
|
+
* The Content Security Policy of preview pages, embed frames and the files they load. They are shown from an origin
|
|
129
|
+
* of their own (`previewOrigin`), which the editor's API doesn't answer and whose changes it refuses, and are
|
|
130
|
+
* sandboxed (`sandbox`, keeping their own origin, so embedded players such as Bandcamp's keep theirs) so they can't
|
|
131
|
+
* send forms or navigate the editor page. Inside, they may run their own scripts and styles, and load from their own
|
|
132
|
+
* address and the web addresses the embed plugins list in `sources`. Only the editor's pages may show them in frames.
|
|
133
|
+
*
|
|
134
|
+
* @param self - the address they are served from, e.g. "http://localhost:5180"
|
|
135
|
+
* @param ancestors - the editor's own addresses, which may show them in frames
|
|
136
|
+
* @example
|
|
137
|
+
* previewCsp([youtube], "http://localhost:5180", ["http://127.0.0.1:5180"]); // "sandbox allow-scripts allow-same-origin ...; default-src http://localhost:5180; ...; frame-src https://www.youtube-nocookie.com; ..."
|
|
138
|
+
*/
|
|
139
|
+
export const previewCsp = (plugins, self, ancestors = []) => {
|
|
140
|
+
const directives = EMBED_SOURCE_KINDS.map((kind) => {
|
|
141
|
+
const origins = [
|
|
142
|
+
...new Set(plugins.flatMap((plugin) => plugin.sources?.[kind] ?? [])),
|
|
143
|
+
];
|
|
144
|
+
const directive = SOURCE_DIRECTIVES[kind].replace("'self'", self);
|
|
145
|
+
// Frames and requests are only allowed to the listed addresses
|
|
146
|
+
return `${directive} ${origins.join(" ") || (directive.includes(" ") ? "" : "'none'")}`.trimEnd();
|
|
147
|
+
});
|
|
148
|
+
return [
|
|
149
|
+
"sandbox allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox",
|
|
150
|
+
`default-src ${self}`,
|
|
151
|
+
...directives,
|
|
152
|
+
`img-src ${self} data: https:`,
|
|
153
|
+
`media-src ${self} https:`,
|
|
154
|
+
"object-src 'none'",
|
|
155
|
+
"base-uri 'none'",
|
|
156
|
+
"form-action 'none'",
|
|
157
|
+
`frame-ancestors ${["'self'", ...ancestors].join(" ")}`,
|
|
158
|
+
].join("; ");
|
|
159
|
+
};
|
|
160
|
+
/**
|
|
161
|
+
* Sends an embed frame's height to the editor page (which sizes the frame to fit), whenever it changes. Messages
|
|
162
|
+
* carry `{ edahaEmbedHeight }`.
|
|
163
|
+
*/
|
|
164
|
+
const FRAME_HEIGHT_SCRIPT = `<script>
|
|
165
|
+
const report = () => parent.postMessage({ edahaEmbedHeight: document.documentElement.scrollHeight }, "*");
|
|
166
|
+
new ResizeObserver(report).observe(document.documentElement);
|
|
167
|
+
addEventListener("load", report);
|
|
168
|
+
</script>`;
|
|
169
|
+
/**
|
|
170
|
+
* The page shown in an embed block's frame in the editor's body: the embed rendered for the editor, with the HTML it
|
|
171
|
+
* needs once, in the editor's light or dark theme.
|
|
172
|
+
*
|
|
173
|
+
* @example
|
|
174
|
+
* embedFramePage('<div class="embed">...</div>', { head: "", foot: "" }, "dark");
|
|
175
|
+
*/
|
|
176
|
+
export const embedFramePage = (html, parts, theme) => `<!doctype html>
|
|
177
|
+
<html lang="en"${theme ? ` data-theme="${theme}" style="color-scheme: ${theme}"` : ""}>
|
|
178
|
+
<head>
|
|
179
|
+
<meta charset="utf-8">
|
|
180
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
181
|
+
<base target="_blank">
|
|
182
|
+
<style>
|
|
183
|
+
html { color-scheme: light dark; }
|
|
184
|
+
body { margin: 0; font-family: system-ui, sans-serif; }
|
|
185
|
+
iframe, img, svg, video { max-width: 100%; }
|
|
186
|
+
.embed-text { white-space: pre-wrap; }
|
|
187
|
+
</style>
|
|
188
|
+
${parts.head}
|
|
189
|
+
</head>
|
|
190
|
+
<body>
|
|
191
|
+
${html}
|
|
192
|
+
${parts.foot}
|
|
193
|
+
${FRAME_HEIGHT_SCRIPT}
|
|
194
|
+
</body>
|
|
195
|
+
</html>
|
|
196
|
+
`;
|
|
197
|
+
/**
|
|
198
|
+
* Create the article editor's local API. Requests that change files must come from the editor's own page (checked
|
|
199
|
+
* with the Origin header), so other websites open in the same browser can't write articles.
|
|
200
|
+
*
|
|
201
|
+
* Routes:
|
|
202
|
+
* - `GET /api/articles`: list articles
|
|
203
|
+
* - `GET /api/types`: the article types from the config file, with their labels
|
|
204
|
+
* - `GET /api/templates/:type`: the template names an article of a type can use
|
|
205
|
+
* - `POST /api/articles`: create an article
|
|
206
|
+
* - `GET|PUT|DELETE /api/articles/:type/:slug`: load, save (and move) or delete an article
|
|
207
|
+
* - `POST /api/articles/:type/:slug/files`: upload a file (multipart field "file")
|
|
208
|
+
* - `GET /files/:type/:slug/:name`: an article's file, for previews in the editor
|
|
209
|
+
* - `GET /api/embeds`: the embed plugins (`EmbedInfo`), for the editor's embed dialog
|
|
210
|
+
* - `POST /api/embed-validations`: check an embed block's content (`{ key, content }`) with its plugin's `validate`,
|
|
211
|
+
* giving why it isn't valid (`EmbedValidation`)
|
|
212
|
+
* - `POST /api/embed-frames`: remember an embed block (`{ key, content }`) for its frame in the editor's body, and give
|
|
213
|
+
* the frame's URL, and why its content isn't valid (then it has no frame) or can't be shown (`EmbedFrame`); `GET /embed-frame/:id/?theme=light|dark` is the frame's page
|
|
214
|
+
* - `POST /api/convert/markdown` and `POST /api/convert/html`: convert an article body between editor HTML and Markdown
|
|
215
|
+
* (`{ html | markdown, location? }`, where `location` is the saved article's, which relative URLs are relative to)
|
|
216
|
+
* - `POST /api/preview`: remember unsaved article data (`{ data, location? }`) for a preview page, and give its URL
|
|
217
|
+
* (`{ url }`); answers 400 if it can't be rendered
|
|
218
|
+
* - `GET /preview/:id/`: render a remembered preview with its type's "single" template, and `GET /<path>`: one of the
|
|
219
|
+
* site's static files (e.g. `/site.css`) or an article's file at its path on the website (e.g.
|
|
220
|
+
* `/news/welcome/photo.png`), all sandboxed by their Content Security Policy (`previewCsp`)
|
|
221
|
+
*
|
|
222
|
+
* Embeds are rendered with the config file's `plugins`, then the given `plugins`.
|
|
223
|
+
*
|
|
224
|
+
* @example
|
|
225
|
+
* const app = createEditorApp(new ArticleStore(await loadSiteConfig({ siteDir: "my-site" })), { allowedOrigins: ["http://127.0.0.1:5180"] });
|
|
226
|
+
*/
|
|
227
|
+
export const createEditorApp = (store, { allowedOrigins, fetch: fetchFn = (...args) => fetch(...args), plugins: givenPlugins = [], previewOrigin, }) => {
|
|
228
|
+
const app = new Hono();
|
|
229
|
+
/** The embed plugins: the config file's, then the given ones */
|
|
230
|
+
const plugins = async () => withPlugins(await store.plugins(), givenPlugins);
|
|
231
|
+
/**
|
|
232
|
+
* A new embed resolver, each time, so a fixed embed, a network failure or a changed plugin isn't remembered
|
|
233
|
+
*/
|
|
234
|
+
const embedResolver = async (logger) => new EmbedResolver({ fetch: fetchFn, logger, plugins: await plugins() });
|
|
235
|
+
/** The Content Security Policy of preview pages and embed frames, allowing the plugins' sources */
|
|
236
|
+
const csp = async (url) => previewCsp(await plugins(), new URL(url).origin, allowedOrigins);
|
|
237
|
+
app.use(async (c, next) => {
|
|
238
|
+
// The previews' own origin only shows previews, embed frames and their files: not the API
|
|
239
|
+
if (previewOrigin &&
|
|
240
|
+
new URL(c.req.url).origin === previewOrigin &&
|
|
241
|
+
c.req.path.startsWith("/api/"))
|
|
242
|
+
return c.json({ error: "Not found" }, 404);
|
|
243
|
+
if (c.req.method !== "GET" && c.req.method !== "HEAD") {
|
|
244
|
+
const origin = c.req.header("origin");
|
|
245
|
+
if (!origin || !allowedOrigins.includes(origin))
|
|
246
|
+
return c.json({ error: "Forbidden" }, 403);
|
|
247
|
+
}
|
|
248
|
+
await next();
|
|
249
|
+
});
|
|
250
|
+
app.onError((error, c) => error instanceof EditorError
|
|
251
|
+
? c.json({
|
|
252
|
+
error: error.message,
|
|
253
|
+
...(error.problems ? { problems: error.problems } : {}),
|
|
254
|
+
}, error.status)
|
|
255
|
+
: c.json({ error: error.message }, 500));
|
|
256
|
+
app.get("/api/articles", async (c) => c.json(await store.query(articleQuery(new URL(c.req.url).searchParams))));
|
|
257
|
+
app.get("/api/articles/recent", async (c) => c.json(await store.recent()));
|
|
258
|
+
app.get("/api/files", async (c) => c.json(await store.queryFiles(fileQuery(new URL(c.req.url).searchParams))));
|
|
259
|
+
app.get("/api/files/filters", async (c) => c.json(await store.fileFilters()));
|
|
260
|
+
app.get("/api/files/:type/:slug/:name/references", async (c) => c.json(await store.fileReferences(c.req.param("type"), c.req.param("slug"), c.req.param("name"))));
|
|
261
|
+
app.put("/api/files/:type/:slug/:name", async (c) => {
|
|
262
|
+
const body = await c.req.parseBody();
|
|
263
|
+
const file = body.file;
|
|
264
|
+
if (!(file instanceof File))
|
|
265
|
+
throw new EditorError(400, 'Expected a file in the "file" field');
|
|
266
|
+
return c.json(await store.replaceFile(c.req.param("type"), c.req.param("slug"), c.req.param("name"), file.name, new Uint8Array(await file.arrayBuffer())));
|
|
267
|
+
});
|
|
268
|
+
app.delete("/api/files/:type/:slug/:name", async (c) => c.json(await store.deleteFile(c.req.param("type"), c.req.param("slug"), c.req.param("name"))));
|
|
269
|
+
app.get("/api/articles/filters", async (c) => c.json(await store.filters()));
|
|
270
|
+
app.get("/api/types", async (c) => c.json(await store.types()));
|
|
271
|
+
app.get("/api/site", async (c) => c.json(await store.site()));
|
|
272
|
+
app.get("/api/metadata", async (c) => c.json(await store.metadataInfo()));
|
|
273
|
+
app.get("/api/templates/:type", (c) => c.json(store.templates(c.req.param("type"))));
|
|
274
|
+
app.get("/api/embeds", async (c) => c.json((await plugins()).map(({ key, name, description, info, contentOptional, options, editor, }) => ({
|
|
275
|
+
key,
|
|
276
|
+
name,
|
|
277
|
+
description,
|
|
278
|
+
info,
|
|
279
|
+
contentOptional,
|
|
280
|
+
icon: editor?.icon,
|
|
281
|
+
options,
|
|
282
|
+
}))));
|
|
283
|
+
app.post("/api/embed-validations", async (c) => {
|
|
284
|
+
const { key, content, options } = await embedRequest(c.req.raw);
|
|
285
|
+
const embeds = await embedResolver(QUIET);
|
|
286
|
+
return c.json({
|
|
287
|
+
errors: await embeds.validate(key, content, options),
|
|
288
|
+
});
|
|
289
|
+
});
|
|
290
|
+
app.post("/api/embed-frames", async (c) => {
|
|
291
|
+
const frame = await embedRequest(c.req.raw);
|
|
292
|
+
const { key, content, options } = frame;
|
|
293
|
+
const warnings = [];
|
|
294
|
+
const embeds = await embedResolver({
|
|
295
|
+
warn: (message) => warnings.push(message),
|
|
296
|
+
});
|
|
297
|
+
// Content that isn't valid isn't on the website, so it has no frame
|
|
298
|
+
const known = (await plugins()).some((plugin) => plugin.key === key);
|
|
299
|
+
const errors = known ? await embeds.validate(key, content, options) : [];
|
|
300
|
+
if (errors.length)
|
|
301
|
+
return c.json({ url: "", errors, warnings });
|
|
302
|
+
// Rendered now to report problems, then again each time the frame is shown
|
|
303
|
+
await embeds.renderPage(embeds.place(key, embedText(content, options), "Embed"), "Embed", "editor");
|
|
304
|
+
return c.json({
|
|
305
|
+
url: `/embed-frame/${store.rememberEmbedFrame(frame)}/`,
|
|
306
|
+
errors,
|
|
307
|
+
warnings,
|
|
308
|
+
});
|
|
309
|
+
});
|
|
310
|
+
// A remembered embed block, rendered for the editor now, so changes to its plugin show when it reloads
|
|
311
|
+
app.get("/embed-frame/:id/", async (c) => {
|
|
312
|
+
const { key, content, options } = store.embedFrame(c.req.param("id"));
|
|
313
|
+
const theme = c.req.query("theme");
|
|
314
|
+
const embeds = await embedResolver(QUIET);
|
|
315
|
+
return c.html(await embeds.renderPage(embedFramePage(embeds.place(key, embedText(content, options), "Embed"), EMBED_PAGE_PARTS, theme === "light" || theme === "dark" ? theme : undefined), "Embed", "editor"), 200, {
|
|
316
|
+
"Cache-Control": "no-store",
|
|
317
|
+
"Content-Security-Policy": await csp(c.req.url),
|
|
318
|
+
});
|
|
319
|
+
});
|
|
320
|
+
app.post("/api/convert/markdown", async (c) => {
|
|
321
|
+
const { html, location } = await c.req.json();
|
|
322
|
+
return c.json({
|
|
323
|
+
markdown: editorHtmlToMarkdown(html, bodyBaseUrl(location)),
|
|
324
|
+
});
|
|
325
|
+
});
|
|
326
|
+
app.post("/api/convert/html", async (c) => {
|
|
327
|
+
const { markdown, location } = await c.req.json();
|
|
328
|
+
return c.json({
|
|
329
|
+
html: markdownToEditorHtml(markdown, bodyBaseUrl(location)),
|
|
330
|
+
});
|
|
331
|
+
});
|
|
332
|
+
app.post("/api/preview", async (c) => {
|
|
333
|
+
const { data, location } = await c.req.json();
|
|
334
|
+
const embeds = await embedResolver(QUIET);
|
|
335
|
+
// Rendered now to report problems (e.g. a missing file), then again each time the page is shown
|
|
336
|
+
await store.preview(data, location, embeds);
|
|
337
|
+
return c.json({
|
|
338
|
+
url: `/preview/${store.rememberPreview(data, location)}/`,
|
|
339
|
+
});
|
|
340
|
+
});
|
|
341
|
+
app.post("/api/articles", async (c) => {
|
|
342
|
+
const data = await c.req.json();
|
|
343
|
+
return c.json(await store.save(data), 201);
|
|
344
|
+
});
|
|
345
|
+
app.get("/api/articles/:type/:slug", async (c) => c.json(await store.read(c.req.param("type"), c.req.param("slug"))));
|
|
346
|
+
app.put("/api/articles/:type/:slug", async (c) => {
|
|
347
|
+
const data = await c.req.json();
|
|
348
|
+
return c.json(await store.save(data, {
|
|
349
|
+
type: c.req.param("type"),
|
|
350
|
+
slug: c.req.param("slug"),
|
|
351
|
+
}));
|
|
352
|
+
});
|
|
353
|
+
app.delete("/api/articles/:type/:slug", async (c) => {
|
|
354
|
+
await store.remove(c.req.param("type"), c.req.param("slug"));
|
|
355
|
+
return c.body(null, 204);
|
|
356
|
+
});
|
|
357
|
+
app.post("/api/articles/:type/:slug/files", async (c) => {
|
|
358
|
+
const body = await c.req.parseBody();
|
|
359
|
+
const file = body.file;
|
|
360
|
+
if (!(file instanceof File))
|
|
361
|
+
throw new EditorError(400, 'Expected a file in the "file" field');
|
|
362
|
+
return c.json(await store.upload(c.req.param("type"), c.req.param("slug"), file.name, new Uint8Array(await file.arrayBuffer())), 201);
|
|
363
|
+
});
|
|
364
|
+
app.get("/files/:type/:slug/:name", async (c) => {
|
|
365
|
+
const name = c.req.param("name");
|
|
366
|
+
const contents = await store.file(c.req.param("type"), c.req.param("slug"), name);
|
|
367
|
+
return c.body(contents, 200, {
|
|
368
|
+
"Content-Type": mime.lookup(name) || "application/octet-stream",
|
|
369
|
+
"Cache-Control": "no-store",
|
|
370
|
+
});
|
|
371
|
+
});
|
|
372
|
+
// A remembered preview, rendered now, so template changes show when it reloads
|
|
373
|
+
app.get("/preview/:id/", async (c) => {
|
|
374
|
+
const html = await store.renderPreview(c.req.param("id"), await embedResolver(QUIET));
|
|
375
|
+
return c.html(html, 200, {
|
|
376
|
+
"Cache-Control": "no-store",
|
|
377
|
+
"Content-Security-Policy": await csp(c.req.url),
|
|
378
|
+
});
|
|
379
|
+
});
|
|
380
|
+
// The site's static files (stylesheet, fonts) and articles' files, at their paths on the website as pages link them
|
|
381
|
+
app.get("/*", async (c) => {
|
|
382
|
+
const path = decodeURIComponent(c.req.path.slice(1));
|
|
383
|
+
return c.body((await store.staticFile(path)), 200, {
|
|
384
|
+
"Content-Type": mime.lookup(path) || "application/octet-stream",
|
|
385
|
+
"Cache-Control": "no-store",
|
|
386
|
+
"Content-Security-Policy": await csp(c.req.url),
|
|
387
|
+
});
|
|
388
|
+
});
|
|
389
|
+
return app;
|
|
390
|
+
};
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import type { ArticleFilters, IndexedFile, MetadataProblem, ArticlePage, ArticleQuery, ArticleSummary, RecentArticles } from "../types/index.ts";
|
|
2
|
+
/** Finds problems with an article's custom metadata, from its type and settings */
|
|
3
|
+
export type MetadataCheck = (type: string, settings: Record<string, unknown>) => MetadataProblem[];
|
|
4
|
+
/** The most articles a page of query results has */
|
|
5
|
+
export declare const MAX_PER_PAGE = 50;
|
|
6
|
+
/** How many of each type's most recently changed articles the editor's nav shows */
|
|
7
|
+
export declare const RECENT_COUNT = 5;
|
|
8
|
+
/**
|
|
9
|
+
* Read an article's summary from its folder: its settings, title, when its article.md last changed, and (with `check`)
|
|
10
|
+
* problems with its custom metadata. Articles that can't be read are summarised with their error. Undefined if the
|
|
11
|
+
* folder has no article.md.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* await summarizeArticle("my-site/articles", "news", "hello");
|
|
15
|
+
* // { type: "news", slug: "hello", title: "Hello", status: "published", date: "2026-10-19T09:54:00.000Z", tags: [], ... }
|
|
16
|
+
*/
|
|
17
|
+
export declare const summarizeArticle: (articlesDir: string, type: string, slug: string, check?: MetadataCheck) => Promise<ArticleSummary | undefined>;
|
|
18
|
+
/**
|
|
19
|
+
* Text for comparing without case or accents.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* comparable("Zoë Ångström"); // "zoe angstrom"
|
|
23
|
+
*/
|
|
24
|
+
export declare const comparable: (text: string) => string;
|
|
25
|
+
/**
|
|
26
|
+
* Find articles: those whose title contains the search text (ignoring case and accents) and that match the type,
|
|
27
|
+
* author, tag, status and problems given, sorted by title, type, status, date or when their file last changed, ascending or
|
|
28
|
+
* descending (by default titles, types and statuses A to Z and dates newest first), one page at a time.
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* queryArticles(articles, { search: "hello", type: "news", sort: "title", page: 2 });
|
|
32
|
+
* // { articles: [...], total: 73, page: 2, pages: 2, perPage: 50 }
|
|
33
|
+
*/
|
|
34
|
+
export declare const queryArticles: (articles: ArticleSummary[], query?: ArticleQuery) => ArticlePage;
|
|
35
|
+
/**
|
|
36
|
+
* Each type's most recently changed articles (by when their file last changed), types in alphabetical order.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* recentArticles(articles, 5); // [{ type: "news", articles: [...5 articles], total: 120 }, ...]
|
|
40
|
+
*/
|
|
41
|
+
export declare const recentArticles: (articles: ArticleSummary[], count?: number) => RecentArticles[];
|
|
42
|
+
/**
|
|
43
|
+
* The types, authors and tags articles use, for the article browser's filters.
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* articleFilters(articles); // { types: ["news", "page"], authors: ["Matt"], tags: ["News", "Releases"] }
|
|
47
|
+
*/
|
|
48
|
+
export declare const articleFilters: (articles: ArticleSummary[]) => ArticleFilters;
|
|
49
|
+
/**
|
|
50
|
+
* The files in an article's folder (not article.md or hidden files), with their kind, size and when they last changed.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* await articleFiles("my-site/articles", "news", "hello"); // [{ type: "news", slug: "hello", name: "photo.png", ... }]
|
|
54
|
+
*/
|
|
55
|
+
export declare const articleFiles: (articlesDir: string, type: string, slug: string) => Promise<IndexedFile[]>;
|
|
56
|
+
/** Options for an `ArticleIndex` */
|
|
57
|
+
export interface ArticleIndexOptions {
|
|
58
|
+
/** How long to wait for more file changes before reading them again, in milliseconds (default: 100) */
|
|
59
|
+
watchDelay?: number;
|
|
60
|
+
/** Called after changes found by watching have been read (e.g. for tests) */
|
|
61
|
+
onWatchUpdate?: () => void;
|
|
62
|
+
/** Finds problems with articles' custom metadata (none are found without it) */
|
|
63
|
+
check?: MetadataCheck | undefined;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* An in-memory index of a site's articles, so the editor can search, filter and sort them without reading every file
|
|
67
|
+
* each time. `load` reads every article; `update` and `delete` keep an entry up to date when the editor changes it;
|
|
68
|
+
* `watch` reads entries again when their files change outside the editor (e.g. a `git pull` or a text editor). The
|
|
69
|
+
* article files stay the only source of truth: nothing is written.
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
* const index = new ArticleIndex("my-site/articles");
|
|
73
|
+
* await index.load();
|
|
74
|
+
* index.watch();
|
|
75
|
+
* queryArticles(index.articles(), { search: "hello" });
|
|
76
|
+
*/
|
|
77
|
+
export declare class ArticleIndex {
|
|
78
|
+
/** Each article's summary and the files in its folder, by "type/slug" */
|
|
79
|
+
private readonly entries;
|
|
80
|
+
private readonly articlesDir;
|
|
81
|
+
private watcher?;
|
|
82
|
+
/** Changed folders waiting to be read again: articles ("news/hello"), whole types ("news"), or everything ("") */
|
|
83
|
+
private readonly pending;
|
|
84
|
+
private timer?;
|
|
85
|
+
private readonly watchDelay;
|
|
86
|
+
private readonly onWatchUpdate?;
|
|
87
|
+
private readonly check?;
|
|
88
|
+
/**
|
|
89
|
+
* @param articlesDir - the site's articles folder, holding a folder per type, each holding a folder per article
|
|
90
|
+
*/
|
|
91
|
+
constructor(articlesDir: string, options?: ArticleIndexOptions);
|
|
92
|
+
/** Every indexed article */
|
|
93
|
+
articles(): ArticleSummary[];
|
|
94
|
+
/** Every file in the indexed articles' folders */
|
|
95
|
+
files(): IndexedFile[];
|
|
96
|
+
/** An article's summary and files, or undefined if it has no article.md */
|
|
97
|
+
private readEntry;
|
|
98
|
+
/** Read every article again, replacing the index */
|
|
99
|
+
load(): Promise<void>;
|
|
100
|
+
/** Read every article of a type */
|
|
101
|
+
private readType;
|
|
102
|
+
/** Read a type's articles again, dropping those that are gone */
|
|
103
|
+
private updateType;
|
|
104
|
+
/**
|
|
105
|
+
* Read an article and its files again, e.g. after the editor saved it. It is dropped if it's gone.
|
|
106
|
+
*/
|
|
107
|
+
update(type: string, slug: string): Promise<void>;
|
|
108
|
+
/**
|
|
109
|
+
* Drop an article, e.g. after the editor deleted or moved it.
|
|
110
|
+
*/
|
|
111
|
+
delete(type: string, slug: string): void;
|
|
112
|
+
/**
|
|
113
|
+
* Read entries again when their files change, until `close` is called. Doesn't keep the process running. Does
|
|
114
|
+
* nothing if the articles folder doesn't exist or the system can't watch it.
|
|
115
|
+
*/
|
|
116
|
+
watch(): void;
|
|
117
|
+
/**
|
|
118
|
+
* Note a changed path (relative to the articles folder) to read again once changes pause. A path inside an article
|
|
119
|
+
* folder reads that article; a type folder reads the type; an unknown path reads everything.
|
|
120
|
+
*/
|
|
121
|
+
private changed;
|
|
122
|
+
/** Read the changed folders again */
|
|
123
|
+
private flush;
|
|
124
|
+
/** Stop watching for changes */
|
|
125
|
+
close(): void;
|
|
126
|
+
}
|