bearminion 1.13.0 → 1.15.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/CHANGELOG.md +12 -0
- package/dist/astro.d.ts +75 -45
- package/dist/astro.js +106 -1553
- package/dist/cli.js +1 -1
- package/dist/content.d.ts +1 -1
- package/dist/content.js +1 -1
- package/dist/{draft-store-1Y4-sn45.js → draft-store-BaZYEe56.js} +45 -1
- package/dist/editor-context-CTfxXtny.d.ts +272 -0
- package/dist/{forms-dev-CEab55ss.js → forms-dev-CzUHR7oS.js} +1 -1
- package/dist/github-store-BT9uiq5W.d.ts +64 -0
- package/dist/github-store-D0bQOwdt.js +1755 -0
- package/dist/hosted.d.ts +45 -0
- package/dist/hosted.js +37 -0
- package/dist/index.d.ts +2 -103
- package/dist/{page-CwbIDegI.d.ts → page-FipdIFb5.d.ts} +37 -37
- package/dist/{reload-BIIa7pej.js → reload-BzVw721A.js} +1 -1
- package/dist/security-CBiOYdVE.js +24 -0
- package/dist/ui/mount.js +1 -2
- package/package.json +5 -1
- package/registry/default/registry.json +1 -1
- package/dist/options-DP6mTauQ.d.ts +0 -205
- package/dist/security-FLvgc2jD.js +0 -93
- package/dist/upload-rules-Cao9uY5K.js +0 -36
package/dist/astro.js
CHANGED
|
@@ -1,14 +1,13 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { c as ContentReadError, l as ContentValidationError, r as loadThemePreview, t as PreviewUnavailableError } from "./preview-ImEm3T8k.js";
|
|
2
2
|
import { t as defaultTheme } from "./theme-BvqJ8UnS.js";
|
|
3
|
-
import { a as resolvePageRules,
|
|
4
|
-
import { a as DEFAULT_UPLOADS_DIR, i as DEFAULT_CONTENT_DIR, n as createMigrator, o as DEFAULT_VIDEOS_DIR,
|
|
5
|
-
import {
|
|
6
|
-
import { a as
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import { n as contentReloadPlugin, r as dropEarlyReloadAfterSave } from "./reload-
|
|
3
|
+
import { a as resolvePageRules, n as createPageSchema, r as createTolerantPageSchema } from "./page-wlcQJAA-.js";
|
|
4
|
+
import { a as DEFAULT_UPLOADS_DIR, i as DEFAULT_CONTENT_DIR, n as createMigrator, o as DEFAULT_VIDEOS_DIR, t as SCHEMA_VERSION_KEY } from "./migrate-b408EaLp.js";
|
|
5
|
+
import { D as resolveMaxImageBytes, E as resolveConvert, S as isAssetPath, T as formatBytes } from "./draft-store-BaZYEe56.js";
|
|
6
|
+
import { a as COMMIT_MESSAGE_LIMIT, c as StoreKeyError, d as uploadStem, f as stableStringify, g as isLocalRequest, h as JSON_BODY_LIMIT, i as isHistoryId, l as imageBodyLimit, m as videoBodyLimit, n as handleEditorRequest, o as GitError, r as historyId, s as StoreError, t as githubStore, u as IMAGE_EXTENSION } from "./github-store-D0bQOwdt.js";
|
|
7
|
+
import { i as resolveInside, n as isInside, r as resolveDir, t as asDirectory } from "./security-CBiOYdVE.js";
|
|
8
|
+
import { a as resolveFormsConfig, n as formFile, r as formsAreLive, t as createFormsMiddleware } from "./forms-dev-CzUHR7oS.js";
|
|
9
|
+
import { n as contentReloadPlugin, r as dropEarlyReloadAfterSave } from "./reload-BzVw721A.js";
|
|
10
10
|
import { i as syncSections, r as staleSectionsMessage } from "./sections-manifest-CO9QfJPG.js";
|
|
11
|
-
import { z } from "zod";
|
|
12
11
|
import fs from "node:fs";
|
|
13
12
|
import path from "node:path";
|
|
14
13
|
import { fileURLToPath } from "node:url";
|
|
@@ -46,32 +45,6 @@ const EXTENSION = {
|
|
|
46
45
|
webm: ".webm",
|
|
47
46
|
ogv: ".ogv"
|
|
48
47
|
};
|
|
49
|
-
const MIME_TO_KIND$1 = {
|
|
50
|
-
"video/mp4": "mp4",
|
|
51
|
-
"video/x-m4v": "mp4",
|
|
52
|
-
"video/quicktime": "mov",
|
|
53
|
-
"video/webm": "webm",
|
|
54
|
-
"video/ogg": "ogv"
|
|
55
|
-
};
|
|
56
|
-
/** Room for multipart boundaries around a max-size video. */
|
|
57
|
-
function videoBodyLimit(maxVideoBytes) {
|
|
58
|
-
return maxVideoBytes + 262144;
|
|
59
|
-
}
|
|
60
|
-
/** The container a file really is, from its first bytes. The file's name and declared type are not trusted. */
|
|
61
|
-
function sniffVideo(bytes) {
|
|
62
|
-
if (bytes.length >= 12 && ascii$1(bytes, 4, 8) === "ftyp") {
|
|
63
|
-
const brand = ascii$1(bytes, 8, 12);
|
|
64
|
-
if (brand === "avif" || brand === "avis") return null;
|
|
65
|
-
return brand === "qt " ? "mov" : "mp4";
|
|
66
|
-
}
|
|
67
|
-
if (bytes.length >= 4 && bytes[0] === 26 && bytes[1] === 69 && bytes[2] === 223 && bytes[3] === 163) return ascii$1(bytes, 0, Math.min(bytes.length, 64)).includes("webm") ? "webm" : null;
|
|
68
|
-
if (bytes.length >= 4 && ascii$1(bytes, 0, 4) === "OggS") return "ogv";
|
|
69
|
-
return null;
|
|
70
|
-
}
|
|
71
|
-
function videoKindFromMime(mime) {
|
|
72
|
-
const base = mime.split(";", 1)[0]?.trim().toLowerCase() ?? "";
|
|
73
|
-
return MIME_TO_KIND$1[base] ?? null;
|
|
74
|
-
}
|
|
75
48
|
/** The address a file in `public/` is served at. */
|
|
76
49
|
function publicUrl(root, filePath) {
|
|
77
50
|
return `/${path.relative(path.resolve(root, "public"), filePath).split(path.sep).join("/")}`;
|
|
@@ -141,9 +114,6 @@ async function deleteVideo(videosDir, filename) {
|
|
|
141
114
|
function safeStem(originalName) {
|
|
142
115
|
return path.win32.basename(path.basename(originalName)).replace(/\.[^.]+$/, "").normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "video";
|
|
143
116
|
}
|
|
144
|
-
function ascii$1(bytes, from, to) {
|
|
145
|
-
return Buffer.from(bytes.subarray(from, to)).toString("latin1");
|
|
146
|
-
}
|
|
147
117
|
//#endregion
|
|
148
118
|
//#region src/asset-refs.ts
|
|
149
119
|
/**
|
|
@@ -155,34 +125,6 @@ function assetFile(root, uploadsDir, src) {
|
|
|
155
125
|
const absolute = path.resolve(root, src);
|
|
156
126
|
return isInside(path.resolve(root, "src/assets"), absolute) || isInside(uploadsDir, absolute) ? absolute : null;
|
|
157
127
|
}
|
|
158
|
-
/** One validation issue per image path in `document` whose file does not exist. */
|
|
159
|
-
async function missingAssetIssues(document, exists) {
|
|
160
|
-
const refs = assetRefs(document);
|
|
161
|
-
const present = await Promise.all(refs.map((ref) => exists(ref.src)));
|
|
162
|
-
return refs.flatMap((ref, index) => present[index] ? [] : [{
|
|
163
|
-
path: ref.path,
|
|
164
|
-
message: `Image file not found: ${ref.src}. Choose another image or upload it again.`
|
|
165
|
-
}]);
|
|
166
|
-
}
|
|
167
|
-
//#endregion
|
|
168
|
-
//#region src/stable-json.ts
|
|
169
|
-
/**
|
|
170
|
-
* Pretty JSON with sorted object keys and a trailing newline.
|
|
171
|
-
* Arrays keep their order. Two writes of the same value match byte for byte.
|
|
172
|
-
*/
|
|
173
|
-
function stableStringify(value) {
|
|
174
|
-
return `${JSON.stringify(sortKeys(value), null, 2)}\n`;
|
|
175
|
-
}
|
|
176
|
-
function sortKeys(value) {
|
|
177
|
-
if (Array.isArray(value)) return value.map((item) => sortKeys(item));
|
|
178
|
-
if (value !== null && typeof value === "object") {
|
|
179
|
-
const source = value;
|
|
180
|
-
const sorted = {};
|
|
181
|
-
for (const key of Object.keys(source).sort()) sorted[key] = sortKeys(source[key]);
|
|
182
|
-
return sorted;
|
|
183
|
-
}
|
|
184
|
-
return value;
|
|
185
|
-
}
|
|
186
128
|
//#endregion
|
|
187
129
|
//#region src/atomic-write.ts
|
|
188
130
|
/**
|
|
@@ -206,66 +148,7 @@ function writeJsonAtomic(filePath, value) {
|
|
|
206
148
|
return writeTextAtomic(filePath, stableStringify(value));
|
|
207
149
|
}
|
|
208
150
|
//#endregion
|
|
209
|
-
//#region src/upload-names.ts
|
|
210
|
-
const IMAGE_EXTENSION = {
|
|
211
|
-
png: ".png",
|
|
212
|
-
jpeg: ".jpg",
|
|
213
|
-
webp: ".webp",
|
|
214
|
-
gif: ".gif",
|
|
215
|
-
avif: ".avif"
|
|
216
|
-
};
|
|
217
|
-
const EXTENSIONS = Object.values(IMAGE_EXTENSION);
|
|
218
|
-
/** True for a file name with an image extension the editor handles. */
|
|
219
|
-
function hasImageExtension(name) {
|
|
220
|
-
const dot = name.lastIndexOf(".");
|
|
221
|
-
return dot > 0 && EXTENSIONS.includes(name.slice(dot).toLowerCase());
|
|
222
|
-
}
|
|
223
|
-
/** A plain image file name: no folders, no leading dot, an extension the editor handles. */
|
|
224
|
-
function isUploadFilename(name) {
|
|
225
|
-
return name !== "" && !name.includes("/") && !name.includes("\\") && !name.startsWith(".") && hasImageExtension(name);
|
|
226
|
-
}
|
|
227
|
-
/** The readable part of an upload's name: the original file name, lowercase ASCII, at most 48 characters. */
|
|
228
|
-
const PLAIN_LETTERS = {
|
|
229
|
-
ł: "l",
|
|
230
|
-
đ: "d",
|
|
231
|
-
ø: "o",
|
|
232
|
-
ð: "d",
|
|
233
|
-
þ: "th",
|
|
234
|
-
ß: "ss",
|
|
235
|
-
æ: "ae",
|
|
236
|
-
œ: "oe",
|
|
237
|
-
ı: "i"
|
|
238
|
-
};
|
|
239
|
-
function uploadStem(originalName) {
|
|
240
|
-
return (originalName.split(/[\\/]/).pop() ?? "").replace(/\.[^.]+$/, "").normalize("NFKD").replace(/\p{M}/gu, "").toLowerCase().replace(/[łđøðþßæœı]/g, (letter) => PLAIN_LETTERS[letter] ?? letter).replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "image";
|
|
241
|
-
}
|
|
242
|
-
/** `photo-1a2b3c4d.jpg`: the stem, eight random hex digits, the extension for the sniffed kind. */
|
|
243
|
-
function uploadFilename(originalName, kind) {
|
|
244
|
-
const random = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(4));
|
|
245
|
-
const suffix = Array.from(random, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
246
|
-
return `${uploadStem(originalName)}-${suffix}${IMAGE_EXTENSION[kind]}`;
|
|
247
|
-
}
|
|
248
|
-
//#endregion
|
|
249
151
|
//#region src/images.ts
|
|
250
|
-
const MIME_TO_KIND = {
|
|
251
|
-
"image/png": "png",
|
|
252
|
-
"image/jpeg": "jpeg",
|
|
253
|
-
"image/webp": "webp",
|
|
254
|
-
"image/gif": "gif",
|
|
255
|
-
"image/avif": "avif"
|
|
256
|
-
};
|
|
257
|
-
function sniffImage(bytes) {
|
|
258
|
-
if (isPng(bytes)) return "png";
|
|
259
|
-
if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "jpeg";
|
|
260
|
-
if (isGif(bytes)) return "gif";
|
|
261
|
-
if (isWebp(bytes)) return "webp";
|
|
262
|
-
if (isAvif(bytes)) return "avif";
|
|
263
|
-
return null;
|
|
264
|
-
}
|
|
265
|
-
function kindFromMime(mime) {
|
|
266
|
-
const base = mime.split(";", 1)[0]?.trim().toLowerCase() ?? "";
|
|
267
|
-
return MIME_TO_KIND[base] ?? null;
|
|
268
|
-
}
|
|
269
152
|
/** Write image bytes under `uploadsDir` using a sniffed extension and a unique name. */
|
|
270
153
|
async function saveImage(options) {
|
|
271
154
|
await mkdir(options.uploadsDir, { recursive: true });
|
|
@@ -329,74 +212,16 @@ async function deleteImage(uploadsDir, filename) {
|
|
|
329
212
|
return false;
|
|
330
213
|
}
|
|
331
214
|
}
|
|
332
|
-
function imageTooLarge(size, maxBytes = IMAGE_BYTE_LIMIT) {
|
|
333
|
-
return size > maxBytes;
|
|
334
|
-
}
|
|
335
|
-
/** The largest request body an image upload may have: the file plus room for the multipart boundaries. */
|
|
336
|
-
function imageBodyLimit(maxBytes) {
|
|
337
|
-
return maxBytes + 262144;
|
|
338
|
-
}
|
|
339
215
|
function projectRelative(root, filePath) {
|
|
340
216
|
const relative = path.relative(root, filePath);
|
|
341
217
|
if (!isInside(root, filePath)) throw new Error("Upload path is outside the project root.");
|
|
342
218
|
return relative.split(path.sep).join("/");
|
|
343
219
|
}
|
|
344
|
-
function isPng(bytes) {
|
|
345
|
-
return bytes.length >= 8 && bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71 && bytes[4] === 13 && bytes[5] === 10 && bytes[6] === 26 && bytes[7] === 10;
|
|
346
|
-
}
|
|
347
|
-
function isGif(bytes) {
|
|
348
|
-
if (bytes.length < 6) return false;
|
|
349
|
-
const header = ascii(bytes.subarray(0, 6));
|
|
350
|
-
return header === "GIF87a" || header === "GIF89a";
|
|
351
|
-
}
|
|
352
|
-
function isWebp(bytes) {
|
|
353
|
-
return bytes.length >= 12 && ascii(bytes.subarray(0, 4)) === "RIFF" && ascii(bytes.subarray(8, 12)) === "WEBP";
|
|
354
|
-
}
|
|
355
|
-
function isAvif(bytes) {
|
|
356
|
-
if (bytes.length < 12 || ascii(bytes.subarray(4, 8)) !== "ftyp") return false;
|
|
357
|
-
const brand = ascii(bytes.subarray(8, 12));
|
|
358
|
-
if (brand === "avif" || brand === "avis") return true;
|
|
359
|
-
return ascii(bytes.subarray(16)).includes("avif") || ascii(bytes.subarray(16)).includes("avis");
|
|
360
|
-
}
|
|
361
|
-
function ascii(bytes) {
|
|
362
|
-
const sample = bytes.byteLength > 64 ? bytes.subarray(0, 64) : bytes;
|
|
363
|
-
return Buffer.from(sample).toString("ascii");
|
|
364
|
-
}
|
|
365
220
|
function isErrno$2(error) {
|
|
366
221
|
return error instanceof Error && "code" in error;
|
|
367
222
|
}
|
|
368
223
|
//#endregion
|
|
369
|
-
//#region src/store-error.ts
|
|
370
|
-
/** A key that is empty, absolute or leaves the content directory. */
|
|
371
|
-
var StoreKeyError = class extends Error {
|
|
372
|
-
constructor(key) {
|
|
373
|
-
super(`"${key}" is not a path inside the content directory.`);
|
|
374
|
-
this.name = "StoreKeyError";
|
|
375
|
-
}
|
|
376
|
-
};
|
|
377
|
-
/**
|
|
378
|
-
* A store that could not do what was asked, for a reason the person editing can act on (a refused token, a protected
|
|
379
|
-
* branch, a branch that moved). The editor API answers it with `status` and `code`, so the message reaches the page
|
|
380
|
-
* instead of becoming a bare 500.
|
|
381
|
-
*/
|
|
382
|
-
var StoreError = class extends Error {
|
|
383
|
-
status;
|
|
384
|
-
code;
|
|
385
|
-
constructor(status, code, message) {
|
|
386
|
-
super(message);
|
|
387
|
-
this.name = "StoreError";
|
|
388
|
-
this.status = status;
|
|
389
|
-
this.code = code;
|
|
390
|
-
}
|
|
391
|
-
};
|
|
392
|
-
//#endregion
|
|
393
224
|
//#region src/store.ts
|
|
394
|
-
const SITE_KEY = "site.json";
|
|
395
|
-
const PAGES_DIR = "pages";
|
|
396
|
-
/** The key of the page with this slug. The slug must already be validated (`readSlug`). */
|
|
397
|
-
function pageKey(slug) {
|
|
398
|
-
return `${PAGES_DIR}/${slug}.json`;
|
|
399
|
-
}
|
|
400
225
|
/** The content store for a local project: content as JSON files, uploads in a folder. */
|
|
401
226
|
function createFileStore({ root, contentDir, uploadsDir, videosDir }) {
|
|
402
227
|
function resolve(key) {
|
|
@@ -477,143 +302,8 @@ function isErrno$1(error) {
|
|
|
477
302
|
return error instanceof Error && "code" in error;
|
|
478
303
|
}
|
|
479
304
|
//#endregion
|
|
480
|
-
//#region src/options.ts
|
|
481
|
-
function resolveEditorContext(options, rootInput) {
|
|
482
|
-
if (!options?.sections) throw new Error("bearminion() needs the `sections` option: the site's section definitions.");
|
|
483
|
-
if (!options.site) throw new Error("bearminion() needs the `site` option: the site's header and footer definition from defineSite().");
|
|
484
|
-
const root = asDirectory(rootInput);
|
|
485
|
-
const contentDir = resolveDir(root, options?.contentDir, DEFAULT_CONTENT_DIR);
|
|
486
|
-
const uploadsDir = resolveDir(root, options?.uploadsDir, DEFAULT_UPLOADS_DIR);
|
|
487
|
-
const videosDir = resolveDir(root, options?.videosDir, DEFAULT_VIDEOS_DIR);
|
|
488
|
-
return {
|
|
489
|
-
root,
|
|
490
|
-
contentDir,
|
|
491
|
-
uploadsDir,
|
|
492
|
-
videosDir,
|
|
493
|
-
maxVideoBytes: options?.maxVideoBytes ?? 52428800,
|
|
494
|
-
maxImageBytes: resolveMaxImageBytes(options?.maxImageBytes),
|
|
495
|
-
pageRules: resolvePageRules(options?.pages),
|
|
496
|
-
imageConvert: resolveConvert(options?.imageConvert),
|
|
497
|
-
sections: options.sections,
|
|
498
|
-
site: options.site,
|
|
499
|
-
theme: options.theme ?? defaultTheme,
|
|
500
|
-
store: options.store ?? createFileStore({
|
|
501
|
-
root,
|
|
502
|
-
contentDir,
|
|
503
|
-
uploadsDir,
|
|
504
|
-
videosDir
|
|
505
|
-
}),
|
|
506
|
-
migrator: createMigrator(options),
|
|
507
|
-
git: options?.git === true,
|
|
508
|
-
formsDir: resolveFormsConfig(options?.forms, root)?.dir ?? null
|
|
509
|
-
};
|
|
510
|
-
}
|
|
511
|
-
//#endregion
|
|
512
|
-
//#region src/history.ts
|
|
513
|
-
/**
|
|
514
|
-
* Local copies of what was saved, in `<project>/.editor/history/`, so an earlier version of a page or of the
|
|
515
|
-
* site can be loaded back into the draft. Dev-only and untracked: the folder belongs in `.gitignore`.
|
|
516
|
-
*/
|
|
517
|
-
const HISTORY_DIR = ".editor/history";
|
|
518
|
-
const ID = /^\d{8}T\d{9}Z$/;
|
|
519
|
-
function isHistoryId(value) {
|
|
520
|
-
return ID.test(value);
|
|
521
|
-
}
|
|
522
|
-
/** `2026-10-13T12:55:30.123Z` → `20261013T125530123Z`. */
|
|
523
|
-
function historyId(date) {
|
|
524
|
-
return date.toISOString().replace(/[-:.]/g, "");
|
|
525
|
-
}
|
|
526
|
-
function idToIso(id) {
|
|
527
|
-
return `${id.slice(0, 4)}-${id.slice(4, 6)}-${id.slice(6, 8)}T${id.slice(9, 11)}:${id.slice(11, 13)}:${id.slice(13, 15)}.${id.slice(15, 18)}Z`;
|
|
528
|
-
}
|
|
529
|
-
function directory(context, scope, slug) {
|
|
530
|
-
return scope === "site" ? path.join(context.root, HISTORY_DIR, "site") : path.join(context.root, HISTORY_DIR, "pages", slug);
|
|
531
|
-
}
|
|
532
|
-
async function ids(dir) {
|
|
533
|
-
try {
|
|
534
|
-
return (await readdir(dir)).filter((name) => name.endsWith(".json") && isHistoryId(name.slice(0, -5))).map((name) => name.slice(0, -5)).sort();
|
|
535
|
-
} catch {
|
|
536
|
-
return [];
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
/** Newest first. */
|
|
540
|
-
async function listHistory(context, scope, slug = "") {
|
|
541
|
-
return (await ids(directory(context, scope, slug))).reverse().map((id) => ({
|
|
542
|
-
id,
|
|
543
|
-
at: idToIso(id)
|
|
544
|
-
}));
|
|
545
|
-
}
|
|
546
|
-
async function readHistory(context, scope, slug, id) {
|
|
547
|
-
if (!isHistoryId(id)) return null;
|
|
548
|
-
try {
|
|
549
|
-
return JSON.parse(await readFile(path.join(directory(context, scope, slug), `${id}.json`), "utf8"));
|
|
550
|
-
} catch {
|
|
551
|
-
return null;
|
|
552
|
-
}
|
|
553
|
-
}
|
|
554
|
-
/**
|
|
555
|
-
* Keep a copy of `value`. A value equal to the newest copy is skipped, and only the newest {@link HISTORY_KEEP}
|
|
556
|
-
* copies stay. Returns the new entry, or null when nothing was written. Never throws: history must not block a save.
|
|
557
|
-
*/
|
|
558
|
-
async function writeHistory(context, scope, slug, value, now = /* @__PURE__ */ new Date()) {
|
|
559
|
-
try {
|
|
560
|
-
const dir = directory(context, scope, slug);
|
|
561
|
-
const existing = await ids(dir);
|
|
562
|
-
const newest = existing[existing.length - 1];
|
|
563
|
-
if (newest !== void 0) {
|
|
564
|
-
if (await readFile(path.join(dir, `${newest}.json`), "utf8") === stableStringify(value)) return null;
|
|
565
|
-
}
|
|
566
|
-
let id = historyId(now);
|
|
567
|
-
while (existing.includes(id)) id = historyId(new Date(Date.parse(idToIso(id)) + 1));
|
|
568
|
-
await writeJsonAtomic(path.join(dir, `${id}.json`), value);
|
|
569
|
-
for (const old of [...existing, id].slice(0, -50)) await rm(path.join(dir, `${old}.json`), { force: true });
|
|
570
|
-
return {
|
|
571
|
-
id,
|
|
572
|
-
at: idToIso(id)
|
|
573
|
-
};
|
|
574
|
-
} catch {
|
|
575
|
-
return null;
|
|
576
|
-
}
|
|
577
|
-
}
|
|
578
|
-
/** Before the first save of a page or the site, keep the file as it was so even that first save can be undone. */
|
|
579
|
-
async function ensureBaseline(context, scope, slug, current) {
|
|
580
|
-
if ((await listHistory(context, scope, slug)).length > 0) return;
|
|
581
|
-
await writeHistory(context, scope, slug, current, /* @__PURE__ */ new Date(Date.now() - 1));
|
|
582
|
-
}
|
|
583
|
-
//#endregion
|
|
584
|
-
//#region src/validate.ts
|
|
585
|
-
function fieldIssues(error) {
|
|
586
|
-
return error.issues.map((issue) => ({
|
|
587
|
-
path: issue.path.length > 0 ? issue.path.map((part) => String(part)).join(".") : "(root)",
|
|
588
|
-
message: issue.message
|
|
589
|
-
}));
|
|
590
|
-
}
|
|
591
|
-
function validateSite(input, site) {
|
|
592
|
-
return site.schema.safeParse(input);
|
|
593
|
-
}
|
|
594
|
-
/** Validate a page document: its own fields, and each section against the registry's schema for its type. */
|
|
595
|
-
function validatePage(input, registry) {
|
|
596
|
-
return createPageSchema$1(registry).safeParse(input);
|
|
597
|
-
}
|
|
598
|
-
/**
|
|
599
|
-
* Validate a page for the editor: like {@link validatePage}, but a section of a type the registry no longer
|
|
600
|
-
* defines is kept as it is. The site build still rejects such a page until the section is removed.
|
|
601
|
-
*/
|
|
602
|
-
function validateEditorPage(input, registry) {
|
|
603
|
-
return createTolerantPageSchema(registry).safeParse(input);
|
|
604
|
-
}
|
|
605
|
-
//#endregion
|
|
606
305
|
//#region src/git.ts
|
|
607
306
|
const run = promisify(execFile);
|
|
608
|
-
/** Longest commit message the editor sends. */
|
|
609
|
-
const COMMIT_MESSAGE_LIMIT = 1e3;
|
|
610
|
-
var GitError = class extends Error {
|
|
611
|
-
code;
|
|
612
|
-
constructor(code, message) {
|
|
613
|
-
super(message);
|
|
614
|
-
this.code = code;
|
|
615
|
-
}
|
|
616
|
-
};
|
|
617
307
|
async function git(root, args) {
|
|
618
308
|
try {
|
|
619
309
|
const { stdout } = await run("git", args, {
|
|
@@ -627,7 +317,8 @@ async function git(root, args) {
|
|
|
627
317
|
return stdout;
|
|
628
318
|
} catch (error) {
|
|
629
319
|
const failure = error;
|
|
630
|
-
|
|
320
|
+
const detail = (failure.stderr || failure.stdout || failure.message).trim().split("\n").slice(-3).join("\n");
|
|
321
|
+
throw new GitError("failed", detail || "git failed.");
|
|
631
322
|
}
|
|
632
323
|
}
|
|
633
324
|
/** The folders a commit may touch: the content and the uploads. Relative to the project root. */
|
|
@@ -743,1005 +434,124 @@ async function commitChanges(context, message, paths) {
|
|
|
743
434
|
files: chosen.length
|
|
744
435
|
};
|
|
745
436
|
}
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
/**
|
|
749
|
-
* Dev-server API. Returns null when the URL is not under {@link API_PREFIX}
|
|
750
|
-
* so other middleware can continue. Every write is schema-checked first.
|
|
751
|
-
*/
|
|
752
|
-
async function handleEditorRequest(request, context, meta = {}) {
|
|
753
|
-
try {
|
|
754
|
-
return await route(request, context, meta);
|
|
755
|
-
} catch (error) {
|
|
756
|
-
if (error instanceof StoreError) return problem(error.status, error.code, error.message);
|
|
757
|
-
throw error;
|
|
758
|
-
}
|
|
759
|
-
}
|
|
760
|
-
async function route(request, context, meta) {
|
|
761
|
-
const pathname = stripTrailingSlash$1(new URL(request.url).pathname);
|
|
762
|
-
if (pathname !== "/__bearminion/api" && !pathname.startsWith(`/__bearminion/api/`)) return null;
|
|
763
|
-
if (!isLocalRequest(request.headers, meta.remoteAddress)) return problem(403, "forbidden", "The editor API only accepts requests from localhost.");
|
|
764
|
-
const parts = pathname.slice(API_PREFIX.length).replace(/^\//, "").split("/").filter((part) => part !== "");
|
|
765
|
-
const method = request.method.toUpperCase();
|
|
766
|
-
if (parts.length === 1 && parts[0] === "schema") {
|
|
767
|
-
if (method === "GET") return getSchema(context);
|
|
768
|
-
return methodNotAllowed(["GET"]);
|
|
769
|
-
}
|
|
770
|
-
if (parts.length === 1 && parts[0] === "site") {
|
|
771
|
-
if (method === "GET") return getSite(context);
|
|
772
|
-
if (method === "PUT") return putSite(request, context);
|
|
773
|
-
return methodNotAllowed(["GET", "PUT"]);
|
|
774
|
-
}
|
|
775
|
-
if (parts.length === 1 && parts[0] === "save") {
|
|
776
|
-
if (method === "POST") return postSave(request, context);
|
|
777
|
-
return methodNotAllowed(["POST"]);
|
|
778
|
-
}
|
|
779
|
-
if (parts.length === 1 && parts[0] === "pages") {
|
|
780
|
-
if (method === "GET") return getPages(context);
|
|
781
|
-
if (method === "POST") return createPage(request, context);
|
|
782
|
-
return methodNotAllowed(["GET", "POST"]);
|
|
783
|
-
}
|
|
784
|
-
if (parts.length === 1 && parts[0] === "forms") {
|
|
785
|
-
if (method === "GET") return getForms(context);
|
|
786
|
-
return methodNotAllowed(["GET"]);
|
|
787
|
-
}
|
|
788
|
-
if (parts.length === 1 && parts[0] === "git") {
|
|
789
|
-
if (method === "GET") return getGit(context);
|
|
790
|
-
return methodNotAllowed(["GET"]);
|
|
791
|
-
}
|
|
792
|
-
if (parts.length === 2 && parts[0] === "git" && parts[1] === "commit") {
|
|
793
|
-
if (method === "POST") return postCommit(request, context);
|
|
794
|
-
return methodNotAllowed(["POST"]);
|
|
795
|
-
}
|
|
796
|
-
if (parts.length === 1 && parts[0] === "images") {
|
|
797
|
-
if (method === "GET") return getImages(context);
|
|
798
|
-
if (method === "POST") return postImage(request, context);
|
|
799
|
-
return methodNotAllowed(["GET", "POST"]);
|
|
800
|
-
}
|
|
801
|
-
if (parts.length === 2 && parts[0] === "images") {
|
|
802
|
-
if (method === "DELETE") return removeImage(context, decodeSegment(parts[1] ?? ""));
|
|
803
|
-
return methodNotAllowed(["DELETE"]);
|
|
804
|
-
}
|
|
805
|
-
if (parts.length === 1 && parts[0] === "videos") {
|
|
806
|
-
if (method === "GET") return getVideos(context);
|
|
807
|
-
if (method === "POST") return postVideo(request, context);
|
|
808
|
-
return methodNotAllowed(["GET", "POST"]);
|
|
809
|
-
}
|
|
810
|
-
if (parts.length === 2 && parts[0] === "videos") {
|
|
811
|
-
if (method === "DELETE") return removeVideo(context, decodeSegment(parts[1] ?? ""));
|
|
812
|
-
return methodNotAllowed(["DELETE"]);
|
|
813
|
-
}
|
|
814
|
-
if (parts.length === 1 && parts[0] === "preview") {
|
|
815
|
-
if (method === "POST") return postPreview(request, context, meta);
|
|
816
|
-
return methodNotAllowed(["POST"]);
|
|
817
|
-
}
|
|
818
|
-
if (parts.length === 2 && parts[0] === "preview" && parts[1] === "site") {
|
|
819
|
-
if (method === "POST") return postSitePreview(request, context, meta);
|
|
820
|
-
return methodNotAllowed(["POST"]);
|
|
821
|
-
}
|
|
822
|
-
if (parts[0] === "history" && (parts[1] === "site" || parts[1] === "pages")) {
|
|
823
|
-
if (method !== "GET") return methodNotAllowed(["GET"]);
|
|
824
|
-
if (parts[1] === "site" && parts.length <= 3) return getHistory(context, "site", "", parts[2]);
|
|
825
|
-
if (parts[1] === "pages" && parts.length >= 3 && parts.length <= 4) {
|
|
826
|
-
const slug = readSlug(parts[2] ?? "");
|
|
827
|
-
if (slug === null) return badSlug();
|
|
828
|
-
return getHistory(context, "page", slug, parts[3]);
|
|
829
|
-
}
|
|
830
|
-
}
|
|
831
|
-
if (parts.length === 2 && parts[0] === "pages") {
|
|
832
|
-
const slug = readSlug(parts[1] ?? "");
|
|
833
|
-
if (slug === null) return badSlug();
|
|
834
|
-
if (method === "GET") return getPage(context, slug);
|
|
835
|
-
if (method === "PUT") return putPage(request, context, slug);
|
|
836
|
-
if (method === "DELETE") return deletePage(context, slug);
|
|
837
|
-
return methodNotAllowed([
|
|
838
|
-
"GET",
|
|
839
|
-
"PUT",
|
|
840
|
-
"DELETE"
|
|
841
|
-
]);
|
|
842
|
-
}
|
|
843
|
-
if (parts.length === 3 && parts[0] === "pages" && parts[2] === "rename") {
|
|
844
|
-
const slug = readSlug(parts[1] ?? "");
|
|
845
|
-
if (slug === null) return badSlug();
|
|
846
|
-
if (method === "POST") return renamePage(request, context, slug);
|
|
847
|
-
return methodNotAllowed(["POST"]);
|
|
848
|
-
}
|
|
849
|
-
if (parts.length === 3 && parts[0] === "pages" && parts[2] === "set-home") {
|
|
850
|
-
const slug = readSlug(parts[1] ?? "");
|
|
851
|
-
if (slug === null) return badSlug();
|
|
852
|
-
if (method === "POST") return setHome(request, context, slug);
|
|
853
|
-
return methodNotAllowed(["POST"]);
|
|
854
|
-
}
|
|
855
|
-
return problem(404, "not_found", "Unknown editor API route.");
|
|
856
|
-
}
|
|
857
|
-
/**
|
|
858
|
-
* Which form handlers the sections post to, and whether their files exist right now. Read on every call, so a handler
|
|
859
|
-
* created while `astro dev` runs shows up at once.
|
|
860
|
-
*/
|
|
861
|
-
async function getForms(context) {
|
|
862
|
-
const handlers = {};
|
|
863
|
-
for (const definition of Object.values(context.sections)) {
|
|
864
|
-
const name = definition.form;
|
|
865
|
-
if (!name || handlers[name]) continue;
|
|
866
|
-
const file = context.formsDir ? formFile(context.formsDir, name) : null;
|
|
867
|
-
handlers[name] = { file: file ? relativeTo(context.root, file) : null };
|
|
868
|
-
}
|
|
869
|
-
return json(200, {
|
|
870
|
-
enabled: context.formsDir != null,
|
|
871
|
-
handlers
|
|
872
|
-
});
|
|
873
|
-
}
|
|
874
|
-
function relativeTo(root, file) {
|
|
875
|
-
const prefix = root.endsWith("/") || root.endsWith("\\") ? root : `${root}/`;
|
|
876
|
-
return file.startsWith(prefix) ? file.slice(prefix.length).replaceAll("\\", "/") : file;
|
|
877
|
-
}
|
|
878
|
-
async function getSchema(context) {
|
|
879
|
-
const sectionDefaults = {};
|
|
880
|
-
const sectionLabels = {};
|
|
881
|
-
const sectionDescriptions = {};
|
|
882
|
-
const sectionWireframes = {};
|
|
883
|
-
const sectionOptions = {};
|
|
884
|
-
const optionalContent = {};
|
|
885
|
-
const contentCounts = { ...context.site.counts };
|
|
886
|
-
const fieldChoices = {};
|
|
887
|
-
const fieldIcons = {};
|
|
888
|
-
const showWhen = {};
|
|
889
|
-
const fieldImages = {};
|
|
890
|
-
const sectionForms = {};
|
|
891
|
-
for (const definition of Object.values(context.sections)) {
|
|
892
|
-
const type = definition.type;
|
|
893
|
-
if (definition.form) sectionForms[type] = definition.form;
|
|
894
|
-
sectionDefaults[type] = definition.defaults;
|
|
895
|
-
sectionLabels[type] = definition.label;
|
|
896
|
-
sectionDescriptions[type] = definition.description;
|
|
897
|
-
sectionWireframes[type] = definition.wireframe;
|
|
898
|
-
sectionOptions[type] = definition.options;
|
|
899
|
-
optionalContent[type] = definition.optional;
|
|
900
|
-
if (Object.keys(definition.counts).length > 0) contentCounts[type] = { ...definition.counts };
|
|
901
|
-
if (Object.keys(definition.choices).length > 0) fieldChoices[type] = definition.choices;
|
|
902
|
-
if (Object.keys(definition.icons).length > 0) fieldIcons[type] = definition.icons;
|
|
903
|
-
if (Object.keys(definition.showWhen).length > 0) showWhen[type] = definition.showWhen;
|
|
904
|
-
const images = imageFields(definition.schema);
|
|
905
|
-
if (images.length > 0) fieldImages[type] = images;
|
|
906
|
-
}
|
|
907
|
-
return json(200, {
|
|
908
|
-
sectionOptions,
|
|
909
|
-
siteOptions: context.site.options,
|
|
910
|
-
siteLimits: context.site.limits,
|
|
911
|
-
theme: context.theme,
|
|
912
|
-
contentCounts,
|
|
913
|
-
optionalContent,
|
|
914
|
-
fieldChoices,
|
|
915
|
-
fieldIcons,
|
|
916
|
-
fieldImages,
|
|
917
|
-
showWhen,
|
|
918
|
-
sectionForms,
|
|
919
|
-
pageRules: context.pageRules,
|
|
920
|
-
sectionDefaults,
|
|
921
|
-
sectionLabels,
|
|
922
|
-
sectionDescriptions,
|
|
923
|
-
sectionWireframes,
|
|
924
|
-
projectId: projectId(context.root, await siteName(context))
|
|
925
|
-
});
|
|
926
|
-
}
|
|
927
|
-
async function siteName(context) {
|
|
928
|
-
try {
|
|
929
|
-
return (await readSite(context)).name;
|
|
930
|
-
} catch {
|
|
931
|
-
return "";
|
|
932
|
-
}
|
|
933
|
-
}
|
|
934
|
-
async function getSite(context) {
|
|
935
|
-
try {
|
|
936
|
-
return json(200, await readSite(context));
|
|
937
|
-
} catch (error) {
|
|
938
|
-
return contentFailure(error);
|
|
939
|
-
}
|
|
940
|
-
}
|
|
941
|
-
async function putSite(request, context) {
|
|
942
|
-
const body = await readJsonBody(request);
|
|
943
|
-
if (body.response) return body.response;
|
|
944
|
-
const parsed = validateSite(body.value, context.site);
|
|
945
|
-
if (!parsed.success) return validation(fieldIssues(parsed.error));
|
|
946
|
-
const missing = await missingAssets(context, parsed.data);
|
|
947
|
-
if (missing.length > 0) return validation(missing);
|
|
948
|
-
await ensureBaseline(context, "site", "", await readStoredJson(context, SITE_KEY, "site"));
|
|
949
|
-
await writeDocuments(context, [[SITE_KEY, parsed.data]]);
|
|
950
|
-
await writeHistory(context, "site", "", parsed.data);
|
|
951
|
-
return json(200, parsed.data);
|
|
952
|
-
}
|
|
953
|
-
/** The parsed document at `key`, upgraded to the current version, or undefined when it is missing or not JSON. */
|
|
954
|
-
async function readStoredJson(context, key, kind) {
|
|
955
|
-
try {
|
|
956
|
-
const text = await context.store.read(key);
|
|
957
|
-
if (text === void 0) return void 0;
|
|
958
|
-
const upgraded = context.migrator.upgrade(JSON.parse(text), kind);
|
|
959
|
-
return upgraded.ok ? upgraded.value : void 0;
|
|
960
|
-
} catch (error) {
|
|
961
|
-
if (error instanceof StoreError) throw error;
|
|
962
|
-
return;
|
|
963
|
-
}
|
|
964
|
-
}
|
|
965
|
-
/** Write documents in the layout every file uses (sorted keys, two spaces, trailing newline). */
|
|
966
|
-
async function writeDocuments(context, documents, removals = []) {
|
|
967
|
-
await context.store.apply([...documents.map(([key, value]) => ({
|
|
968
|
-
type: "write",
|
|
969
|
-
key,
|
|
970
|
-
text: stableStringify(context.migrator.stamp(value))
|
|
971
|
-
})), ...removals.map((key) => ({
|
|
972
|
-
type: "remove",
|
|
973
|
-
key
|
|
974
|
-
}))]);
|
|
975
|
-
}
|
|
976
|
-
const saveSchema = z.object({
|
|
977
|
-
page: z.object({
|
|
978
|
-
/** The slug the page is stored under now. The document's own `slug` is where it goes. */
|
|
979
|
-
from: z.string(),
|
|
980
|
-
document: z.unknown(),
|
|
981
|
-
/** Where the current home page moves when this page becomes `index`. */
|
|
982
|
-
previousHomeSlug: z.string().optional()
|
|
983
|
-
}).strict().optional(),
|
|
984
|
-
site: z.unknown().optional()
|
|
985
|
-
}).strict().refine((value) => value.page !== void 0 || value.site !== void 0, { message: "Nothing to save." });
|
|
986
|
-
/**
|
|
987
|
-
* Save the editor draft in one request: a page (with its rename or promotion to home, when the slug
|
|
988
|
-
* changed) and the site. Every document is validated before anything is written, and all writes and
|
|
989
|
-
* removals go to the store as one `apply`, so a failure never leaves a page renamed with stale content
|
|
990
|
-
* or the page saved without the site.
|
|
991
|
-
*/
|
|
992
|
-
async function postSave(request, context) {
|
|
993
|
-
const body = await readJsonBody(request);
|
|
994
|
-
if (body.response) return body.response;
|
|
995
|
-
const parsed = saveSchema.safeParse(body.value);
|
|
996
|
-
if (!parsed.success) return validation(fieldIssues(parsed.error));
|
|
997
|
-
const writes = [];
|
|
998
|
-
const removals = [];
|
|
999
|
-
const after = [];
|
|
1000
|
-
const result = {};
|
|
1001
|
-
const failures = [];
|
|
1002
|
-
if (parsed.data.site !== void 0) {
|
|
1003
|
-
const upgraded = context.migrator.upgrade(parsed.data.site, "site");
|
|
1004
|
-
if (!upgraded.ok) failures.push(...tagIssues([{
|
|
1005
|
-
path: SCHEMA_VERSION_KEY,
|
|
1006
|
-
message: upgraded.message
|
|
1007
|
-
}], "site"));
|
|
1008
|
-
else {
|
|
1009
|
-
const site = validateSite(upgraded.value, context.site);
|
|
1010
|
-
const missing = site.success ? await missingAssets(context, site.data) : [];
|
|
1011
|
-
if (!site.success) failures.push(...tagIssues(fieldIssues(site.error), "site"));
|
|
1012
|
-
else if (missing.length > 0) failures.push(...tagIssues(missing, "site"));
|
|
1013
|
-
else {
|
|
1014
|
-
const stored = await readStoredJson(context, SITE_KEY, "site");
|
|
1015
|
-
writes.push([SITE_KEY, site.data]);
|
|
1016
|
-
after.push(async () => {
|
|
1017
|
-
await ensureBaseline(context, "site", "", stored);
|
|
1018
|
-
await writeHistory(context, "site", "", site.data);
|
|
1019
|
-
});
|
|
1020
|
-
result.site = site.data;
|
|
1021
|
-
}
|
|
1022
|
-
}
|
|
1023
|
-
}
|
|
1024
|
-
if (parsed.data.page !== void 0) {
|
|
1025
|
-
const planned = await planPageSave(context, parsed.data.page);
|
|
1026
|
-
if (planned.issues) failures.push(...tagIssues(planned.issues, "page"));
|
|
1027
|
-
else if (planned.response) {
|
|
1028
|
-
if (failures.length === 0) return planned.response;
|
|
1029
|
-
} else {
|
|
1030
|
-
writes.push(...planned.writes);
|
|
1031
|
-
removals.push(...planned.removals);
|
|
1032
|
-
after.push(planned.after);
|
|
1033
|
-
result.page = planned.page;
|
|
1034
|
-
}
|
|
1035
|
-
}
|
|
1036
|
-
if (failures.length > 0) return validation(failures);
|
|
1037
|
-
const written = new Set(writes.map(([key]) => key));
|
|
1038
|
-
await writeDocuments(context, writes, removals.filter((key) => !written.has(key)));
|
|
1039
|
-
for (const step of after) await step();
|
|
1040
|
-
return json(200, result);
|
|
1041
|
-
}
|
|
1042
|
-
async function planPageSave(context, input) {
|
|
1043
|
-
const from = readSlug(input.from);
|
|
1044
|
-
if (from === null) return { response: badSlug() };
|
|
1045
|
-
const upgraded = context.migrator.upgrade(input.document, "page");
|
|
1046
|
-
if (!upgraded.ok) return { issues: [{
|
|
1047
|
-
path: SCHEMA_VERSION_KEY,
|
|
1048
|
-
message: upgraded.message
|
|
1049
|
-
}] };
|
|
1050
|
-
const parsed = validateEditorPage(upgraded.value, context.sections);
|
|
1051
|
-
if (!parsed.success) return { issues: fieldIssues(parsed.error) };
|
|
1052
|
-
const page = parsed.data;
|
|
1053
|
-
const target = page.slug;
|
|
1054
|
-
const missing = await missingAssets(context, page);
|
|
1055
|
-
if (missing.length > 0) return { issues: missing };
|
|
1056
|
-
const loaded = await loadStoredPages(context);
|
|
1057
|
-
if (loaded.response) return { response: loaded.response };
|
|
1058
|
-
const found = loaded.pages.find((entry) => entry.page.slug === from);
|
|
1059
|
-
if (!found) return { response: problem(404, "not_found", `No page with slug "${from}".`) };
|
|
1060
|
-
const stored = new Set(found.page.sections.filter((section) => isOrphanSection(context.sections, section)).map(orphanKey));
|
|
1061
|
-
const added = page.sections.flatMap((section, index) => isOrphanSection(context.sections, section) && !stored.has(orphanKey(section)) ? [{
|
|
1062
|
-
path: `sections.${index}.type`,
|
|
1063
|
-
message: `Unknown section type "${section.type}". Expected one of: ${Object.keys(context.sections).join(", ")}.`
|
|
1064
|
-
}] : []);
|
|
1065
|
-
if (added.length > 0) return { issues: added };
|
|
1066
|
-
const after = async () => {
|
|
1067
|
-
await ensureBaseline(context, "page", target, found.page);
|
|
1068
|
-
await writeHistory(context, "page", target, page);
|
|
1069
|
-
};
|
|
1070
|
-
if (target === from) return {
|
|
1071
|
-
page,
|
|
1072
|
-
writes: [[found.key, page]],
|
|
1073
|
-
removals: [],
|
|
1074
|
-
after
|
|
1075
|
-
};
|
|
1076
|
-
if (!context.pageRules.rename) return { response: locked("rename") };
|
|
1077
|
-
if (from === "index") return { response: problem(409, "conflict", "The home page slug stays index. Set another page as home to move it.") };
|
|
1078
|
-
if (isSystemPage(from) || isSystemPage(target)) return { response: problem(409, "reserved_slug", "System pages cannot be renamed, and no page can take their slug.") };
|
|
1079
|
-
if (target !== "index") {
|
|
1080
|
-
if (loaded.pages.some((entry) => entry.page.slug === target)) return { response: problem(409, "conflict", `A page with slug "${target}" already exists.`) };
|
|
1081
|
-
const nextKey = pageKey(target);
|
|
1082
|
-
if (await context.store.exists(nextKey)) return { response: problem(409, "conflict", `A file named ${target}.json already exists.`) };
|
|
1083
|
-
return {
|
|
1084
|
-
page,
|
|
1085
|
-
writes: [[nextKey, page]],
|
|
1086
|
-
removals: [found.key],
|
|
1087
|
-
after
|
|
1088
|
-
};
|
|
1089
|
-
}
|
|
1090
|
-
const indexKey = pageKey("index");
|
|
1091
|
-
const home = loaded.pages.find((entry) => entry.page.slug === "index");
|
|
1092
|
-
if (!home) {
|
|
1093
|
-
if (await context.store.exists(indexKey)) return { response: problem(409, "conflict", "A file named index.json already exists.") };
|
|
1094
|
-
return {
|
|
1095
|
-
page,
|
|
1096
|
-
writes: [[indexKey, page]],
|
|
1097
|
-
removals: [found.key],
|
|
1098
|
-
after
|
|
1099
|
-
};
|
|
1100
|
-
}
|
|
1101
|
-
const previousSlug = input.previousHomeSlug === void 0 ? null : readSlug(input.previousHomeSlug);
|
|
1102
|
-
if (previousSlug === null || previousSlug === "index" || isSystemPage(previousSlug)) return { response: problem(400, "invalid_slug", "previousHomeSlug is required to move the current home page.") };
|
|
1103
|
-
if (loaded.pages.some((entry) => entry.page.slug === previousSlug)) return { response: problem(409, "conflict", `A page with slug "${previousSlug}" already exists.`) };
|
|
1104
|
-
const previousKey = pageKey(previousSlug);
|
|
1105
|
-
if (await context.store.exists(previousKey)) return { response: problem(409, "conflict", `A file named ${previousSlug}.json already exists.`) };
|
|
1106
|
-
const moved = validateEditorPage({
|
|
1107
|
-
...home.page,
|
|
1108
|
-
slug: previousSlug
|
|
1109
|
-
}, context.sections);
|
|
1110
|
-
if (!moved.success) return { issues: fieldIssues(moved.error) };
|
|
437
|
+
/** Commit changes on the local git work tree of the project. */
|
|
438
|
+
function fileGit(context) {
|
|
1111
439
|
return {
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
removals: [...home.key === indexKey ? [] : [home.key], found.key],
|
|
1115
|
-
after
|
|
440
|
+
info: () => gitInfo(context),
|
|
441
|
+
commit: (message, paths) => commitChanges(context, message, paths)
|
|
1116
442
|
};
|
|
1117
443
|
}
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
paths: z.array(z.string().min(1).max(512)).max(500).optional()
|
|
1121
|
-
}).strict();
|
|
1122
|
-
async function getGit(context) {
|
|
1123
|
-
return json(200, await gitInfo(context));
|
|
1124
|
-
}
|
|
1125
|
-
async function postCommit(request, context) {
|
|
1126
|
-
const body = await readJsonBody(request);
|
|
1127
|
-
if (body.response) return body.response;
|
|
1128
|
-
const parsed = commitSchema.safeParse(body.value);
|
|
1129
|
-
if (!parsed.success) return validation(fieldIssues(parsed.error));
|
|
1130
|
-
try {
|
|
1131
|
-
return json(201, await commitChanges(context, parsed.data.message, parsed.data.paths));
|
|
1132
|
-
} catch (error) {
|
|
1133
|
-
if (!(error instanceof GitError)) throw error;
|
|
1134
|
-
return problem(error.code === "failed" ? 500 : error.code === "invalid" ? 400 : 409, `git_${error.code}`, error.message);
|
|
1135
|
-
}
|
|
1136
|
-
}
|
|
1137
|
-
async function getHistory(context, scope, slug, id) {
|
|
1138
|
-
if (id === void 0) return json(200, { entries: await listHistory(context, scope, slug) });
|
|
1139
|
-
if (!isHistoryId(id)) return problem(400, "invalid_id", "Not a history id.");
|
|
1140
|
-
const snapshot = await readHistory(context, scope, slug, id);
|
|
1141
|
-
if (snapshot === null) return problem(404, "not_found", "No saved version with that id.");
|
|
1142
|
-
return json(200, snapshot);
|
|
1143
|
-
}
|
|
1144
|
-
async function getPages(context) {
|
|
1145
|
-
const loaded = await loadStoredPages(context);
|
|
1146
|
-
if (loaded.response) return loaded.response;
|
|
1147
|
-
return json(200, { pages: loaded.pages.map((entry) => ({
|
|
1148
|
-
slug: entry.page.slug,
|
|
1149
|
-
title: entry.page.title,
|
|
1150
|
-
file: entry.fileName,
|
|
1151
|
-
system: isSystemPage(entry.page.slug),
|
|
1152
|
-
anchors: entry.page.sections.flatMap((section) => "anchor" in section && typeof section.anchor === "string" && section.anchor !== "" ? [section.anchor] : [])
|
|
1153
|
-
})) });
|
|
1154
|
-
}
|
|
1155
|
-
async function getPage(context, slug) {
|
|
1156
|
-
const loaded = await loadStoredPages(context);
|
|
1157
|
-
if (loaded.response) return loaded.response;
|
|
1158
|
-
const found = loaded.pages.find((entry) => entry.page.slug === slug);
|
|
1159
|
-
if (!found) return problem(404, "not_found", `No page with slug "${slug}".`);
|
|
1160
|
-
return json(200, found.page);
|
|
1161
|
-
}
|
|
1162
|
-
async function putPage(request, context, slug) {
|
|
1163
|
-
const body = await readJsonBody(request);
|
|
1164
|
-
if (body.response) return body.response;
|
|
1165
|
-
const parsed = validateEditorPage(body.value, context.sections);
|
|
1166
|
-
if (!parsed.success) return validation(fieldIssues(parsed.error));
|
|
1167
|
-
const page = parsed.data;
|
|
1168
|
-
if (page.slug !== slug) return problem(400, "slug_mismatch", `Slug in the body must be "${slug}". Rename the page with POST /pages/${slug}/rename.`);
|
|
1169
|
-
const missing = await missingAssets(context, page);
|
|
1170
|
-
if (missing.length > 0) return validation(missing);
|
|
1171
|
-
const loaded = await loadStoredPages(context);
|
|
1172
|
-
if (loaded.response) return loaded.response;
|
|
1173
|
-
const found = loaded.pages.find((entry) => entry.page.slug === slug);
|
|
1174
|
-
if (!found) return problem(404, "not_found", `No page with slug "${slug}".`);
|
|
1175
|
-
const stored = new Set(found.page.sections.filter((section) => isOrphanSection(context.sections, section)).map(orphanKey));
|
|
1176
|
-
const added = page.sections.flatMap((section, index) => isOrphanSection(context.sections, section) && !stored.has(orphanKey(section)) ? [{
|
|
1177
|
-
path: `sections.${index}.type`,
|
|
1178
|
-
message: `Unknown section type "${section.type}". Expected one of: ${Object.keys(context.sections).join(", ")}.`
|
|
1179
|
-
}] : []);
|
|
1180
|
-
if (added.length > 0) return validation(added);
|
|
1181
|
-
await ensureBaseline(context, "page", slug, found.page);
|
|
1182
|
-
await writeDocuments(context, [[found.key, page]]);
|
|
1183
|
-
await writeHistory(context, "page", slug, page);
|
|
1184
|
-
return json(200, page);
|
|
1185
|
-
}
|
|
1186
|
-
const orphanKey = (section) => `${section.id}:${section.type}`;
|
|
1187
|
-
async function createPage(request, context) {
|
|
1188
|
-
const body = await readJsonBody(request);
|
|
1189
|
-
if (body.response) return body.response;
|
|
1190
|
-
const parsed = createPageSchema.safeParse(body.value);
|
|
1191
|
-
if (!parsed.success) return validation(fieldIssues(parsed.error));
|
|
1192
|
-
if (isSystemPage(parsed.data.slug)) return problem(409, "reserved_slug", `"${parsed.data.slug}" is a system page and cannot be created.`);
|
|
1193
|
-
const loaded = await loadStoredPages(context, { allowMissing: true });
|
|
1194
|
-
if (loaded.response) return loaded.response;
|
|
1195
|
-
if (loaded.pages.some((entry) => entry.page.slug === parsed.data.slug)) return problem(409, "conflict", `A page with slug "${parsed.data.slug}" already exists.`);
|
|
1196
|
-
const key = pageKey(parsed.data.slug);
|
|
1197
|
-
if (await context.store.exists(key)) return problem(409, "conflict", `A file named ${parsed.data.slug}.json already exists.`);
|
|
1198
|
-
const drafted = draftPage(parsed.data, loaded.pages, context.sections);
|
|
1199
|
-
if (drafted.response) return drafted.response;
|
|
1200
|
-
const validated = validatePage(drafted.page, context.sections);
|
|
1201
|
-
if (!validated.success) return validation(fieldIssues(validated.error));
|
|
1202
|
-
await writeDocuments(context, [[key, validated.data]]);
|
|
1203
|
-
return json(201, validated.data);
|
|
1204
|
-
}
|
|
1205
|
-
function locked(operation) {
|
|
1206
|
-
return problem(409, "operation_locked", `${operation === "rename" ? "Renaming pages" : "Deleting pages"} is turned off for this site (pages.${operation} in the bearminion() options).`);
|
|
1207
|
-
}
|
|
1208
|
-
async function deletePage(context, slug) {
|
|
1209
|
-
if (!context.pageRules.delete) return locked("delete");
|
|
1210
|
-
if (slug === "index") return problem(409, "conflict", "Refusing to delete the index page.");
|
|
1211
|
-
if (isSystemPage(slug)) return problem(409, "reserved_slug", `"${slug}" is a system page and cannot be deleted.`);
|
|
1212
|
-
const loaded = await loadStoredPages(context);
|
|
1213
|
-
if (loaded.response) return loaded.response;
|
|
1214
|
-
const found = loaded.pages.find((entry) => entry.page.slug === slug);
|
|
1215
|
-
if (!found) return problem(404, "not_found", `No page with slug "${slug}".`);
|
|
1216
|
-
await writeDocuments(context, [], [found.key]);
|
|
1217
|
-
return json(200, {
|
|
1218
|
-
deleted: true,
|
|
1219
|
-
slug
|
|
1220
|
-
});
|
|
1221
|
-
}
|
|
444
|
+
//#endregion
|
|
445
|
+
//#region src/history.ts
|
|
1222
446
|
/**
|
|
1223
|
-
*
|
|
1224
|
-
* site
|
|
447
|
+
* Local copies of what was saved, in `<project>/.editor/history/`, so an earlier version of a page or of the
|
|
448
|
+
* site can be loaded back into the draft. Dev-only and untracked: the folder belongs in `.gitignore`.
|
|
1225
449
|
*/
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
const parsed = setHomeSchema.safeParse(body.value);
|
|
1230
|
-
if (!parsed.success) return validation(fieldIssues(parsed.error));
|
|
1231
|
-
if (!context.pageRules.rename) return locked("rename");
|
|
1232
|
-
if (slug === "index") return problem(409, "conflict", "That page is already the home page.");
|
|
1233
|
-
if (isSystemPage(slug)) return problem(409, "reserved_slug", `"${slug}" is a system page and cannot be the home page.`);
|
|
1234
|
-
const loaded = await loadStoredPages(context);
|
|
1235
|
-
if (loaded.response) return loaded.response;
|
|
1236
|
-
const target = loaded.pages.find((entry) => entry.page.slug === slug);
|
|
1237
|
-
if (!target) return problem(404, "not_found", `No page with slug "${slug}".`);
|
|
1238
|
-
const previous = loaded.pages.find((entry) => entry.page.slug === "index");
|
|
1239
|
-
const indexKey = pageKey("index");
|
|
1240
|
-
if (previous) {
|
|
1241
|
-
const previousSlug = parsed.data.previousSlug;
|
|
1242
|
-
if (previousSlug === void 0 || previousSlug === "index") return problem(400, "invalid_slug", "previousSlug is required to move the current home page.");
|
|
1243
|
-
if (loaded.pages.some((entry) => entry.page.slug === previousSlug)) return problem(409, "conflict", `A page with slug "${previousSlug}" already exists.`);
|
|
1244
|
-
const previousKey = pageKey(previousSlug);
|
|
1245
|
-
if (await context.store.exists(previousKey)) return problem(409, "conflict", `A file named ${previousSlug}.json already exists.`);
|
|
1246
|
-
const moved = validateEditorPage({
|
|
1247
|
-
...previous.page,
|
|
1248
|
-
slug: previousSlug
|
|
1249
|
-
}, context.sections);
|
|
1250
|
-
if (!moved.success) return validation(fieldIssues(moved.error));
|
|
1251
|
-
const promoted = validateEditorPage({
|
|
1252
|
-
...target.page,
|
|
1253
|
-
slug: "index"
|
|
1254
|
-
}, context.sections);
|
|
1255
|
-
if (!promoted.success) return validation(fieldIssues(promoted.error));
|
|
1256
|
-
await writeDocuments(context, [[previousKey, moved.data], [indexKey, promoted.data]], [...previous.key === indexKey ? [] : [previous.key], target.key]);
|
|
1257
|
-
return json(200, promoted.data);
|
|
1258
|
-
}
|
|
1259
|
-
if (await context.store.exists(indexKey)) return problem(409, "conflict", "A file named index.json already exists.");
|
|
1260
|
-
const promoted = validateEditorPage({
|
|
1261
|
-
...target.page,
|
|
1262
|
-
slug: "index"
|
|
1263
|
-
}, context.sections);
|
|
1264
|
-
if (!promoted.success) return validation(fieldIssues(promoted.error));
|
|
1265
|
-
await writeDocuments(context, [[indexKey, promoted.data]], [target.key]);
|
|
1266
|
-
return json(200, promoted.data);
|
|
1267
|
-
}
|
|
1268
|
-
async function renamePage(request, context, slug) {
|
|
1269
|
-
const body = await readJsonBody(request);
|
|
1270
|
-
if (body.response) return body.response;
|
|
1271
|
-
const parsed = renameSchema.safeParse(body.value);
|
|
1272
|
-
if (!parsed.success) return validation(fieldIssues(parsed.error));
|
|
1273
|
-
const nextSlug = parsed.data.slug;
|
|
1274
|
-
if (!context.pageRules.rename) return locked("rename");
|
|
1275
|
-
if (nextSlug === slug) return problem(400, "invalid_slug", "The new slug is the same as the current slug.");
|
|
1276
|
-
if (slug === "index") return problem(409, "conflict", "Refusing to rename the index page.");
|
|
1277
|
-
if (isSystemPage(slug) || isSystemPage(nextSlug)) return problem(409, "reserved_slug", "System pages cannot be renamed, and no page can take their slug.");
|
|
1278
|
-
const loaded = await loadStoredPages(context);
|
|
1279
|
-
if (loaded.response) return loaded.response;
|
|
1280
|
-
const found = loaded.pages.find((entry) => entry.page.slug === slug);
|
|
1281
|
-
if (!found) return problem(404, "not_found", `No page with slug "${slug}".`);
|
|
1282
|
-
if (loaded.pages.some((entry) => entry.page.slug === nextSlug)) return problem(409, "conflict", `A page with slug "${nextSlug}" already exists.`);
|
|
1283
|
-
const nextKey = pageKey(nextSlug);
|
|
1284
|
-
if (await context.store.exists(nextKey)) return problem(409, "conflict", `A file named ${nextSlug}.json already exists.`);
|
|
1285
|
-
const validated = validateEditorPage({
|
|
1286
|
-
...found.page,
|
|
1287
|
-
slug: nextSlug
|
|
1288
|
-
}, context.sections);
|
|
1289
|
-
if (!validated.success) return validation(fieldIssues(validated.error));
|
|
1290
|
-
await writeDocuments(context, [[nextKey, validated.data]], [found.key]);
|
|
1291
|
-
return json(200, validated.data);
|
|
450
|
+
const HISTORY_DIR = ".editor/history";
|
|
451
|
+
function idToIso(id) {
|
|
452
|
+
return `${id.slice(0, 4)}-${id.slice(4, 6)}-${id.slice(6, 8)}T${id.slice(9, 11)}:${id.slice(11, 13)}:${id.slice(13, 15)}.${id.slice(15, 18)}Z`;
|
|
1292
453
|
}
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
motion: z.boolean().optional()
|
|
1296
|
-
}).strict();
|
|
1297
|
-
async function postPreview(request, context, meta) {
|
|
1298
|
-
if (!meta.renderPreview) return problem(501, "preview_unavailable", "Live preview is only available while astro dev is running.");
|
|
1299
|
-
const body = await readJsonBody(request);
|
|
1300
|
-
if (body.response) return body.response;
|
|
1301
|
-
const payload = previewBodySchema.safeParse(body.value);
|
|
1302
|
-
if (!payload.success) return validation(fieldIssues(payload.error));
|
|
1303
|
-
const parsed = validateEditorPage(payload.data.page, context.sections);
|
|
1304
|
-
if (!parsed.success) return validation(fieldIssues(parsed.error));
|
|
1305
|
-
const renderable = withoutOrphanSections(parsed.data, context.sections);
|
|
1306
|
-
try {
|
|
1307
|
-
return json(200, { html: await meta.renderPreview(renderable, payload.data.motion ?? true) });
|
|
1308
|
-
} catch (error) {
|
|
1309
|
-
if (error instanceof PreviewUnavailableError) return problem(501, "preview_unavailable", error.message);
|
|
1310
|
-
const message = error instanceof Error ? error.message : "Preview failed.";
|
|
1311
|
-
console.error("[bearminion] preview failed", error);
|
|
1312
|
-
return problem(500, "preview_failed", message);
|
|
1313
|
-
}
|
|
454
|
+
function directory(context, scope, slug) {
|
|
455
|
+
return scope === "site" ? path.join(context.root, HISTORY_DIR, "site") : path.join(context.root, HISTORY_DIR, "pages", slug);
|
|
1314
456
|
}
|
|
1315
|
-
|
|
1316
|
-
site: z.unknown(),
|
|
1317
|
-
pathname: z.string().max(2048)
|
|
1318
|
-
}).strict();
|
|
1319
|
-
async function postSitePreview(request, context, meta) {
|
|
1320
|
-
if (!meta.renderSitePreview) return problem(501, "preview_unavailable", "Live site preview is not available in this project.");
|
|
1321
|
-
const body = await readJsonBody(request);
|
|
1322
|
-
if (body.response) return body.response;
|
|
1323
|
-
const payload = sitePreviewBodySchema.safeParse(body.value);
|
|
1324
|
-
if (!payload.success) return validation(fieldIssues(payload.error));
|
|
1325
|
-
const parsed = validateSite(payload.data.site, context.site);
|
|
1326
|
-
if (!parsed.success) return validation(fieldIssues(parsed.error));
|
|
457
|
+
async function ids(dir) {
|
|
1327
458
|
try {
|
|
1328
|
-
return
|
|
1329
|
-
} catch
|
|
1330
|
-
|
|
1331
|
-
const message = error instanceof Error ? error.message : "Preview failed.";
|
|
1332
|
-
console.error("[bearminion] site preview failed", error);
|
|
1333
|
-
return problem(500, "preview_failed", message);
|
|
459
|
+
return (await readdir(dir)).filter((name) => name.endsWith(".json") && isHistoryId(name.slice(0, -5))).map((name) => name.slice(0, -5)).sort();
|
|
460
|
+
} catch {
|
|
461
|
+
return [];
|
|
1334
462
|
}
|
|
1335
463
|
}
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
images: await context.store.uploads.list(),
|
|
1343
|
-
limits
|
|
1344
|
-
});
|
|
464
|
+
/** Newest first. */
|
|
465
|
+
async function listHistory(context, scope, slug = "") {
|
|
466
|
+
return (await ids(directory(context, scope, slug))).reverse().map((id) => ({
|
|
467
|
+
id,
|
|
468
|
+
at: idToIso(id)
|
|
469
|
+
}));
|
|
1345
470
|
}
|
|
1346
|
-
function
|
|
471
|
+
async function readHistory(context, scope, slug, id) {
|
|
472
|
+
if (!isHistoryId(id)) return null;
|
|
1347
473
|
try {
|
|
1348
|
-
return
|
|
474
|
+
return JSON.parse(await readFile(path.join(directory(context, scope, slug), `${id}.json`), "utf8"));
|
|
1349
475
|
} catch {
|
|
1350
|
-
return
|
|
476
|
+
return null;
|
|
1351
477
|
}
|
|
1352
478
|
}
|
|
1353
|
-
/** Image paths that a saved file must not point at, because the file is not there. */
|
|
1354
|
-
async function missingAssets(context, document) {
|
|
1355
|
-
const { store } = context;
|
|
1356
|
-
if (!store.assetExists) return [];
|
|
1357
|
-
return missingAssetIssues(document, (src) => store.assetExists?.(src) ?? Promise.resolve(true));
|
|
1358
|
-
}
|
|
1359
479
|
/**
|
|
1360
|
-
*
|
|
1361
|
-
*
|
|
1362
|
-
* drafts before it asks to delete, and saving a draft that still points at a deleted image fails validation.
|
|
480
|
+
* Keep a copy of `value`. A value equal to the newest copy is skipped, and only the newest {@link HISTORY_KEEP}
|
|
481
|
+
* copies stay. Returns the new entry, or null when nothing was written. Never throws: history must not block a save.
|
|
1363
482
|
*/
|
|
1364
|
-
async function
|
|
1365
|
-
const labels = Object.fromEntries(Object.values(context.sections).map((definition) => [definition.type, definition.label]));
|
|
1366
|
-
const usages = [];
|
|
1367
|
-
const site = await readStoredJson(context, SITE_KEY, "site");
|
|
1368
|
-
for (const ref of assetRefs(site)) if (ref.src === src) usages.push(describeSiteRef(ref));
|
|
1369
|
-
for (const name of await context.store.list("pages") ?? []) {
|
|
1370
|
-
if (!name.endsWith(".json") || name.startsWith(".")) continue;
|
|
1371
|
-
const page = await readStoredJson(context, `${PAGES_DIR}/${name}`, "page");
|
|
1372
|
-
if (typeof page !== "object" || page === null) continue;
|
|
1373
|
-
const title = "title" in page && typeof page.title === "string" ? page.title : name.replace(/\.json$/, "");
|
|
1374
|
-
const sections = "sections" in page && Array.isArray(page.sections) ? page.sections : [];
|
|
1375
|
-
for (const ref of assetRefs(page)) if (ref.src === src) usages.push(describePageRef(ref, {
|
|
1376
|
-
title,
|
|
1377
|
-
sections
|
|
1378
|
-
}, labels));
|
|
1379
|
-
}
|
|
1380
|
-
return usages;
|
|
1381
|
-
}
|
|
1382
|
-
async function removeImage(context, filename) {
|
|
1383
|
-
const image = (await context.store.uploads.list()).find((item) => item.filename === filename);
|
|
1384
|
-
if (!image) return problem(404, "not_found", "No uploaded image has that name.");
|
|
1385
|
-
const usages = await imageUsages(context, image.path);
|
|
1386
|
-
if (usages.length > 0) return json(409, {
|
|
1387
|
-
error: "in_use",
|
|
1388
|
-
message: `${filename} is still used: ${usages.join("; ")}. Choose another image there and save, then delete it.`,
|
|
1389
|
-
usages
|
|
1390
|
-
});
|
|
1391
|
-
if (!await context.store.uploads.remove(filename)) return problem(404, "not_found", "No uploaded image has that name.");
|
|
1392
|
-
return json(200, {
|
|
1393
|
-
deleted: true,
|
|
1394
|
-
filename
|
|
1395
|
-
});
|
|
1396
|
-
}
|
|
1397
|
-
const NO_VIDEOS = "This content store does not take video uploads.";
|
|
1398
|
-
async function getVideos(context) {
|
|
1399
|
-
if (!context.store.videos) return json(200, {
|
|
1400
|
-
videos: [],
|
|
1401
|
-
maxBytes: context.maxVideoBytes
|
|
1402
|
-
});
|
|
1403
|
-
return json(200, {
|
|
1404
|
-
videos: await context.store.videos.list(),
|
|
1405
|
-
maxBytes: context.maxVideoBytes
|
|
1406
|
-
});
|
|
1407
|
-
}
|
|
1408
|
-
/** Every string in a JSON value. */
|
|
1409
|
-
function* strings(value) {
|
|
1410
|
-
if (typeof value === "string") yield value;
|
|
1411
|
-
else if (Array.isArray(value)) for (const item of value) yield* strings(item);
|
|
1412
|
-
else if (typeof value === "object" && value !== null) for (const item of Object.values(value)) yield* strings(item);
|
|
1413
|
-
}
|
|
1414
|
-
/** Where saved content links the video at `url`, named like the image usages: "Home page › Media". */
|
|
1415
|
-
async function videoUsages(context, url) {
|
|
1416
|
-
const labels = Object.fromEntries(Object.values(context.sections).map((definition) => [definition.type, definition.label]));
|
|
1417
|
-
const usages = [];
|
|
1418
|
-
if ([...strings(await readStoredJson(context, "site.json", "site"))].includes(url)) usages.push("Site settings");
|
|
1419
|
-
for (const name of await context.store.list("pages") ?? []) {
|
|
1420
|
-
if (!name.endsWith(".json") || name.startsWith(".")) continue;
|
|
1421
|
-
const page = await readStoredJson(context, `${PAGES_DIR}/${name}`, "page");
|
|
1422
|
-
if (typeof page !== "object" || page === null) continue;
|
|
1423
|
-
const title = "title" in page && typeof page.title === "string" ? page.title : name.replace(/\.json$/, "");
|
|
1424
|
-
const sections = "sections" in page && Array.isArray(page.sections) ? page.sections : [];
|
|
1425
|
-
for (const section of sections) if ([...strings(section)].includes(url)) usages.push(`${title} › ${labels[section.type ?? ""] ?? section.type ?? "section"}`);
|
|
1426
|
-
}
|
|
1427
|
-
return usages;
|
|
1428
|
-
}
|
|
1429
|
-
async function removeVideo(context, filename) {
|
|
1430
|
-
const videos = context.store.videos;
|
|
1431
|
-
if (!videos) return problem(404, "not_found", NO_VIDEOS);
|
|
1432
|
-
const video = (await videos.list()).find((item) => item.filename === filename);
|
|
1433
|
-
if (!video) return problem(404, "not_found", "No uploaded video has that name.");
|
|
1434
|
-
const usages = await videoUsages(context, video.url);
|
|
1435
|
-
if (usages.length > 0) return json(409, {
|
|
1436
|
-
error: "in_use",
|
|
1437
|
-
message: `${filename} is still used: ${usages.join("; ")}. Choose another video there and save, then delete it.`,
|
|
1438
|
-
usages
|
|
1439
|
-
});
|
|
1440
|
-
if (!await videos.remove(filename)) return problem(404, "not_found", "No uploaded video has that name.");
|
|
1441
|
-
return json(200, {
|
|
1442
|
-
deleted: true,
|
|
1443
|
-
filename
|
|
1444
|
-
});
|
|
1445
|
-
}
|
|
1446
|
-
async function postVideo(request, context) {
|
|
1447
|
-
const videos = context.store.videos;
|
|
1448
|
-
if (!videos) return problem(404, "not_found", NO_VIDEOS);
|
|
1449
|
-
const limitMb = Math.round(context.maxVideoBytes / 1048576);
|
|
1450
|
-
const tooLarge = () => problem(413, "too_large", `Videos must be ${limitMb}MB or smaller. Link a hosted video instead, or compress this one.`);
|
|
1451
|
-
const length = contentLength(request);
|
|
1452
|
-
if (length !== null && length > videoBodyLimit(context.maxVideoBytes)) return tooLarge();
|
|
1453
|
-
if (!(request.headers.get("content-type") ?? "").toLowerCase().includes("multipart/form-data")) return problem(415, "unsupported_media_type", "Upload the video as multipart/form-data.");
|
|
1454
|
-
let form;
|
|
483
|
+
async function writeHistory(context, scope, slug, value, now = /* @__PURE__ */ new Date()) {
|
|
1455
484
|
try {
|
|
1456
|
-
|
|
485
|
+
const dir = directory(context, scope, slug);
|
|
486
|
+
const existing = await ids(dir);
|
|
487
|
+
const newest = existing[existing.length - 1];
|
|
488
|
+
if (newest !== void 0) {
|
|
489
|
+
if (await readFile(path.join(dir, `${newest}.json`), "utf8") === stableStringify(value)) return null;
|
|
490
|
+
}
|
|
491
|
+
let id = historyId(now);
|
|
492
|
+
while (existing.includes(id)) id = historyId(new Date(Date.parse(idToIso(id)) + 1));
|
|
493
|
+
await writeJsonAtomic(path.join(dir, `${id}.json`), value);
|
|
494
|
+
for (const old of [...existing, id].slice(0, -50)) await rm(path.join(dir, `${old}.json`), { force: true });
|
|
495
|
+
return {
|
|
496
|
+
id,
|
|
497
|
+
at: idToIso(id)
|
|
498
|
+
};
|
|
1457
499
|
} catch {
|
|
1458
|
-
return
|
|
1459
|
-
}
|
|
1460
|
-
const entry = form.get("file");
|
|
1461
|
-
if (!(entry instanceof File)) return problem(400, "invalid_upload", "Expected a multipart file field named \"file\".");
|
|
1462
|
-
if (entry.size > context.maxVideoBytes) return tooLarge();
|
|
1463
|
-
const bytes = new Uint8Array(await entry.arrayBuffer());
|
|
1464
|
-
if (bytes.byteLength > context.maxVideoBytes) return tooLarge();
|
|
1465
|
-
const declared = videoKindFromMime(entry.type);
|
|
1466
|
-
const sniffed = sniffVideo(bytes);
|
|
1467
|
-
if (declared === null || sniffed === null || declared !== sniffed) return problem(415, "unsupported_media_type", "Upload an mp4, webm, mov or ogv video whose contents match the declared type.");
|
|
1468
|
-
try {
|
|
1469
|
-
return json(201, await videos.save({
|
|
1470
|
-
originalName: entry.name,
|
|
1471
|
-
bytes,
|
|
1472
|
-
kind: sniffed
|
|
1473
|
-
}));
|
|
1474
|
-
} catch (error) {
|
|
1475
|
-
return problem(500, "write_failed", error instanceof Error ? error.message : "Upload failed.");
|
|
500
|
+
return null;
|
|
1476
501
|
}
|
|
1477
502
|
}
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
if (!(request.headers.get("content-type") ?? "").toLowerCase().includes("multipart/form-data")) return problem(415, "unsupported_media_type", "Upload the image as multipart/form-data.");
|
|
1483
|
-
let form;
|
|
1484
|
-
try {
|
|
1485
|
-
form = await request.formData();
|
|
1486
|
-
} catch {
|
|
1487
|
-
return problem(400, "invalid_upload", "The upload body could not be read.");
|
|
1488
|
-
}
|
|
1489
|
-
const entry = form.get("file");
|
|
1490
|
-
if (!(entry instanceof File)) return problem(400, "invalid_upload", "Expected a multipart file field named \"file\".");
|
|
1491
|
-
if (imageTooLarge(entry.size, context.maxImageBytes)) return tooLarge();
|
|
1492
|
-
const bytes = new Uint8Array(await entry.arrayBuffer());
|
|
1493
|
-
if (imageTooLarge(bytes.byteLength, context.maxImageBytes)) return tooLarge();
|
|
1494
|
-
const declared = kindFromMime(entry.type);
|
|
1495
|
-
const sniffed = sniffImage(bytes);
|
|
1496
|
-
if (declared === null || sniffed === null || declared !== sniffed) return problem(415, "unsupported_media_type", "Upload a png, jpeg, webp, gif, or avif file whose contents match the declared type.");
|
|
1497
|
-
try {
|
|
1498
|
-
return json(201, await context.store.uploads.save({
|
|
1499
|
-
originalName: entry.name,
|
|
1500
|
-
bytes,
|
|
1501
|
-
kind: sniffed
|
|
1502
|
-
}));
|
|
1503
|
-
} catch (error) {
|
|
1504
|
-
if (error instanceof StoreError) throw error;
|
|
1505
|
-
return problem(500, "write_failed", error instanceof Error ? error.message : "Upload failed.");
|
|
1506
|
-
}
|
|
503
|
+
/** Before the first save of a page or the site, keep the file as it was so even that first save can be undone. */
|
|
504
|
+
async function ensureBaseline(context, scope, slug, current) {
|
|
505
|
+
if ((await listHistory(context, scope, slug)).length > 0) return;
|
|
506
|
+
await writeHistory(context, scope, slug, current, /* @__PURE__ */ new Date(Date.now() - 1));
|
|
1507
507
|
}
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
title: z.string(),
|
|
1511
|
-
template: z.string().min(1).optional()
|
|
1512
|
-
}).strict().superRefine((value, ctx) => {
|
|
1513
|
-
if (readSlug(value.slug) === null) ctx.addIssue({
|
|
1514
|
-
code: "custom",
|
|
1515
|
-
message: "Slug must be lowercase kebab-case (the home page uses \"index\")",
|
|
1516
|
-
path: ["slug"]
|
|
1517
|
-
});
|
|
1518
|
-
if (value.title.trim() === "") ctx.addIssue({
|
|
1519
|
-
code: "custom",
|
|
1520
|
-
message: "Title is required",
|
|
1521
|
-
path: ["title"]
|
|
1522
|
-
});
|
|
1523
|
-
});
|
|
1524
|
-
const setHomeSchema = z.object({
|
|
1525
|
-
/** Slug the current home page moves to. Required when a home page exists. */
|
|
1526
|
-
previousSlug: z.string().optional() }).strict().superRefine((value, ctx) => {
|
|
1527
|
-
if (value.previousSlug !== void 0 && readSlug(value.previousSlug) === null) ctx.addIssue({
|
|
1528
|
-
code: "custom",
|
|
1529
|
-
message: "Slug must be lowercase kebab-case",
|
|
1530
|
-
path: ["previousSlug"]
|
|
1531
|
-
});
|
|
1532
|
-
});
|
|
1533
|
-
const renameSchema = z.object({ slug: z.string() }).strict().superRefine((value, ctx) => {
|
|
1534
|
-
if (readSlug(value.slug) === null) ctx.addIssue({
|
|
1535
|
-
code: "custom",
|
|
1536
|
-
message: "Slug must be lowercase kebab-case (the home page uses \"index\")",
|
|
1537
|
-
path: ["slug"]
|
|
1538
|
-
});
|
|
1539
|
-
});
|
|
1540
|
-
function pageFromSection(slug, title, seo, definition) {
|
|
1541
|
-
const section = {
|
|
1542
|
-
id: sectionId(definition.type),
|
|
1543
|
-
type: definition.type,
|
|
1544
|
-
props: structuredClone(definition.defaults)
|
|
1545
|
-
};
|
|
1546
|
-
const variant = definition.options.find((option) => option.name === "variant");
|
|
1547
|
-
const tone = definition.options.find((option) => option.name === "tone");
|
|
1548
|
-
if (variant?.type === "enum") section.variant = variant.default;
|
|
1549
|
-
if (tone?.type === "enum") section.tone = tone.default;
|
|
508
|
+
/** The undo history of the local project, in `.editor/history/`. */
|
|
509
|
+
function fileHistory(context) {
|
|
1550
510
|
return {
|
|
1551
|
-
slug,
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
511
|
+
list: (scope, slug) => listHistory(context, scope, slug),
|
|
512
|
+
read: (scope, slug, id) => readHistory(context, scope, slug, id),
|
|
513
|
+
async write(scope, slug, value) {
|
|
514
|
+
await writeHistory(context, scope, slug, value);
|
|
515
|
+
},
|
|
516
|
+
ensureBaseline: (scope, slug, current) => ensureBaseline(context, scope, slug, current)
|
|
1555
517
|
};
|
|
1556
518
|
}
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
519
|
+
//#endregion
|
|
520
|
+
//#region src/options.ts
|
|
521
|
+
function resolveEditorContext(options, rootInput) {
|
|
522
|
+
if (!options?.sections) throw new Error("bearminion() needs the `sections` option: the site's section definitions.");
|
|
523
|
+
if (!options.site) throw new Error("bearminion() needs the `site` option: the site's header and footer definition from defineSite().");
|
|
524
|
+
const root = asDirectory(rootInput);
|
|
525
|
+
const contentDir = resolveDir(root, options?.contentDir, DEFAULT_CONTENT_DIR);
|
|
526
|
+
const uploadsDir = resolveDir(root, options?.uploadsDir, DEFAULT_UPLOADS_DIR);
|
|
527
|
+
const videosDir = resolveDir(root, options?.videosDir, DEFAULT_VIDEOS_DIR);
|
|
528
|
+
const context = {
|
|
529
|
+
root,
|
|
530
|
+
contentDir,
|
|
531
|
+
uploadsDir,
|
|
532
|
+
videosDir,
|
|
533
|
+
maxVideoBytes: options?.maxVideoBytes ?? 52428800,
|
|
534
|
+
maxImageBytes: resolveMaxImageBytes(options?.maxImageBytes),
|
|
535
|
+
pageRules: resolvePageRules(options?.pages),
|
|
536
|
+
imageConvert: resolveConvert(options?.imageConvert),
|
|
537
|
+
sections: options.sections,
|
|
538
|
+
site: options.site,
|
|
539
|
+
theme: options.theme ?? defaultTheme,
|
|
540
|
+
store: options.store ?? createFileStore({
|
|
541
|
+
root,
|
|
542
|
+
contentDir,
|
|
543
|
+
uploadsDir,
|
|
544
|
+
videosDir
|
|
545
|
+
}),
|
|
546
|
+
migrator: createMigrator(options),
|
|
547
|
+
git: options?.git === true,
|
|
548
|
+
formsDir: resolveFormsConfig(options?.forms, root)?.dir ?? null
|
|
1565
549
|
};
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
const definition = registry[input.template];
|
|
1572
|
-
if (definition) return { page: pageFromSection(slug, input.title, seo, definition) };
|
|
1573
|
-
const source = pages.find((entry) => entry.page.slug === input.template);
|
|
1574
|
-
if (!source) return { response: problem(400, "unknown_template", `Unknown template "${input.template}". Use a section type or an existing page slug.`) };
|
|
1575
|
-
return { page: {
|
|
1576
|
-
slug,
|
|
1577
|
-
title: input.title,
|
|
1578
|
-
seo,
|
|
1579
|
-
sections: structuredClone(source.page.sections)
|
|
1580
|
-
} };
|
|
1581
|
-
}
|
|
1582
|
-
function sectionId(type) {
|
|
1583
|
-
return type.replace(/[^A-Za-z0-9_-]+/g, "") || "section";
|
|
1584
|
-
}
|
|
1585
|
-
async function loadStoredPages(context, options = {}) {
|
|
1586
|
-
let listed;
|
|
1587
|
-
try {
|
|
1588
|
-
listed = await context.store.list(PAGES_DIR);
|
|
1589
|
-
} catch (error) {
|
|
1590
|
-
return { response: contentFailure(error) };
|
|
1591
|
-
}
|
|
1592
|
-
if (listed === void 0) {
|
|
1593
|
-
if (options.allowMissing) return { pages: [] };
|
|
1594
|
-
return { response: problem(404, "not_found", `Pages directory not found: ${PAGES_DIR}`) };
|
|
1595
|
-
}
|
|
1596
|
-
const names = listed.filter((name) => name.endsWith(".json") && !name.startsWith("."));
|
|
1597
|
-
const pages = [];
|
|
1598
|
-
const seen = /* @__PURE__ */ new Map();
|
|
1599
|
-
for (const name of names) {
|
|
1600
|
-
const key = `${PAGES_DIR}/${name}`;
|
|
1601
|
-
let raw;
|
|
1602
|
-
try {
|
|
1603
|
-
raw = JSON.parse(await context.store.read(key) ?? "");
|
|
1604
|
-
} catch (error) {
|
|
1605
|
-
if (error instanceof StoreError) throw error;
|
|
1606
|
-
if (error instanceof StoreKeyError) return { response: problem(400, "invalid_path", `Refusing to read ${name}.`) };
|
|
1607
|
-
return { response: problem(400, "invalid_json", `Invalid JSON in ${name}: ${error instanceof Error ? error.message : String(error)}`) };
|
|
1608
|
-
}
|
|
1609
|
-
const upgraded = context.migrator.upgrade(raw, "page");
|
|
1610
|
-
if (!upgraded.ok) return { response: json(422, {
|
|
1611
|
-
error: "validation",
|
|
1612
|
-
message: `Invalid content in ${name}.`,
|
|
1613
|
-
issues: [{
|
|
1614
|
-
path: SCHEMA_VERSION_KEY,
|
|
1615
|
-
message: upgraded.message
|
|
1616
|
-
}]
|
|
1617
|
-
}) };
|
|
1618
|
-
const parsed = validateEditorPage(upgraded.value, context.sections);
|
|
1619
|
-
if (!parsed.success) return { response: json(422, {
|
|
1620
|
-
error: "validation",
|
|
1621
|
-
message: `Invalid content in ${name}.`,
|
|
1622
|
-
issues: fieldIssues(parsed.error)
|
|
1623
|
-
}) };
|
|
1624
|
-
const page = parsed.data;
|
|
1625
|
-
const previous = seen.get(page.slug);
|
|
1626
|
-
if (previous !== void 0) return { response: problem(409, "conflict", `Duplicate slug "${page.slug}" in ${name} (also defined in ${previous}).`) };
|
|
1627
|
-
seen.set(page.slug, name);
|
|
1628
|
-
pages.push({
|
|
1629
|
-
key,
|
|
1630
|
-
fileName: name,
|
|
1631
|
-
page
|
|
1632
|
-
});
|
|
1633
|
-
}
|
|
1634
|
-
return { pages };
|
|
1635
|
-
}
|
|
1636
|
-
async function readSite(context) {
|
|
1637
|
-
const raw = await context.store.read(SITE_KEY);
|
|
1638
|
-
if (raw === void 0) throw new ContentReadError(SITE_KEY, `Content file not found: ${SITE_KEY}`);
|
|
1639
|
-
let parsed;
|
|
1640
|
-
try {
|
|
1641
|
-
parsed = JSON.parse(raw);
|
|
1642
|
-
} catch (error) {
|
|
1643
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
1644
|
-
throw new ContentReadError(SITE_KEY, `Invalid JSON in ${SITE_KEY}: ${message}`);
|
|
1645
|
-
}
|
|
1646
|
-
const upgraded = context.migrator.upgrade(parsed, "site");
|
|
1647
|
-
if (!upgraded.ok) throw new ContentValidationError(SITE_KEY, [{
|
|
1648
|
-
path: [SCHEMA_VERSION_KEY],
|
|
1649
|
-
message: upgraded.message
|
|
1650
|
-
}]);
|
|
1651
|
-
const result = validateSite(upgraded.value, context.site);
|
|
1652
|
-
if (!result.success) {
|
|
1653
|
-
const issues = result.error.issues.map((issue) => ({
|
|
1654
|
-
path: [...issue.path],
|
|
1655
|
-
message: issue.message
|
|
1656
|
-
}));
|
|
1657
|
-
throw new ContentValidationError(SITE_KEY, issues);
|
|
1658
|
-
}
|
|
1659
|
-
return result.data;
|
|
1660
|
-
}
|
|
1661
|
-
async function readJsonBody(request) {
|
|
1662
|
-
const length = contentLength(request);
|
|
1663
|
-
if (length !== null && length > 1048576) return { response: problem(413, "too_large", "JSON body exceeds 1MB.") };
|
|
1664
|
-
if ((request.headers.get("content-type") ?? "").toLowerCase().includes("multipart/form-data")) return { response: problem(415, "unsupported_media_type", "This route expects a JSON body.") };
|
|
1665
|
-
let text;
|
|
1666
|
-
try {
|
|
1667
|
-
text = await request.text();
|
|
1668
|
-
} catch {
|
|
1669
|
-
return { response: problem(400, "invalid_json", "The request body could not be read.") };
|
|
1670
|
-
}
|
|
1671
|
-
if (Buffer.byteLength(text) > 1048576) return { response: problem(413, "too_large", "JSON body exceeds 1MB.") };
|
|
1672
|
-
try {
|
|
1673
|
-
return { value: JSON.parse(text) };
|
|
1674
|
-
} catch {
|
|
1675
|
-
return { response: problem(400, "invalid_json", "Request body is not valid JSON.") };
|
|
1676
|
-
}
|
|
1677
|
-
}
|
|
1678
|
-
function contentLength(request) {
|
|
1679
|
-
const header = request.headers.get("content-length");
|
|
1680
|
-
if (header === null || header === "") return null;
|
|
1681
|
-
const value = Number(header);
|
|
1682
|
-
if (!Number.isFinite(value) || value < 0) return null;
|
|
1683
|
-
return value;
|
|
1684
|
-
}
|
|
1685
|
-
function contentFailure(error) {
|
|
1686
|
-
if (error instanceof StoreError) throw error;
|
|
1687
|
-
if (error instanceof ContentValidationError) return json(422, {
|
|
1688
|
-
error: "validation",
|
|
1689
|
-
message: error.message,
|
|
1690
|
-
issues: error.issues.map((issue) => ({
|
|
1691
|
-
path: issue.path.length > 0 ? issue.path.map((part) => String(part)).join(".") : "(root)",
|
|
1692
|
-
message: issue.message
|
|
1693
|
-
}))
|
|
1694
|
-
});
|
|
1695
|
-
if (error instanceof ContentReadError) {
|
|
1696
|
-
const missing = /not found/i.test(error.message);
|
|
1697
|
-
return problem(missing ? 404 : 400, missing ? "not_found" : "invalid_json", error.message);
|
|
1698
|
-
}
|
|
1699
|
-
return problem(500, "write_failed", error instanceof Error ? error.message : "Unexpected error.");
|
|
1700
|
-
}
|
|
1701
|
-
/** Name the document an issue belongs to, for the save route that validates a page and the site together. */
|
|
1702
|
-
function tagIssues(issues, file) {
|
|
1703
|
-
return issues.map((issue) => ({
|
|
1704
|
-
...issue,
|
|
1705
|
-
file
|
|
1706
|
-
}));
|
|
1707
|
-
}
|
|
1708
|
-
function validation(issues) {
|
|
1709
|
-
return json(400, {
|
|
1710
|
-
error: "validation",
|
|
1711
|
-
message: "The document failed schema validation.",
|
|
1712
|
-
issues
|
|
1713
|
-
});
|
|
1714
|
-
}
|
|
1715
|
-
function badSlug() {
|
|
1716
|
-
return problem(400, "invalid_slug", "Slug must be lowercase kebab-case and must not contain a path.");
|
|
1717
|
-
}
|
|
1718
|
-
function methodNotAllowed(allow) {
|
|
1719
|
-
return json(405, {
|
|
1720
|
-
error: "method_not_allowed",
|
|
1721
|
-
message: `Allowed: ${allow.join(", ")}.`
|
|
1722
|
-
}, { allow: allow.join(", ") });
|
|
1723
|
-
}
|
|
1724
|
-
function problem(status, error, message) {
|
|
1725
|
-
return json(status, {
|
|
1726
|
-
error,
|
|
1727
|
-
message
|
|
1728
|
-
});
|
|
1729
|
-
}
|
|
1730
|
-
function json(status, body, extra) {
|
|
1731
|
-
const headers = new Headers({
|
|
1732
|
-
"content-type": "application/json; charset=utf-8",
|
|
1733
|
-
"cache-control": "no-store",
|
|
1734
|
-
"x-content-type-options": "nosniff"
|
|
1735
|
-
});
|
|
1736
|
-
if (extra) for (const [key, value] of Object.entries(extra)) headers.set(key, value);
|
|
1737
|
-
return new Response(JSON.stringify(body), {
|
|
1738
|
-
status,
|
|
1739
|
-
headers
|
|
1740
|
-
});
|
|
1741
|
-
}
|
|
1742
|
-
function stripTrailingSlash$1(pathname) {
|
|
1743
|
-
if (pathname.length > 1 && pathname.endsWith("/")) return pathname.replace(/\/+$/, "");
|
|
1744
|
-
return pathname;
|
|
550
|
+
context.history = fileHistory(context);
|
|
551
|
+
context.commits = fileGit(context);
|
|
552
|
+
const formsDir = context.formsDir;
|
|
553
|
+
if (formsDir) context.formFile = (name) => formFile(formsDir, name);
|
|
554
|
+
return context;
|
|
1745
555
|
}
|
|
1746
556
|
const ASSET_TYPES = {
|
|
1747
557
|
".png": "image/png",
|
|
@@ -1805,11 +615,12 @@ async function dispatch(req, res, context, rawUrl, hooks) {
|
|
|
1805
615
|
} catch {
|
|
1806
616
|
requestUrl = new URL(rawUrl, "http://127.0.0.1").toString();
|
|
1807
617
|
}
|
|
1808
|
-
|
|
618
|
+
const request = new Request(requestUrl, {
|
|
1809
619
|
method,
|
|
1810
620
|
headers,
|
|
1811
621
|
body: body === void 0 ? void 0 : body
|
|
1812
|
-
})
|
|
622
|
+
});
|
|
623
|
+
await send(res, await handleEditorRequest(request, context, {
|
|
1813
624
|
remoteAddress: req.socket?.remoteAddress ?? null,
|
|
1814
625
|
renderPreview: hooks.renderPreview,
|
|
1815
626
|
renderSitePreview: hooks.renderSitePreview
|
|
@@ -2061,264 +872,6 @@ function rootInput(root) {
|
|
|
2061
872
|
return process.cwd();
|
|
2062
873
|
}
|
|
2063
874
|
//#endregion
|
|
2064
|
-
//#region src/github-store.ts
|
|
2065
|
-
const API_VERSION = "2022-11-28";
|
|
2066
|
-
const RAW = "application/vnd.github.raw+json";
|
|
2067
|
-
const JSON_TYPE = "application/vnd.github+json";
|
|
2068
|
-
/** GitHub's messages for a push that a branch rule refuses. */
|
|
2069
|
-
const PROTECTED = /protected branch|must be made through a pull request|repository rule violation|required status check/i;
|
|
2070
|
-
function folder(value, name) {
|
|
2071
|
-
const parts = value.split("/").filter((part) => part !== "");
|
|
2072
|
-
if (parts.some((part) => part === "." || part === "..")) throw new Error(`githubStore(): ${name} must stay inside the repository, got "${value}".`);
|
|
2073
|
-
return parts.join("/");
|
|
2074
|
-
}
|
|
2075
|
-
const encodePath = (path) => path.split("/").map(encodeURIComponent).join("/");
|
|
2076
|
-
function toBase64(bytes) {
|
|
2077
|
-
let binary = "";
|
|
2078
|
-
for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
|
|
2079
|
-
return btoa(binary);
|
|
2080
|
-
}
|
|
2081
|
-
function messageOf(text) {
|
|
2082
|
-
try {
|
|
2083
|
-
const body = JSON.parse(text);
|
|
2084
|
-
return typeof body.message === "string" ? body.message : "";
|
|
2085
|
-
} catch {
|
|
2086
|
-
return "";
|
|
2087
|
-
}
|
|
2088
|
-
}
|
|
2089
|
-
function defaultMessage({ written, removed }) {
|
|
2090
|
-
if (written.length + removed.length === 1) return written.length === 1 ? `Update ${written[0]}` : `Remove ${removed[0]}`;
|
|
2091
|
-
return `Update ${written.length + removed.length} files`;
|
|
2092
|
-
}
|
|
2093
|
-
function githubStore(options) {
|
|
2094
|
-
const match = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(options.repo);
|
|
2095
|
-
if (!match) throw new Error(`githubStore(): repo must be "owner/name", got "${options.repo}".`);
|
|
2096
|
-
if (typeof options.token !== "string" || options.token === "") throw new Error("githubStore(): token is required. Use a fine-grained token with \"Contents: Read and write\" on this repository.");
|
|
2097
|
-
const repo = `${match[1]}/${match[2]}`;
|
|
2098
|
-
const api = (options.apiUrl ?? "https://api.github.com").replace(/\/+$/, "");
|
|
2099
|
-
const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
|
|
2100
|
-
const rootDir = folder(options.rootDir ?? "", "rootDir");
|
|
2101
|
-
const contentDir = folder(options.contentDir ?? "content", "contentDir");
|
|
2102
|
-
const uploadsDir = folder(options.uploadsDir ?? "src/assets/uploads", "uploadsDir");
|
|
2103
|
-
const message = options.message ?? defaultMessage;
|
|
2104
|
-
const inRepo = (...parts) => [rootDir, ...parts].filter((part) => part !== "").join("/");
|
|
2105
|
-
/** The repository path of a store key, checked the way the file store checks it. */
|
|
2106
|
-
function contentPath(key) {
|
|
2107
|
-
const parts = key.split("/");
|
|
2108
|
-
if (key === "" || parts.some((part) => part === "" || part === "." || part === "..")) throw new StoreKeyError(key);
|
|
2109
|
-
return inRepo(contentDir, key);
|
|
2110
|
-
}
|
|
2111
|
-
async function send(method, route, init = {}) {
|
|
2112
|
-
let response;
|
|
2113
|
-
try {
|
|
2114
|
-
response = await doFetch(`${api}${route}`, {
|
|
2115
|
-
method,
|
|
2116
|
-
headers: {
|
|
2117
|
-
accept: init.accept ?? JSON_TYPE,
|
|
2118
|
-
authorization: `Bearer ${options.token}`,
|
|
2119
|
-
"x-github-api-version": API_VERSION,
|
|
2120
|
-
"user-agent": "bearminion",
|
|
2121
|
-
...init.body === void 0 ? {} : { "content-type": "application/json" },
|
|
2122
|
-
...init.headers
|
|
2123
|
-
},
|
|
2124
|
-
body: init.body === void 0 ? void 0 : JSON.stringify(init.body)
|
|
2125
|
-
});
|
|
2126
|
-
} catch (error) {
|
|
2127
|
-
throw new StoreError(502, "github_unreachable", `Could not reach GitHub: ${error instanceof Error ? error.message : "the request failed"}.`);
|
|
2128
|
-
}
|
|
2129
|
-
return {
|
|
2130
|
-
status: response.status,
|
|
2131
|
-
headers: response.headers,
|
|
2132
|
-
text: await response.text()
|
|
2133
|
-
};
|
|
2134
|
-
}
|
|
2135
|
-
/** What went wrong, in words the person editing can act on. */
|
|
2136
|
-
function failure(reply, action) {
|
|
2137
|
-
const detail = messageOf(reply.text);
|
|
2138
|
-
if (reply.status === 401) return new StoreError(502, "github_auth", "GitHub refused the token. Check that it is valid and has not expired.");
|
|
2139
|
-
if (reply.status === 403 || reply.status === 429) {
|
|
2140
|
-
if (reply.headers.get("x-ratelimit-remaining") === "0" || /rate limit/i.test(detail)) return new StoreError(429, "github_rate_limited", "GitHub is rate limiting this token. Wait a few minutes and try again.");
|
|
2141
|
-
return new StoreError(502, "github_forbidden", `GitHub refused to ${action}. The token needs "Contents: Read and write" on ${repo}.`);
|
|
2142
|
-
}
|
|
2143
|
-
if (reply.status === 404) return new StoreError(502, "github_not_found", `GitHub could not find ${repo} or the branch. Check the name, and that the token can see this repository.`);
|
|
2144
|
-
return new StoreError(502, "github_error", `GitHub could not ${action}: ${detail || `HTTP ${reply.status}`}.`);
|
|
2145
|
-
}
|
|
2146
|
-
async function json(reply, action, ok = [200, 201]) {
|
|
2147
|
-
const settled = await reply;
|
|
2148
|
-
if (!ok.includes(settled.status)) throw failure(settled, action);
|
|
2149
|
-
return JSON.parse(settled.text);
|
|
2150
|
-
}
|
|
2151
|
-
let branchName;
|
|
2152
|
-
function branch() {
|
|
2153
|
-
if (options.branch) return Promise.resolve(options.branch);
|
|
2154
|
-
branchName ??= json(send("GET", `/repos/${repo}`), "read the repository").then((info) => info.default_branch, (error) => {
|
|
2155
|
-
branchName = void 0;
|
|
2156
|
-
throw error;
|
|
2157
|
-
});
|
|
2158
|
-
return branchName;
|
|
2159
|
-
}
|
|
2160
|
-
/** GETs that GitHub can answer with 304 Not Modified, which costs no rate limit. */
|
|
2161
|
-
const cache = /* @__PURE__ */ new Map();
|
|
2162
|
-
async function cached(route, accept) {
|
|
2163
|
-
const key = `${accept} ${route}`;
|
|
2164
|
-
const known = cache.get(key);
|
|
2165
|
-
const reply = await send("GET", route, {
|
|
2166
|
-
accept,
|
|
2167
|
-
headers: known ? { "if-none-match": known.etag } : {}
|
|
2168
|
-
});
|
|
2169
|
-
if (reply.status === 304 && known) return {
|
|
2170
|
-
...reply,
|
|
2171
|
-
status: 200,
|
|
2172
|
-
text: known.text
|
|
2173
|
-
};
|
|
2174
|
-
const etag = reply.headers.get("etag");
|
|
2175
|
-
if (reply.status === 200 && etag) cache.set(key, {
|
|
2176
|
-
etag,
|
|
2177
|
-
text: reply.text
|
|
2178
|
-
});
|
|
2179
|
-
return reply;
|
|
2180
|
-
}
|
|
2181
|
-
const contentsRoute = (path, ref) => `/repos/${repo}/contents/${encodePath(path)}?ref=${encodeURIComponent(ref)}`;
|
|
2182
|
-
async function readFile(path, ref) {
|
|
2183
|
-
const reply = await cached(contentsRoute(path, ref ?? await branch()), RAW);
|
|
2184
|
-
if (reply.status === 404) return void 0;
|
|
2185
|
-
if (reply.status !== 200) throw failure(reply, `read ${path}`);
|
|
2186
|
-
return reply.text;
|
|
2187
|
-
}
|
|
2188
|
-
/** The names of the files directly inside `path`, or `undefined` when there is no such folder. */
|
|
2189
|
-
async function listFiles(path) {
|
|
2190
|
-
const reply = await cached(contentsRoute(path, await branch()), JSON_TYPE);
|
|
2191
|
-
if (reply.status === 404) return void 0;
|
|
2192
|
-
if (reply.status !== 200) throw failure(reply, `list ${path}`);
|
|
2193
|
-
const entries = JSON.parse(reply.text);
|
|
2194
|
-
if (!Array.isArray(entries)) return void 0;
|
|
2195
|
-
return entries.filter((entry) => typeof entry === "object" && entry !== null && "name" in entry).filter((entry) => entry.type === "file").map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
|
|
2196
|
-
}
|
|
2197
|
-
/** One commit on the branch holding all of `changes`. Goes through the Git Data API so the files land together. */
|
|
2198
|
-
async function commit(changes, describe) {
|
|
2199
|
-
const name = await branch();
|
|
2200
|
-
const refRoute = `/repos/${repo}/git/refs/heads/${encodePath(name)}`;
|
|
2201
|
-
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
2202
|
-
const head = await json(send("GET", `/repos/${repo}/git/ref/heads/${encodePath(name)}`), "read the branch");
|
|
2203
|
-
const parent = await json(send("GET", `/repos/${repo}/git/commits/${head.object.sha}`), "read the latest commit");
|
|
2204
|
-
const entries = [];
|
|
2205
|
-
const applied = [];
|
|
2206
|
-
for (const change of changes) if ("remove" in change) {
|
|
2207
|
-
if (await readFile(change.path, head.object.sha) === void 0) continue;
|
|
2208
|
-
entries.push({
|
|
2209
|
-
path: change.path,
|
|
2210
|
-
mode: "100644",
|
|
2211
|
-
type: "blob",
|
|
2212
|
-
sha: null
|
|
2213
|
-
});
|
|
2214
|
-
applied.push(change);
|
|
2215
|
-
} else if ("text" in change) {
|
|
2216
|
-
entries.push({
|
|
2217
|
-
path: change.path,
|
|
2218
|
-
mode: "100644",
|
|
2219
|
-
type: "blob",
|
|
2220
|
-
content: change.text
|
|
2221
|
-
});
|
|
2222
|
-
applied.push(change);
|
|
2223
|
-
} else {
|
|
2224
|
-
const blob = await json(send("POST", `/repos/${repo}/git/blobs`, { body: {
|
|
2225
|
-
content: toBase64(change.bytes),
|
|
2226
|
-
encoding: "base64"
|
|
2227
|
-
} }), `upload ${change.path}`);
|
|
2228
|
-
entries.push({
|
|
2229
|
-
path: change.path,
|
|
2230
|
-
mode: "100644",
|
|
2231
|
-
type: "blob",
|
|
2232
|
-
sha: blob.sha
|
|
2233
|
-
});
|
|
2234
|
-
applied.push(change);
|
|
2235
|
-
}
|
|
2236
|
-
if (entries.length === 0) return;
|
|
2237
|
-
const tree = await json(send("POST", `/repos/${repo}/git/trees`, { body: {
|
|
2238
|
-
base_tree: parent.tree.sha,
|
|
2239
|
-
tree: entries
|
|
2240
|
-
} }), "write the files");
|
|
2241
|
-
const update = await send("PATCH", refRoute, { body: {
|
|
2242
|
-
sha: (await json(send("POST", `/repos/${repo}/git/commits`, { body: {
|
|
2243
|
-
message: describe(applied),
|
|
2244
|
-
tree: tree.sha,
|
|
2245
|
-
parents: [head.object.sha]
|
|
2246
|
-
} }), "create the commit")).sha,
|
|
2247
|
-
force: false
|
|
2248
|
-
} });
|
|
2249
|
-
if (update.status === 200) return;
|
|
2250
|
-
if ((update.status === 403 || update.status === 422) && PROTECTED.test(messageOf(update.text))) throw new StoreError(409, "branch_protected", `The branch "${name}" is protected, so edits cannot be committed to it directly. Allow this token to push to it, or use another branch.`);
|
|
2251
|
-
if (update.status === 422 && attempt === 0) continue;
|
|
2252
|
-
if (update.status === 422) throw new StoreError(409, "branch_moved", "The branch changed while saving. Reload the editor and try again.");
|
|
2253
|
-
throw failure(update, `update the branch "${name}"`);
|
|
2254
|
-
}
|
|
2255
|
-
}
|
|
2256
|
-
return {
|
|
2257
|
-
async read(key) {
|
|
2258
|
-
return readFile(contentPath(key));
|
|
2259
|
-
},
|
|
2260
|
-
async exists(key) {
|
|
2261
|
-
return await readFile(contentPath(key)) !== void 0;
|
|
2262
|
-
},
|
|
2263
|
-
async list(dir) {
|
|
2264
|
-
return listFiles(contentPath(dir));
|
|
2265
|
-
},
|
|
2266
|
-
async apply(operations) {
|
|
2267
|
-
const changes = operations.map((operation) => operation.type === "write" ? {
|
|
2268
|
-
path: contentPath(operation.key),
|
|
2269
|
-
text: operation.text
|
|
2270
|
-
} : {
|
|
2271
|
-
path: contentPath(operation.key),
|
|
2272
|
-
remove: true
|
|
2273
|
-
});
|
|
2274
|
-
if (changes.length === 0) return;
|
|
2275
|
-
await commit(changes, (applied) => message({
|
|
2276
|
-
written: applied.filter((change) => !("remove" in change)).map((change) => change.path),
|
|
2277
|
-
removed: applied.filter((change) => "remove" in change).map((change) => change.path)
|
|
2278
|
-
}));
|
|
2279
|
-
},
|
|
2280
|
-
uploads: {
|
|
2281
|
-
async list() {
|
|
2282
|
-
return (await listFiles(inRepo(uploadsDir)) ?? []).filter((name) => !name.startsWith(".") && hasImageExtension(name)).map((filename) => ({
|
|
2283
|
-
filename,
|
|
2284
|
-
path: `${uploadsDir}/${filename}`
|
|
2285
|
-
}));
|
|
2286
|
-
},
|
|
2287
|
-
async save({ originalName, bytes, kind }) {
|
|
2288
|
-
const taken = new Set(await listFiles(inRepo(uploadsDir)) ?? []);
|
|
2289
|
-
for (let attempt = 0; attempt < 8; attempt += 1) {
|
|
2290
|
-
const filename = uploadFilename(originalName, kind);
|
|
2291
|
-
if (taken.has(filename)) continue;
|
|
2292
|
-
await commit([{
|
|
2293
|
-
path: inRepo(uploadsDir, filename),
|
|
2294
|
-
bytes
|
|
2295
|
-
}], () => `Upload ${filename}`);
|
|
2296
|
-
return {
|
|
2297
|
-
filename,
|
|
2298
|
-
path: `${uploadsDir}/${filename}`,
|
|
2299
|
-
bytes: bytes.byteLength
|
|
2300
|
-
};
|
|
2301
|
-
}
|
|
2302
|
-
throw new Error("Unable to allocate a unique upload filename.");
|
|
2303
|
-
},
|
|
2304
|
-
async remove(filename) {
|
|
2305
|
-
if (!isUploadFilename(filename)) return false;
|
|
2306
|
-
if (!(await listFiles(inRepo(uploadsDir)) ?? []).includes(filename)) return false;
|
|
2307
|
-
await commit([{
|
|
2308
|
-
path: inRepo(uploadsDir, filename),
|
|
2309
|
-
remove: true
|
|
2310
|
-
}], () => `Remove ${filename}`);
|
|
2311
|
-
return true;
|
|
2312
|
-
}
|
|
2313
|
-
},
|
|
2314
|
-
async assetExists(src) {
|
|
2315
|
-
if (!isAssetPath(src)) return false;
|
|
2316
|
-
const slash = src.lastIndexOf("/");
|
|
2317
|
-
return (await listFiles(inRepo(src.slice(0, slash))))?.includes(src.slice(slash + 1)) ?? false;
|
|
2318
|
-
}
|
|
2319
|
-
};
|
|
2320
|
-
}
|
|
2321
|
-
//#endregion
|
|
2322
875
|
//#region src/load.ts
|
|
2323
876
|
/**
|
|
2324
877
|
* Load `site.json` and `pages/*.json` from a content directory.
|
|
@@ -2353,7 +906,7 @@ function loadPages(contentDir, registry, { migrator = createMigrator(), tolerate
|
|
|
2353
906
|
throw new ContentReadError(pagesDir, `Unable to read pages directory ${pagesDir}: ${message}`);
|
|
2354
907
|
}
|
|
2355
908
|
const files = entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
|
|
2356
|
-
const pageSchema = tolerateOrphans ? createTolerantPageSchema(registry) : createPageSchema
|
|
909
|
+
const pageSchema = tolerateOrphans ? createTolerantPageSchema(registry) : createPageSchema(registry);
|
|
2357
910
|
const pages = files.map((name) => parseFile(path.join(pagesDir, name), pageSchema, migrator, "page"));
|
|
2358
911
|
const seen = /* @__PURE__ */ new Map();
|
|
2359
912
|
for (const [index, page] of pages.entries()) {
|