bearminion 1.12.0 → 1.13.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 +6 -0
- package/dist/astro.d.ts +47 -2
- package/dist/astro.js +335 -18
- package/dist/index.d.ts +1 -1
- package/dist/{options-WI_ztZTj.d.ts → options-DP6mTauQ.d.ts} +4 -6
- package/package.json +1 -1
- package/registry/default/registry.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# bearminion
|
|
2
2
|
|
|
3
|
+
## 1.13.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 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.
|
|
8
|
+
|
|
3
9
|
## 1.12.0
|
|
4
10
|
|
|
5
11
|
### 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-DP6mTauQ.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,35 @@ 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
|
+
/** The GitHub API. Default `https://api.github.com`. Set it for GitHub Enterprise. */
|
|
54
|
+
apiUrl?: string;
|
|
55
|
+
/** Default: the global `fetch`. */
|
|
56
|
+
fetch?: typeof fetch;
|
|
57
|
+
}
|
|
58
|
+
export declare function githubStore(options: GithubStoreOptions): ContentStore;
|
|
59
|
+
//#endregion
|
|
15
60
|
//#region src/load.d.ts
|
|
16
61
|
interface LoadOptions {
|
|
17
62
|
/** Upgrades files written under an older `schemaVersion`. `loadContent` builds it from the model. */
|
|
@@ -40,4 +85,4 @@ export declare function loadSite<TDefinition extends SiteDefinition>(contentDir:
|
|
|
40
85
|
*/
|
|
41
86
|
export declare function loadPages<TRegistry extends SectionRegistry>(contentDir: string, registry: TRegistry, { migrator, tolerateOrphans }?: LoadOptions): Page<SectionOf<TRegistry>>[];
|
|
42
87
|
//#endregion
|
|
43
|
-
export { type BearminionIntegration, type BearminionOptions, type ContentStore, type EditorContext, type FileStoreOptions, type LoadOptions, type LoadedContent,
|
|
88
|
+
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.");
|
|
@@ -902,7 +957,8 @@ async function readStoredJson(context, key, kind) {
|
|
|
902
957
|
if (text === void 0) return void 0;
|
|
903
958
|
const upgraded = context.migrator.upgrade(JSON.parse(text), kind);
|
|
904
959
|
return upgraded.ok ? upgraded.value : void 0;
|
|
905
|
-
} catch {
|
|
960
|
+
} catch (error) {
|
|
961
|
+
if (error instanceof StoreError) throw error;
|
|
906
962
|
return;
|
|
907
963
|
}
|
|
908
964
|
}
|
|
@@ -1445,6 +1501,7 @@ async function postImage(request, context) {
|
|
|
1445
1501
|
kind: sniffed
|
|
1446
1502
|
}));
|
|
1447
1503
|
} catch (error) {
|
|
1504
|
+
if (error instanceof StoreError) throw error;
|
|
1448
1505
|
return problem(500, "write_failed", error instanceof Error ? error.message : "Upload failed.");
|
|
1449
1506
|
}
|
|
1450
1507
|
}
|
|
@@ -1545,6 +1602,7 @@ async function loadStoredPages(context, options = {}) {
|
|
|
1545
1602
|
try {
|
|
1546
1603
|
raw = JSON.parse(await context.store.read(key) ?? "");
|
|
1547
1604
|
} catch (error) {
|
|
1605
|
+
if (error instanceof StoreError) throw error;
|
|
1548
1606
|
if (error instanceof StoreKeyError) return { response: problem(400, "invalid_path", `Refusing to read ${name}.`) };
|
|
1549
1607
|
return { response: problem(400, "invalid_json", `Invalid JSON in ${name}: ${error instanceof Error ? error.message : String(error)}`) };
|
|
1550
1608
|
}
|
|
@@ -1625,6 +1683,7 @@ function contentLength(request) {
|
|
|
1625
1683
|
return value;
|
|
1626
1684
|
}
|
|
1627
1685
|
function contentFailure(error) {
|
|
1686
|
+
if (error instanceof StoreError) throw error;
|
|
1628
1687
|
if (error instanceof ContentValidationError) return json(422, {
|
|
1629
1688
|
error: "validation",
|
|
1630
1689
|
message: error.message,
|
|
@@ -2002,6 +2061,264 @@ function rootInput(root) {
|
|
|
2002
2061
|
return process.cwd();
|
|
2003
2062
|
}
|
|
2004
2063
|
//#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
|
|
2005
2322
|
//#region src/load.ts
|
|
2006
2323
|
/**
|
|
2007
2324
|
* Load `site.json` and `pages/*.json` from a content directory.
|
|
@@ -2097,4 +2414,4 @@ function isErrno(error) {
|
|
|
2097
2414
|
*/
|
|
2098
2415
|
var astro_default = bearminion;
|
|
2099
2416
|
//#endregion
|
|
2100
|
-
export { StoreKeyError, bearminion, createFileStore, astro_default as default, loadContent, loadPages, loadSite };
|
|
2417
|
+
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-DP6mTauQ.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;
|
|
@@ -87,10 +89,6 @@ interface VideoStore {
|
|
|
87
89
|
}): Promise<SavedVideo>;
|
|
88
90
|
remove(filename: string): Promise<boolean>;
|
|
89
91
|
}
|
|
90
|
-
/** A key that is empty, absolute or leaves the content directory. */
|
|
91
|
-
declare class StoreKeyError extends Error {
|
|
92
|
-
constructor(key: string);
|
|
93
|
-
}
|
|
94
92
|
interface FileStoreOptions {
|
|
95
93
|
/** Project root. Upload paths are relative to it. */
|
|
96
94
|
root: string;
|
|
@@ -204,4 +202,4 @@ interface EditorContext {
|
|
|
204
202
|
formsDir?: string | null;
|
|
205
203
|
}
|
|
206
204
|
//#endregion
|
|
207
|
-
export {
|
|
205
|
+
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.13.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",
|