bearminion 1.12.0 → 1.14.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 +64 -2
- package/dist/astro.js +504 -30
- package/dist/index.d.ts +1 -1
- package/dist/{options-WI_ztZTj.d.ts → options-CosfIOMs.d.ts} +10 -6
- package/package.json +1 -1
- package/registry/default/registry.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# bearminion
|
|
2
2
|
|
|
3
|
+
## 1.14.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 5ae0f26: `githubStore` gets `mode: 'pr'`: each edited page gets a branch and a pull request of its own, later saves join it, and nothing is ever merged. Stores can now expose `scoped(scope)` for this, and the editor API uses it per page, site, upload and batch save.
|
|
8
|
+
|
|
9
|
+
## 1.13.0
|
|
10
|
+
|
|
11
|
+
### Minor Changes
|
|
12
|
+
|
|
13
|
+
- d6de040: Add an experimental `githubStore` (`bearminion/astro`): a content store that commits edits to a GitHub repository through the Git Data API. One save is one commit, and uploads are committed as binary files. Store failures now reach the editor as readable errors (`branch_protected`, `github_auth`, `github_rate_limited`, and others) instead of a generic 500.
|
|
14
|
+
|
|
3
15
|
## 1.12.0
|
|
4
16
|
|
|
5
17
|
### Minor Changes
|
package/dist/astro.d.ts
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
import { A as ContentModel, X as SiteOf, Xt as ContentMigrator, Y as SiteDefinition, d as SectionOf, j as SectionRegistry, t as Page } from "./page-CwbIDegI.js";
|
|
2
|
-
import { a as
|
|
2
|
+
import { a as StoreOperation, i as FileStoreOptions, n as EditorContext, o as UploadStore, r as ContentStore, s as createFileStore, t as BearminionOptions } from "./options-CosfIOMs.js";
|
|
3
3
|
import { AstroIntegration } from "astro";
|
|
4
|
+
//#region src/store-error.d.ts
|
|
5
|
+
/** A key that is empty, absolute or leaves the content directory. */
|
|
6
|
+
export declare class StoreKeyError extends Error {
|
|
7
|
+
constructor(key: string);
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* A store that could not do what was asked, for a reason the person editing can act on (a refused token, a protected
|
|
11
|
+
* branch, a branch that moved). The editor API answers it with `status` and `code`, so the message reaches the page
|
|
12
|
+
* instead of becoming a bare 500.
|
|
13
|
+
*/
|
|
14
|
+
export declare class StoreError extends Error {
|
|
15
|
+
readonly status: number;
|
|
16
|
+
readonly code: string;
|
|
17
|
+
constructor(status: number, code: string, message: string);
|
|
18
|
+
}
|
|
19
|
+
//#endregion
|
|
4
20
|
//#region src/integration.d.ts
|
|
5
21
|
interface BearminionIntegration extends AstroIntegration {
|
|
6
22
|
name: 'bearminion';
|
|
@@ -12,6 +28,52 @@ interface BearminionIntegration extends AstroIntegration {
|
|
|
12
28
|
*/
|
|
13
29
|
export declare function bearminion(options: BearminionOptions): BearminionIntegration;
|
|
14
30
|
//#endregion
|
|
31
|
+
//#region src/github-store.d.ts
|
|
32
|
+
interface GithubStoreOptions {
|
|
33
|
+
/** `owner/name`. */
|
|
34
|
+
repo: string;
|
|
35
|
+
/**
|
|
36
|
+
* A token that may write to the repository: a fine-grained personal access token with "Contents: Read and write" on
|
|
37
|
+
* this one repository. Keep it in the environment, never in a file the repository tracks.
|
|
38
|
+
*/
|
|
39
|
+
token: string;
|
|
40
|
+
/** The branch edits are committed to. Default: the repository's default branch. */
|
|
41
|
+
branch?: string;
|
|
42
|
+
/** The folder of the site inside the repository. Default: the repository root. */
|
|
43
|
+
rootDir?: string;
|
|
44
|
+
/** The content folder, relative to `rootDir`. Default `content`. */
|
|
45
|
+
contentDir?: string;
|
|
46
|
+
/** The folder uploaded images go to, relative to `rootDir`. Default `src/assets/uploads`. */
|
|
47
|
+
uploadsDir?: string;
|
|
48
|
+
/** The commit message for a change. Default: `Update pages/about.json`, `Update 3 files`, `Upload photo-1a2b3c4d.jpg`. */
|
|
49
|
+
message?: (change: {
|
|
50
|
+
written: readonly string[];
|
|
51
|
+
removed: readonly string[];
|
|
52
|
+
}) => string;
|
|
53
|
+
/**
|
|
54
|
+
* `direct` (default): a save is a commit on `branch`. `pr`: a save is a commit on a branch of its own for the entry
|
|
55
|
+
* being edited, with a pull request opened on the first save. Nothing here ever merges. Needs "Pull requests: Read
|
|
56
|
+
* and write" besides "Contents: Read and write".
|
|
57
|
+
*/
|
|
58
|
+
mode?: 'direct' | 'pr';
|
|
59
|
+
/** `pr` mode: the title and body of the pull request opened for an entry. */
|
|
60
|
+
pullRequest?: (change: {
|
|
61
|
+
scope: string;
|
|
62
|
+
written: readonly string[];
|
|
63
|
+
removed: readonly string[];
|
|
64
|
+
}) => {
|
|
65
|
+
title: string;
|
|
66
|
+
body: string;
|
|
67
|
+
};
|
|
68
|
+
/** `pr` mode: the label put on the pull requests. Default `bearminion`; `false` for none. */
|
|
69
|
+
label?: string | false;
|
|
70
|
+
/** The GitHub API. Default `https://api.github.com`. Set it for GitHub Enterprise. */
|
|
71
|
+
apiUrl?: string;
|
|
72
|
+
/** Default: the global `fetch`. */
|
|
73
|
+
fetch?: typeof fetch;
|
|
74
|
+
}
|
|
75
|
+
export declare function githubStore(options: GithubStoreOptions): ContentStore;
|
|
76
|
+
//#endregion
|
|
15
77
|
//#region src/load.d.ts
|
|
16
78
|
interface LoadOptions {
|
|
17
79
|
/** Upgrades files written under an older `schemaVersion`. `loadContent` builds it from the model. */
|
|
@@ -40,4 +102,4 @@ export declare function loadSite<TDefinition extends SiteDefinition>(contentDir:
|
|
|
40
102
|
*/
|
|
41
103
|
export declare function loadPages<TRegistry extends SectionRegistry>(contentDir: string, registry: TRegistry, { migrator, tolerateOrphans }?: LoadOptions): Page<SectionOf<TRegistry>>[];
|
|
42
104
|
//#endregion
|
|
43
|
-
export { type BearminionIntegration, type BearminionOptions, type ContentStore, type EditorContext, type FileStoreOptions, type LoadOptions, type LoadedContent,
|
|
105
|
+
export { type BearminionIntegration, type BearminionOptions, type ContentStore, type EditorContext, type FileStoreOptions, type GithubStoreOptions, type LoadOptions, type LoadedContent, type StoreOperation, type UploadStore, bearminion as default, createFileStore };
|
package/dist/astro.js
CHANGED
|
@@ -40,7 +40,7 @@ function editorClientPlugin() {
|
|
|
40
40
|
}
|
|
41
41
|
//#endregion
|
|
42
42
|
//#region src/videos.ts
|
|
43
|
-
const EXTENSION
|
|
43
|
+
const EXTENSION = {
|
|
44
44
|
mp4: ".mp4",
|
|
45
45
|
mov: ".mov",
|
|
46
46
|
webm: ".webm",
|
|
@@ -78,8 +78,8 @@ function publicUrl(root, filePath) {
|
|
|
78
78
|
}
|
|
79
79
|
async function saveVideo(options) {
|
|
80
80
|
await mkdir(options.videosDir, { recursive: true });
|
|
81
|
-
const extension = EXTENSION
|
|
82
|
-
const stem = safeStem
|
|
81
|
+
const extension = EXTENSION[options.kind];
|
|
82
|
+
const stem = safeStem(options.originalName);
|
|
83
83
|
for (let attempt = 0; attempt < 8; attempt += 1) {
|
|
84
84
|
const filename = `${stem}-${randomBytes(4).toString("hex")}${extension}`;
|
|
85
85
|
const filePath = resolveInside(options.videosDir, filename);
|
|
@@ -110,7 +110,7 @@ async function listVideos(root, videosDir) {
|
|
|
110
110
|
const videos = [];
|
|
111
111
|
for (const entry of entries) {
|
|
112
112
|
if (!entry.isFile() || entry.name.startsWith(".")) continue;
|
|
113
|
-
if (!Object.values(EXTENSION
|
|
113
|
+
if (!Object.values(EXTENSION).includes(path.extname(entry.name).toLowerCase())) continue;
|
|
114
114
|
const filePath = resolveInside(videosDir, entry.name);
|
|
115
115
|
if (filePath === null) continue;
|
|
116
116
|
const info = await stat(filePath).catch(() => null);
|
|
@@ -127,7 +127,7 @@ async function listVideos(root, videosDir) {
|
|
|
127
127
|
/** Delete one uploaded video by file name. False when there is no such file or the name is not a plain video file name. */
|
|
128
128
|
async function deleteVideo(videosDir, filename) {
|
|
129
129
|
if (filename !== path.basename(filename) || filename.startsWith(".")) return false;
|
|
130
|
-
if (!Object.values(EXTENSION
|
|
130
|
+
if (!Object.values(EXTENSION).includes(path.extname(filename).toLowerCase())) return false;
|
|
131
131
|
const filePath = resolveInside(videosDir, filename);
|
|
132
132
|
if (filePath === null) return false;
|
|
133
133
|
try {
|
|
@@ -138,7 +138,7 @@ async function deleteVideo(videosDir, filename) {
|
|
|
138
138
|
return false;
|
|
139
139
|
}
|
|
140
140
|
}
|
|
141
|
-
function safeStem
|
|
141
|
+
function safeStem(originalName) {
|
|
142
142
|
return path.win32.basename(path.basename(originalName)).replace(/\.[^.]+$/, "").normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "video";
|
|
143
143
|
}
|
|
144
144
|
function ascii$1(bytes, from, to) {
|
|
@@ -206,14 +206,47 @@ function writeJsonAtomic(filePath, value) {
|
|
|
206
206
|
return writeTextAtomic(filePath, stableStringify(value));
|
|
207
207
|
}
|
|
208
208
|
//#endregion
|
|
209
|
-
//#region src/
|
|
210
|
-
const
|
|
209
|
+
//#region src/upload-names.ts
|
|
210
|
+
const IMAGE_EXTENSION = {
|
|
211
211
|
png: ".png",
|
|
212
212
|
jpeg: ".jpg",
|
|
213
213
|
webp: ".webp",
|
|
214
214
|
gif: ".gif",
|
|
215
215
|
avif: ".avif"
|
|
216
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
|
+
//#region src/images.ts
|
|
217
250
|
const MIME_TO_KIND = {
|
|
218
251
|
"image/png": "png",
|
|
219
252
|
"image/jpeg": "jpeg",
|
|
@@ -236,8 +269,8 @@ function kindFromMime(mime) {
|
|
|
236
269
|
/** Write image bytes under `uploadsDir` using a sniffed extension and a unique name. */
|
|
237
270
|
async function saveImage(options) {
|
|
238
271
|
await mkdir(options.uploadsDir, { recursive: true });
|
|
239
|
-
const extension =
|
|
240
|
-
const stem =
|
|
272
|
+
const extension = IMAGE_EXTENSION[options.kind];
|
|
273
|
+
const stem = uploadStem(options.originalName);
|
|
241
274
|
for (let attempt = 0; attempt < 8; attempt += 1) {
|
|
242
275
|
const filename = `${stem}-${randomBytes(4).toString("hex")}${extension}`;
|
|
243
276
|
const filePath = resolveInside(options.uploadsDir, filename);
|
|
@@ -267,7 +300,7 @@ async function listImages(root, uploadsDir) {
|
|
|
267
300
|
for (const entry of entries) {
|
|
268
301
|
if (!entry.isFile() || entry.name.startsWith(".")) continue;
|
|
269
302
|
const extension = path.extname(entry.name).toLowerCase();
|
|
270
|
-
if (!Object.values(
|
|
303
|
+
if (!Object.values(IMAGE_EXTENSION).includes(extension)) continue;
|
|
271
304
|
const filePath = resolveInside(uploadsDir, entry.name);
|
|
272
305
|
if (filePath === null || !isInside(uploadsDir, filePath)) continue;
|
|
273
306
|
images.push({
|
|
@@ -285,7 +318,7 @@ async function listImages(root, uploadsDir) {
|
|
|
285
318
|
async function deleteImage(uploadsDir, filename) {
|
|
286
319
|
if (filename !== path.basename(filename) || filename.startsWith(".")) return false;
|
|
287
320
|
const extension = path.extname(filename).toLowerCase();
|
|
288
|
-
if (!Object.values(
|
|
321
|
+
if (!Object.values(IMAGE_EXTENSION).includes(extension)) return false;
|
|
289
322
|
const filePath = resolveInside(uploadsDir, filename);
|
|
290
323
|
if (filePath === null || !isInside(uploadsDir, filePath)) return false;
|
|
291
324
|
try {
|
|
@@ -303,9 +336,6 @@ function imageTooLarge(size, maxBytes = IMAGE_BYTE_LIMIT) {
|
|
|
303
336
|
function imageBodyLimit(maxBytes) {
|
|
304
337
|
return maxBytes + 262144;
|
|
305
338
|
}
|
|
306
|
-
function safeStem(originalName) {
|
|
307
|
-
return path.win32.basename(path.basename(originalName)).replace(/\.[^.]+$/, "").normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "image";
|
|
308
|
-
}
|
|
309
339
|
function projectRelative(root, filePath) {
|
|
310
340
|
const relative = path.relative(root, filePath);
|
|
311
341
|
if (!isInside(root, filePath)) throw new Error("Upload path is outside the project root.");
|
|
@@ -336,7 +366,7 @@ function isErrno$2(error) {
|
|
|
336
366
|
return error instanceof Error && "code" in error;
|
|
337
367
|
}
|
|
338
368
|
//#endregion
|
|
339
|
-
//#region src/store.ts
|
|
369
|
+
//#region src/store-error.ts
|
|
340
370
|
/** A key that is empty, absolute or leaves the content directory. */
|
|
341
371
|
var StoreKeyError = class extends Error {
|
|
342
372
|
constructor(key) {
|
|
@@ -344,6 +374,23 @@ var StoreKeyError = class extends Error {
|
|
|
344
374
|
this.name = "StoreKeyError";
|
|
345
375
|
}
|
|
346
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
|
+
//#region src/store.ts
|
|
347
394
|
const SITE_KEY = "site.json";
|
|
348
395
|
const PAGES_DIR = "pages";
|
|
349
396
|
/** The key of the page with this slug. The slug must already be validated (`readSlug`). */
|
|
@@ -703,6 +750,14 @@ async function commitChanges(context, message, paths) {
|
|
|
703
750
|
* so other middleware can continue. Every write is schema-checked first.
|
|
704
751
|
*/
|
|
705
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) {
|
|
706
761
|
const pathname = stripTrailingSlash$1(new URL(request.url).pathname);
|
|
707
762
|
if (pathname !== "/__bearminion/api" && !pathname.startsWith(`/__bearminion/api/`)) return null;
|
|
708
763
|
if (!isLocalRequest(request.headers, meta.remoteAddress)) return problem(403, "forbidden", "The editor API only accepts requests from localhost.");
|
|
@@ -713,12 +768,12 @@ async function handleEditorRequest(request, context, meta = {}) {
|
|
|
713
768
|
return methodNotAllowed(["GET"]);
|
|
714
769
|
}
|
|
715
770
|
if (parts.length === 1 && parts[0] === "site") {
|
|
716
|
-
if (method === "GET") return getSite(context);
|
|
717
|
-
if (method === "PUT") return putSite(request, context);
|
|
771
|
+
if (method === "GET") return getSite(scoped(context, "site"));
|
|
772
|
+
if (method === "PUT") return putSite(request, scoped(context, "site"));
|
|
718
773
|
return methodNotAllowed(["GET", "PUT"]);
|
|
719
774
|
}
|
|
720
775
|
if (parts.length === 1 && parts[0] === "save") {
|
|
721
|
-
if (method === "POST") return postSave(request, context);
|
|
776
|
+
if (method === "POST") return postSave(request, scoped(context, "edits"));
|
|
722
777
|
return methodNotAllowed(["POST"]);
|
|
723
778
|
}
|
|
724
779
|
if (parts.length === 1 && parts[0] === "pages") {
|
|
@@ -739,12 +794,12 @@ async function handleEditorRequest(request, context, meta = {}) {
|
|
|
739
794
|
return methodNotAllowed(["POST"]);
|
|
740
795
|
}
|
|
741
796
|
if (parts.length === 1 && parts[0] === "images") {
|
|
742
|
-
if (method === "GET") return getImages(context);
|
|
743
|
-
if (method === "POST") return postImage(request, context);
|
|
797
|
+
if (method === "GET") return getImages(scoped(context, "uploads"));
|
|
798
|
+
if (method === "POST") return postImage(request, scoped(context, "uploads"));
|
|
744
799
|
return methodNotAllowed(["GET", "POST"]);
|
|
745
800
|
}
|
|
746
801
|
if (parts.length === 2 && parts[0] === "images") {
|
|
747
|
-
if (method === "DELETE") return removeImage(context, decodeSegment(parts[1] ?? ""));
|
|
802
|
+
if (method === "DELETE") return removeImage(scoped(context, "uploads"), decodeSegment(parts[1] ?? ""));
|
|
748
803
|
return methodNotAllowed(["DELETE"]);
|
|
749
804
|
}
|
|
750
805
|
if (parts.length === 1 && parts[0] === "videos") {
|
|
@@ -776,9 +831,10 @@ async function handleEditorRequest(request, context, meta = {}) {
|
|
|
776
831
|
if (parts.length === 2 && parts[0] === "pages") {
|
|
777
832
|
const slug = readSlug(parts[1] ?? "");
|
|
778
833
|
if (slug === null) return badSlug();
|
|
779
|
-
|
|
780
|
-
if (method === "
|
|
781
|
-
if (method === "
|
|
834
|
+
const entry = scoped(context, `page:${slug}`);
|
|
835
|
+
if (method === "GET") return getPage(entry, slug);
|
|
836
|
+
if (method === "PUT") return putPage(request, entry, slug);
|
|
837
|
+
if (method === "DELETE") return deletePage(entry, slug);
|
|
782
838
|
return methodNotAllowed([
|
|
783
839
|
"GET",
|
|
784
840
|
"PUT",
|
|
@@ -788,13 +844,13 @@ async function handleEditorRequest(request, context, meta = {}) {
|
|
|
788
844
|
if (parts.length === 3 && parts[0] === "pages" && parts[2] === "rename") {
|
|
789
845
|
const slug = readSlug(parts[1] ?? "");
|
|
790
846
|
if (slug === null) return badSlug();
|
|
791
|
-
if (method === "POST") return renamePage(request, context, slug);
|
|
847
|
+
if (method === "POST") return renamePage(request, scoped(context, `page:${slug}`), slug);
|
|
792
848
|
return methodNotAllowed(["POST"]);
|
|
793
849
|
}
|
|
794
850
|
if (parts.length === 3 && parts[0] === "pages" && parts[2] === "set-home") {
|
|
795
851
|
const slug = readSlug(parts[1] ?? "");
|
|
796
852
|
if (slug === null) return badSlug();
|
|
797
|
-
if (method === "POST") return setHome(request, context, slug);
|
|
853
|
+
if (method === "POST") return setHome(request, scoped(context, `page:${slug}`), slug);
|
|
798
854
|
return methodNotAllowed(["POST"]);
|
|
799
855
|
}
|
|
800
856
|
return problem(404, "not_found", "Unknown editor API route.");
|
|
@@ -820,6 +876,17 @@ function relativeTo(root, file) {
|
|
|
820
876
|
const prefix = root.endsWith("/") || root.endsWith("\\") ? root : `${root}/`;
|
|
821
877
|
return file.startsWith(prefix) ? file.slice(prefix.length).replaceAll("\\", "/") : file;
|
|
822
878
|
}
|
|
879
|
+
/**
|
|
880
|
+
* The context for editing one entry. A store that keeps each entry's pending edits apart (`githubStore` in `pr` mode)
|
|
881
|
+
* hands out a view of its own; every other store is used as it is.
|
|
882
|
+
*/
|
|
883
|
+
function scoped(context, scope) {
|
|
884
|
+
const store = context.store.scoped?.(scope);
|
|
885
|
+
return store ? {
|
|
886
|
+
...context,
|
|
887
|
+
store
|
|
888
|
+
} : context;
|
|
889
|
+
}
|
|
823
890
|
async function getSchema(context) {
|
|
824
891
|
const sectionDefaults = {};
|
|
825
892
|
const sectionLabels = {};
|
|
@@ -902,7 +969,8 @@ async function readStoredJson(context, key, kind) {
|
|
|
902
969
|
if (text === void 0) return void 0;
|
|
903
970
|
const upgraded = context.migrator.upgrade(JSON.parse(text), kind);
|
|
904
971
|
return upgraded.ok ? upgraded.value : void 0;
|
|
905
|
-
} catch {
|
|
972
|
+
} catch (error) {
|
|
973
|
+
if (error instanceof StoreError) throw error;
|
|
906
974
|
return;
|
|
907
975
|
}
|
|
908
976
|
}
|
|
@@ -1128,11 +1196,12 @@ async function putPage(request, context, slug) {
|
|
|
1128
1196
|
return json(200, page);
|
|
1129
1197
|
}
|
|
1130
1198
|
const orphanKey = (section) => `${section.id}:${section.type}`;
|
|
1131
|
-
async function createPage(request,
|
|
1199
|
+
async function createPage(request, baseContext) {
|
|
1132
1200
|
const body = await readJsonBody(request);
|
|
1133
1201
|
if (body.response) return body.response;
|
|
1134
1202
|
const parsed = createPageSchema.safeParse(body.value);
|
|
1135
1203
|
if (!parsed.success) return validation(fieldIssues(parsed.error));
|
|
1204
|
+
const context = scoped(baseContext, `page:${parsed.data.slug}`);
|
|
1136
1205
|
if (isSystemPage(parsed.data.slug)) return problem(409, "reserved_slug", `"${parsed.data.slug}" is a system page and cannot be created.`);
|
|
1137
1206
|
const loaded = await loadStoredPages(context, { allowMissing: true });
|
|
1138
1207
|
if (loaded.response) return loaded.response;
|
|
@@ -1445,6 +1514,7 @@ async function postImage(request, context) {
|
|
|
1445
1514
|
kind: sniffed
|
|
1446
1515
|
}));
|
|
1447
1516
|
} catch (error) {
|
|
1517
|
+
if (error instanceof StoreError) throw error;
|
|
1448
1518
|
return problem(500, "write_failed", error instanceof Error ? error.message : "Upload failed.");
|
|
1449
1519
|
}
|
|
1450
1520
|
}
|
|
@@ -1545,6 +1615,7 @@ async function loadStoredPages(context, options = {}) {
|
|
|
1545
1615
|
try {
|
|
1546
1616
|
raw = JSON.parse(await context.store.read(key) ?? "");
|
|
1547
1617
|
} catch (error) {
|
|
1618
|
+
if (error instanceof StoreError) throw error;
|
|
1548
1619
|
if (error instanceof StoreKeyError) return { response: problem(400, "invalid_path", `Refusing to read ${name}.`) };
|
|
1549
1620
|
return { response: problem(400, "invalid_json", `Invalid JSON in ${name}: ${error instanceof Error ? error.message : String(error)}`) };
|
|
1550
1621
|
}
|
|
@@ -1625,6 +1696,7 @@ function contentLength(request) {
|
|
|
1625
1696
|
return value;
|
|
1626
1697
|
}
|
|
1627
1698
|
function contentFailure(error) {
|
|
1699
|
+
if (error instanceof StoreError) throw error;
|
|
1628
1700
|
if (error instanceof ContentValidationError) return json(422, {
|
|
1629
1701
|
error: "validation",
|
|
1630
1702
|
message: error.message,
|
|
@@ -2002,6 +2074,408 @@ function rootInput(root) {
|
|
|
2002
2074
|
return process.cwd();
|
|
2003
2075
|
}
|
|
2004
2076
|
//#endregion
|
|
2077
|
+
//#region src/github-store.ts
|
|
2078
|
+
const API_VERSION = "2022-11-28";
|
|
2079
|
+
const RAW = "application/vnd.github.raw+json";
|
|
2080
|
+
const JSON_TYPE = "application/vnd.github+json";
|
|
2081
|
+
/** GitHub's messages for a push that a branch rule refuses. */
|
|
2082
|
+
const PROTECTED = /protected branch|must be made through a pull request|repository rule violation|required status check/i;
|
|
2083
|
+
function folder(value, name) {
|
|
2084
|
+
const parts = value.split("/").filter((part) => part !== "");
|
|
2085
|
+
if (parts.some((part) => part === "." || part === "..")) throw new Error(`githubStore(): ${name} must stay inside the repository, got "${value}".`);
|
|
2086
|
+
return parts.join("/");
|
|
2087
|
+
}
|
|
2088
|
+
const encodePath = (path) => path.split("/").map(encodeURIComponent).join("/");
|
|
2089
|
+
function toBase64(bytes) {
|
|
2090
|
+
let binary = "";
|
|
2091
|
+
for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
|
|
2092
|
+
return btoa(binary);
|
|
2093
|
+
}
|
|
2094
|
+
function messageOf(text) {
|
|
2095
|
+
try {
|
|
2096
|
+
const body = JSON.parse(text);
|
|
2097
|
+
return typeof body.message === "string" ? body.message : "";
|
|
2098
|
+
} catch {
|
|
2099
|
+
return "";
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
function defaultMessage({ written, removed }) {
|
|
2103
|
+
if (written.length + removed.length === 1) return written.length === 1 ? `Update ${written[0]}` : `Remove ${removed[0]}`;
|
|
2104
|
+
return `Update ${written.length + removed.length} files`;
|
|
2105
|
+
}
|
|
2106
|
+
function branchStem(scope) {
|
|
2107
|
+
const part = scope.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
|
|
2108
|
+
return `bearminion/${part === "" ? "edit" : part}`;
|
|
2109
|
+
}
|
|
2110
|
+
const MAX_BRANCHES_PER_SCOPE = 20;
|
|
2111
|
+
function githubStore(options) {
|
|
2112
|
+
const match = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(options.repo);
|
|
2113
|
+
if (!match) throw new Error(`githubStore(): repo must be "owner/name", got "${options.repo}".`);
|
|
2114
|
+
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.");
|
|
2115
|
+
const repo = `${match[1]}/${match[2]}`;
|
|
2116
|
+
const api = (options.apiUrl ?? "https://api.github.com").replace(/\/+$/, "");
|
|
2117
|
+
const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
|
|
2118
|
+
const rootDir = folder(options.rootDir ?? "", "rootDir");
|
|
2119
|
+
const contentDir = folder(options.contentDir ?? "content", "contentDir");
|
|
2120
|
+
const uploadsDir = folder(options.uploadsDir ?? "src/assets/uploads", "uploadsDir");
|
|
2121
|
+
const message = options.message ?? defaultMessage;
|
|
2122
|
+
const prMode = options.mode === "pr";
|
|
2123
|
+
if (options.mode !== void 0 && options.mode !== "direct" && options.mode !== "pr") throw new Error(`githubStore(): mode must be "direct" or "pr", got "${String(options.mode)}".`);
|
|
2124
|
+
const inRepo = (...parts) => [rootDir, ...parts].filter((part) => part !== "").join("/");
|
|
2125
|
+
/** The repository path of a store key, checked the way the file store checks it. */
|
|
2126
|
+
function contentPath(key) {
|
|
2127
|
+
const parts = key.split("/");
|
|
2128
|
+
if (key === "" || parts.some((part) => part === "" || part === "." || part === "..")) throw new StoreKeyError(key);
|
|
2129
|
+
return inRepo(contentDir, key);
|
|
2130
|
+
}
|
|
2131
|
+
async function send(method, route, init = {}) {
|
|
2132
|
+
let response;
|
|
2133
|
+
try {
|
|
2134
|
+
response = await doFetch(`${api}${route}`, {
|
|
2135
|
+
method,
|
|
2136
|
+
headers: {
|
|
2137
|
+
accept: init.accept ?? JSON_TYPE,
|
|
2138
|
+
authorization: `Bearer ${options.token}`,
|
|
2139
|
+
"x-github-api-version": API_VERSION,
|
|
2140
|
+
"user-agent": "bearminion",
|
|
2141
|
+
...init.body === void 0 ? {} : { "content-type": "application/json" },
|
|
2142
|
+
...init.headers
|
|
2143
|
+
},
|
|
2144
|
+
body: init.body === void 0 ? void 0 : JSON.stringify(init.body)
|
|
2145
|
+
});
|
|
2146
|
+
} catch (error) {
|
|
2147
|
+
throw new StoreError(502, "github_unreachable", `Could not reach GitHub: ${error instanceof Error ? error.message : "the request failed"}.`);
|
|
2148
|
+
}
|
|
2149
|
+
return {
|
|
2150
|
+
status: response.status,
|
|
2151
|
+
headers: response.headers,
|
|
2152
|
+
text: await response.text()
|
|
2153
|
+
};
|
|
2154
|
+
}
|
|
2155
|
+
/** What went wrong, in words the person editing can act on. */
|
|
2156
|
+
function failure(reply, action) {
|
|
2157
|
+
const detail = messageOf(reply.text);
|
|
2158
|
+
if (reply.status === 401) return new StoreError(502, "github_auth", "GitHub refused the token. Check that it is valid and has not expired.");
|
|
2159
|
+
if (reply.status === 403 || reply.status === 429) {
|
|
2160
|
+
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.");
|
|
2161
|
+
return new StoreError(502, "github_forbidden", `GitHub refused to ${action}. The token needs "Contents: Read and write" on ${repo}.`);
|
|
2162
|
+
}
|
|
2163
|
+
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.`);
|
|
2164
|
+
return new StoreError(502, "github_error", `GitHub could not ${action}: ${detail || `HTTP ${reply.status}`}.`);
|
|
2165
|
+
}
|
|
2166
|
+
async function json(reply, action, ok = [200, 201]) {
|
|
2167
|
+
const settled = await reply;
|
|
2168
|
+
if (!ok.includes(settled.status)) throw failure(settled, action);
|
|
2169
|
+
return JSON.parse(settled.text);
|
|
2170
|
+
}
|
|
2171
|
+
let branchName;
|
|
2172
|
+
/** The branch edits are based on: the configured one, or the repository's default. */
|
|
2173
|
+
function baseBranch() {
|
|
2174
|
+
if (options.branch) return Promise.resolve(options.branch);
|
|
2175
|
+
branchName ??= json(send("GET", `/repos/${repo}`), "read the repository").then((info) => info.default_branch, (error) => {
|
|
2176
|
+
branchName = void 0;
|
|
2177
|
+
throw error;
|
|
2178
|
+
});
|
|
2179
|
+
return branchName;
|
|
2180
|
+
}
|
|
2181
|
+
/** GETs that GitHub can answer with 304 Not Modified, which costs no rate limit. */
|
|
2182
|
+
const cache = /* @__PURE__ */ new Map();
|
|
2183
|
+
async function cached(route, accept) {
|
|
2184
|
+
const key = `${accept} ${route}`;
|
|
2185
|
+
const known = cache.get(key);
|
|
2186
|
+
const reply = await send("GET", route, {
|
|
2187
|
+
accept,
|
|
2188
|
+
headers: known ? { "if-none-match": known.etag } : {}
|
|
2189
|
+
});
|
|
2190
|
+
if (reply.status === 304 && known) return {
|
|
2191
|
+
...reply,
|
|
2192
|
+
status: 200,
|
|
2193
|
+
text: known.text
|
|
2194
|
+
};
|
|
2195
|
+
const etag = reply.headers.get("etag");
|
|
2196
|
+
if (reply.status === 200 && etag) cache.set(key, {
|
|
2197
|
+
etag,
|
|
2198
|
+
text: reply.text
|
|
2199
|
+
});
|
|
2200
|
+
return reply;
|
|
2201
|
+
}
|
|
2202
|
+
const contentsRoute = (path, ref) => `/repos/${repo}/contents/${encodePath(path)}?ref=${encodeURIComponent(ref)}`;
|
|
2203
|
+
async function readFileAt(path, ref) {
|
|
2204
|
+
const reply = await cached(contentsRoute(path, ref), RAW);
|
|
2205
|
+
if (reply.status === 404) return void 0;
|
|
2206
|
+
if (reply.status !== 200) throw failure(reply, `read ${path}`);
|
|
2207
|
+
return reply.text;
|
|
2208
|
+
}
|
|
2209
|
+
/** The names of the files directly inside `path`, or `undefined` when there is no such folder. */
|
|
2210
|
+
async function listFilesAt(path, ref) {
|
|
2211
|
+
const reply = await cached(contentsRoute(path, ref), JSON_TYPE);
|
|
2212
|
+
if (reply.status === 404) return void 0;
|
|
2213
|
+
if (reply.status !== 200) throw failure(reply, `list ${path}`);
|
|
2214
|
+
const entries = JSON.parse(reply.text);
|
|
2215
|
+
if (!Array.isArray(entries)) return void 0;
|
|
2216
|
+
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));
|
|
2217
|
+
}
|
|
2218
|
+
async function branchHead(name) {
|
|
2219
|
+
const reply = await send("GET", `/repos/${repo}/git/ref/heads/${encodePath(name)}`);
|
|
2220
|
+
if (reply.status === 404) return void 0;
|
|
2221
|
+
if (reply.status !== 200) throw failure(reply, `read the branch "${name}"`);
|
|
2222
|
+
return JSON.parse(reply.text).object.sha;
|
|
2223
|
+
}
|
|
2224
|
+
/** The state of the pull requests whose head is `name`: any open one wins, then closed or merged ones. */
|
|
2225
|
+
async function pullState(name) {
|
|
2226
|
+
const head = encodeURIComponent(`${match?.[1] ?? ""}:${name}`);
|
|
2227
|
+
const pulls = await json(send("GET", `/repos/${repo}/pulls?head=${head}&state=all&per_page=100`), "look up pull requests");
|
|
2228
|
+
if (pulls.some((pull) => pull.state === "open")) return "open";
|
|
2229
|
+
return pulls.length > 0 ? "closed" : "none";
|
|
2230
|
+
}
|
|
2231
|
+
/** One commit on the target's branch holding all of `changes`. Goes through the Git Data API so the files land together. */
|
|
2232
|
+
function view(target) {
|
|
2233
|
+
async function readFile(path) {
|
|
2234
|
+
return readFileAt(path, await target.readRef());
|
|
2235
|
+
}
|
|
2236
|
+
async function listFile(path) {
|
|
2237
|
+
return listFilesAt(path, await target.readRef());
|
|
2238
|
+
}
|
|
2239
|
+
async function listAcross(path) {
|
|
2240
|
+
const names = /* @__PURE__ */ new Set();
|
|
2241
|
+
for (const ref of await target.refs()) for (const name of await listFilesAt(path, ref) ?? []) names.add(name);
|
|
2242
|
+
return [...names].sort((a, b) => a.localeCompare(b));
|
|
2243
|
+
}
|
|
2244
|
+
async function commit(changes, describe) {
|
|
2245
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
2246
|
+
const name = await target.writeBranch();
|
|
2247
|
+
const headSha = await branchHead(name);
|
|
2248
|
+
if (headSha === void 0) throw failure({
|
|
2249
|
+
status: 404,
|
|
2250
|
+
headers: new Headers(),
|
|
2251
|
+
text: ""
|
|
2252
|
+
}, `read the branch "${name}"`);
|
|
2253
|
+
const parent = await json(send("GET", `/repos/${repo}/git/commits/${headSha}`), "read the latest commit");
|
|
2254
|
+
const entries = [];
|
|
2255
|
+
const applied = [];
|
|
2256
|
+
for (const change of changes) if ("remove" in change) {
|
|
2257
|
+
if (await readFileAt(change.path, headSha) === void 0) continue;
|
|
2258
|
+
entries.push({
|
|
2259
|
+
path: change.path,
|
|
2260
|
+
mode: "100644",
|
|
2261
|
+
type: "blob",
|
|
2262
|
+
sha: null
|
|
2263
|
+
});
|
|
2264
|
+
applied.push(change);
|
|
2265
|
+
} else if ("text" in change) {
|
|
2266
|
+
entries.push({
|
|
2267
|
+
path: change.path,
|
|
2268
|
+
mode: "100644",
|
|
2269
|
+
type: "blob",
|
|
2270
|
+
content: change.text
|
|
2271
|
+
});
|
|
2272
|
+
applied.push(change);
|
|
2273
|
+
} else {
|
|
2274
|
+
const blob = await json(send("POST", `/repos/${repo}/git/blobs`, { body: {
|
|
2275
|
+
content: toBase64(change.bytes),
|
|
2276
|
+
encoding: "base64"
|
|
2277
|
+
} }), `upload ${change.path}`);
|
|
2278
|
+
entries.push({
|
|
2279
|
+
path: change.path,
|
|
2280
|
+
mode: "100644",
|
|
2281
|
+
type: "blob",
|
|
2282
|
+
sha: blob.sha
|
|
2283
|
+
});
|
|
2284
|
+
applied.push(change);
|
|
2285
|
+
}
|
|
2286
|
+
if (entries.length === 0) return;
|
|
2287
|
+
const tree = await json(send("POST", `/repos/${repo}/git/trees`, { body: {
|
|
2288
|
+
base_tree: parent.tree.sha,
|
|
2289
|
+
tree: entries
|
|
2290
|
+
} }), "write the files");
|
|
2291
|
+
const created = await json(send("POST", `/repos/${repo}/git/commits`, { body: {
|
|
2292
|
+
message: describe(applied),
|
|
2293
|
+
tree: tree.sha,
|
|
2294
|
+
parents: [headSha]
|
|
2295
|
+
} }), "create the commit");
|
|
2296
|
+
const update = await send("PATCH", `/repos/${repo}/git/refs/heads/${encodePath(name)}`, { body: {
|
|
2297
|
+
sha: created.sha,
|
|
2298
|
+
force: false
|
|
2299
|
+
} });
|
|
2300
|
+
if (update.status === 200) {
|
|
2301
|
+
await target.committed?.(name, {
|
|
2302
|
+
written: applied.filter((change) => !("remove" in change)).map((change) => change.path),
|
|
2303
|
+
removed: applied.filter((change) => "remove" in change).map((change) => change.path)
|
|
2304
|
+
});
|
|
2305
|
+
return;
|
|
2306
|
+
}
|
|
2307
|
+
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, use another branch, or set mode: 'pr'.`);
|
|
2308
|
+
if (update.status === 422 && attempt === 0) continue;
|
|
2309
|
+
if (update.status === 422) throw new StoreError(409, "branch_moved", "The branch changed while saving. Reload the editor and try again.");
|
|
2310
|
+
throw failure(update, `update the branch "${name}"`);
|
|
2311
|
+
}
|
|
2312
|
+
}
|
|
2313
|
+
return {
|
|
2314
|
+
async read(key) {
|
|
2315
|
+
return readFile(contentPath(key));
|
|
2316
|
+
},
|
|
2317
|
+
async exists(key) {
|
|
2318
|
+
return await readFile(contentPath(key)) !== void 0;
|
|
2319
|
+
},
|
|
2320
|
+
async list(dir) {
|
|
2321
|
+
return listFile(contentPath(dir));
|
|
2322
|
+
},
|
|
2323
|
+
async apply(operations) {
|
|
2324
|
+
const changes = operations.map((operation) => operation.type === "write" ? {
|
|
2325
|
+
path: contentPath(operation.key),
|
|
2326
|
+
text: operation.text
|
|
2327
|
+
} : {
|
|
2328
|
+
path: contentPath(operation.key),
|
|
2329
|
+
remove: true
|
|
2330
|
+
});
|
|
2331
|
+
if (changes.length === 0) return;
|
|
2332
|
+
await commit(changes, (applied) => message({
|
|
2333
|
+
written: applied.filter((change) => !("remove" in change)).map((change) => change.path),
|
|
2334
|
+
removed: applied.filter((change) => "remove" in change).map((change) => change.path)
|
|
2335
|
+
}));
|
|
2336
|
+
},
|
|
2337
|
+
uploads: {
|
|
2338
|
+
async list() {
|
|
2339
|
+
return (await listAcross(inRepo(uploadsDir))).filter((name) => !name.startsWith(".") && hasImageExtension(name)).map((filename) => ({
|
|
2340
|
+
filename,
|
|
2341
|
+
path: `${uploadsDir}/${filename}`
|
|
2342
|
+
}));
|
|
2343
|
+
},
|
|
2344
|
+
async save({ originalName, bytes, kind }) {
|
|
2345
|
+
const taken = new Set(await listAcross(inRepo(uploadsDir)));
|
|
2346
|
+
for (let attempt = 0; attempt < 8; attempt += 1) {
|
|
2347
|
+
const filename = uploadFilename(originalName, kind);
|
|
2348
|
+
if (taken.has(filename)) continue;
|
|
2349
|
+
await commit([{
|
|
2350
|
+
path: inRepo(uploadsDir, filename),
|
|
2351
|
+
bytes
|
|
2352
|
+
}], () => `Upload ${filename}`);
|
|
2353
|
+
return {
|
|
2354
|
+
filename,
|
|
2355
|
+
path: `${uploadsDir}/${filename}`,
|
|
2356
|
+
bytes: bytes.byteLength
|
|
2357
|
+
};
|
|
2358
|
+
}
|
|
2359
|
+
throw new Error("Unable to allocate a unique upload filename.");
|
|
2360
|
+
},
|
|
2361
|
+
async remove(filename) {
|
|
2362
|
+
if (!isUploadFilename(filename)) return false;
|
|
2363
|
+
if (!(await listAcross(inRepo(uploadsDir))).includes(filename)) return false;
|
|
2364
|
+
await commit([{
|
|
2365
|
+
path: inRepo(uploadsDir, filename),
|
|
2366
|
+
remove: true
|
|
2367
|
+
}], () => `Remove ${filename}`);
|
|
2368
|
+
return true;
|
|
2369
|
+
}
|
|
2370
|
+
},
|
|
2371
|
+
async assetExists(src) {
|
|
2372
|
+
if (!isAssetPath(src)) return false;
|
|
2373
|
+
const slash = src.lastIndexOf("/");
|
|
2374
|
+
const folder = inRepo(src.slice(0, slash));
|
|
2375
|
+
const name = src.slice(slash + 1);
|
|
2376
|
+
for (const ref of await target.refs()) if ((await listFilesAt(folder, ref))?.includes(name)) return true;
|
|
2377
|
+
return false;
|
|
2378
|
+
}
|
|
2379
|
+
};
|
|
2380
|
+
}
|
|
2381
|
+
const direct = {
|
|
2382
|
+
readRef: baseBranch,
|
|
2383
|
+
refs: async () => [await baseBranch()],
|
|
2384
|
+
writeBranch: baseBranch
|
|
2385
|
+
};
|
|
2386
|
+
if (!prMode) return view(direct);
|
|
2387
|
+
/** The branch of one entry's pull request: `bearminion/<scope>`, then `-2`, `-3` once earlier pull requests are closed. */
|
|
2388
|
+
async function activeBranch(scope) {
|
|
2389
|
+
const stem = branchStem(scope);
|
|
2390
|
+
for (let index = 1; index <= MAX_BRANCHES_PER_SCOPE; index += 1) {
|
|
2391
|
+
const name = index === 1 ? stem : `${stem}-${index}`;
|
|
2392
|
+
if (await branchHead(name) === void 0) return {
|
|
2393
|
+
name,
|
|
2394
|
+
exists: false
|
|
2395
|
+
};
|
|
2396
|
+
if (await pullState(name) !== "closed") return {
|
|
2397
|
+
name,
|
|
2398
|
+
exists: true
|
|
2399
|
+
};
|
|
2400
|
+
}
|
|
2401
|
+
throw new StoreError(409, "branch_exhausted", `There are already ${MAX_BRANCHES_PER_SCOPE} closed pull requests for "${scope}". Delete some of the bearminion/ branches.`);
|
|
2402
|
+
}
|
|
2403
|
+
const labelName = options.label === void 0 ? "bearminion" : options.label;
|
|
2404
|
+
async function openPullRequest(scope, name, change) {
|
|
2405
|
+
if (await pullState(name) === "open") return;
|
|
2406
|
+
const kind = scope.replace(":", ": ");
|
|
2407
|
+
const files = [...change.written.map((path) => `- ${path}`), ...change.removed.map((path) => `- ${path} (removed)`)].join("\n");
|
|
2408
|
+
const text = options.pullRequest?.({
|
|
2409
|
+
scope,
|
|
2410
|
+
...change
|
|
2411
|
+
}) ?? {
|
|
2412
|
+
title: `Edit ${kind}`,
|
|
2413
|
+
body: `Opened by the BearMinion editor. Merge it to publish the change.\n\nFirst save changed:\n${files}\n\nLater saves of the same entry are added to this pull request.`
|
|
2414
|
+
};
|
|
2415
|
+
const reply = await send("POST", `/repos/${repo}/pulls`, { body: {
|
|
2416
|
+
title: text.title,
|
|
2417
|
+
head: name,
|
|
2418
|
+
base: await baseBranch(),
|
|
2419
|
+
body: text.body
|
|
2420
|
+
} });
|
|
2421
|
+
if (reply.status === 422 && /already exists/i.test(messageOf(reply.text))) return;
|
|
2422
|
+
if (reply.status !== 201) throw failure(reply, "open the pull request");
|
|
2423
|
+
if (labelName === false) return;
|
|
2424
|
+
const { number } = JSON.parse(reply.text);
|
|
2425
|
+
await send("POST", `/repos/${repo}/issues/${number}/labels`, { body: { labels: [labelName] } });
|
|
2426
|
+
}
|
|
2427
|
+
function scopeTarget(scope) {
|
|
2428
|
+
const readRef = async () => {
|
|
2429
|
+
const active = await activeBranch(scope);
|
|
2430
|
+
return active.exists ? active.name : baseBranch();
|
|
2431
|
+
};
|
|
2432
|
+
return {
|
|
2433
|
+
readRef,
|
|
2434
|
+
refs: async () => {
|
|
2435
|
+
const refs = [await readRef()];
|
|
2436
|
+
if (scope !== "uploads") {
|
|
2437
|
+
const uploads = await activeBranch("uploads");
|
|
2438
|
+
if (uploads.exists) refs.push(uploads.name);
|
|
2439
|
+
}
|
|
2440
|
+
const base = await baseBranch();
|
|
2441
|
+
if (!refs.includes(base)) refs.push(base);
|
|
2442
|
+
return refs;
|
|
2443
|
+
},
|
|
2444
|
+
async writeBranch() {
|
|
2445
|
+
const active = await activeBranch(scope);
|
|
2446
|
+
if (active.exists) return active.name;
|
|
2447
|
+
const base = await baseBranch();
|
|
2448
|
+
const sha = await branchHead(base);
|
|
2449
|
+
if (sha === void 0) throw failure({
|
|
2450
|
+
status: 404,
|
|
2451
|
+
headers: new Headers(),
|
|
2452
|
+
text: ""
|
|
2453
|
+
}, `read the branch "${base}"`);
|
|
2454
|
+
const created = await send("POST", `/repos/${repo}/git/refs`, { body: {
|
|
2455
|
+
ref: `refs/heads/${active.name}`,
|
|
2456
|
+
sha
|
|
2457
|
+
} });
|
|
2458
|
+
if (created.status !== 201 && created.status !== 422) throw failure(created, `create the branch "${active.name}"`);
|
|
2459
|
+
return active.name;
|
|
2460
|
+
},
|
|
2461
|
+
committed: (name, change) => openPullRequest(scope, name, change)
|
|
2462
|
+
};
|
|
2463
|
+
}
|
|
2464
|
+
const scoped = (scope) => view(scopeTarget(scope));
|
|
2465
|
+
const base = view(direct);
|
|
2466
|
+
const edits = scoped("edits");
|
|
2467
|
+
const uploadScope = scoped("uploads");
|
|
2468
|
+
return {
|
|
2469
|
+
read: base.read,
|
|
2470
|
+
exists: base.exists,
|
|
2471
|
+
list: base.list,
|
|
2472
|
+
apply: edits.apply,
|
|
2473
|
+
uploads: uploadScope.uploads,
|
|
2474
|
+
assetExists: base.assetExists,
|
|
2475
|
+
scoped
|
|
2476
|
+
};
|
|
2477
|
+
}
|
|
2478
|
+
//#endregion
|
|
2005
2479
|
//#region src/load.ts
|
|
2006
2480
|
/**
|
|
2007
2481
|
* Load `site.json` and `pages/*.json` from a content directory.
|
|
@@ -2097,4 +2571,4 @@ function isErrno(error) {
|
|
|
2097
2571
|
*/
|
|
2098
2572
|
var astro_default = bearminion;
|
|
2099
2573
|
//#endregion
|
|
2100
|
-
export { StoreKeyError, bearminion, createFileStore, astro_default as default, loadContent, loadPages, loadSite };
|
|
2574
|
+
export { StoreError, StoreKeyError, bearminion, createFileStore, astro_default as default, githubStore, loadContent, loadPages, loadSite };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { $ as Theme, $t as SCHEMA_VERSION_KEY, A as ContentModel, At as wireKinds, B as Footer, Bt as motionOption, C as jsonLdSchema, Ct as SectionConfig, D as siteJsonLdIds, Dt as WireRect, E as parseJsonLdInput, Et as WireKind, F as defaultTheme, Ft as EnumOption, G as Site, Gt as FieldChoices, H as FooterConfig, Ht as toneOption, I as defineTheme, It as NumberOption, J as SiteConsent, Jt as ShowWhen, K as SiteAnalytics, Kt as FieldIcons, L as BRAND_LOGO_HEIGHT, Lt as Option, M as ThemeConfig, Mt as OptionalContent, N as ThemeDefinition, Nt as BooleanOption, O as upsertJsonLd, Ot as Wireframe, P as ThemeFont, Pt as CountRule, Q as SiteWith, Qt as DocumentKind, R as DEFAULT_MAX_FOOTER_COLUMNS, Rt as StringOption, S as isPlaceholderSiteUrl, St as withEmphasis, T as mergeJsonLd, Tt as defineSection, U as Header, Ut as tones, V as FooterColumn, Vt as themeModes, W as HeaderConfig, Wt as variantOption, X as SiteOf, Xt as ContentMigrator, Y as SiteDefinition, Yt as ContentMigration, Z as SiteSeo, Zt as ContentVersioning, _ as SiteJsonLdIds, _t as richTextSchema, a as createPageSchema, at as themeColorsSchema, b as generateSiteJsonLd, bt as toneSchema, c as withoutOrphanSections, ct as Image, d as SectionOf, dt as RichText, en as createMigrator, et as brandLogoSchema, f as anchorSchema, ft as Text, g as JsonLdResult, gt as linkSchema, h as JsonLdBlock, ht as imageSchema, i as Seo, it as siteSeoSchema, j as SectionRegistry, jt as wireframeIssues, k as API_PREFIX, kt as defineWireframe, l as BaseSection, lt as Link, m as sectionIdSchema, mt as htmlIdSchema, nt as siteAnalyticsSchema, o as isSystemPage, ot as themeSchema, p as createSectionSchema, pt as Tone, q as SiteConfig, qt as ShowCondition, r as SYSTEM_PAGES, rt as siteConsentSchema, s as seoSchema, st as ButtonStyle, t as Page, tt as defineSite, u as PropsOf, ut as MAX_NAV_DEPTH, v as SiteJsonLdSource, vt as textMarkSchema, w as jsonLdWarnings, wt as SectionDefinition, x as hasJsonLdId, xt as trackingIdSchema, y as formatJsonLd, yt as textSchema, z as DEFAULT_MAX_HEADER_ACTIONS, zt as buttonStyles } from "./page-CwbIDegI.js";
|
|
2
2
|
import { _ as renderMarkedHtml, a as WeightMark, f as markClass, g as reconcileMarks, i as TextRun, l as fontMarks, m as marksFromEmphasis, o as applyTextMark, r as TextMark, t as FontMark, v as splitMarkedText, y as weightMarks } from "./marks-BzLa48Y9.js";
|
|
3
|
-
import "./options-
|
|
3
|
+
import "./options-CosfIOMs.js";
|
|
4
4
|
import { a as TURNSTILE_FIELD, i as HONEYPOT_FIELD, n as FormResult, r as FormSubmission, t as FormFieldErrors } from "./form-contract-BURSJP3Y.js";
|
|
5
5
|
//#region src/errors.d.ts
|
|
6
6
|
/** One schema problem, addressed by a dot path such as `sections.0.props.heading`. */
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { A as ContentModel, N as ThemeDefinition, Xt as ContentMigrator, Y as SiteDefinition, j as SectionRegistry, n as PageRules } from "./page-CwbIDegI.js";
|
|
2
|
-
//#region src/
|
|
2
|
+
//#region src/upload-names.d.ts
|
|
3
3
|
type ImageKind = 'png' | 'jpeg' | 'webp' | 'gif' | 'avif';
|
|
4
|
+
//#endregion
|
|
5
|
+
//#region src/images.d.ts
|
|
4
6
|
interface SavedImage {
|
|
5
7
|
filename: string;
|
|
6
8
|
path: string;
|
|
@@ -58,6 +60,12 @@ interface ContentStore {
|
|
|
58
60
|
* fail validation. A store without it skips that check.
|
|
59
61
|
*/
|
|
60
62
|
assetExists?(src: string): Promise<boolean>;
|
|
63
|
+
/**
|
|
64
|
+
* A view of the store for editing one entry (`page:about`, `site`), for stores that keep each entry's pending edits
|
|
65
|
+
* apart, such as `githubStore` in `pr` mode, where every scope is a branch and a pull request. Reads see the entry's
|
|
66
|
+
* pending edits, writes go to them. Absent when every write goes to the same place.
|
|
67
|
+
*/
|
|
68
|
+
scoped?(scope: string): ContentStore;
|
|
61
69
|
}
|
|
62
70
|
type StoreOperation = {
|
|
63
71
|
type: 'write';
|
|
@@ -87,10 +95,6 @@ interface VideoStore {
|
|
|
87
95
|
}): Promise<SavedVideo>;
|
|
88
96
|
remove(filename: string): Promise<boolean>;
|
|
89
97
|
}
|
|
90
|
-
/** A key that is empty, absolute or leaves the content directory. */
|
|
91
|
-
declare class StoreKeyError extends Error {
|
|
92
|
-
constructor(key: string);
|
|
93
|
-
}
|
|
94
98
|
interface FileStoreOptions {
|
|
95
99
|
/** Project root. Upload paths are relative to it. */
|
|
96
100
|
root: string;
|
|
@@ -204,4 +208,4 @@ interface EditorContext {
|
|
|
204
208
|
formsDir?: string | null;
|
|
205
209
|
}
|
|
206
210
|
//#endregion
|
|
207
|
-
export {
|
|
211
|
+
export { StoreOperation as a, FileStoreOptions as i, EditorContext as n, UploadStore as o, ContentStore as r, createFileStore as s, BearminionOptions as t };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bearminion",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.14.0",
|
|
4
4
|
"description": "A git-based CMS for Astro with no database and no server: JSON content in your repo, edited by clicking on the page during astro dev.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Jakub Lange",
|