bearminion 1.11.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 CHANGED
@@ -1,5 +1,21 @@
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
+
9
+ ## 1.12.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 1435da5: `bearminion({ pages: { rename: false, delete: false } })` locks page operations for sites whose addresses carry search ranking or are the target of redirects. Both default to `true`, so nothing changes unless you set them. A locked operation is refused by the API with `409` `operation_locked`, whoever asks: the rename route, the delete route, set-home, and a save that changes a slug (making another page the home page counts as a rename, because the old home page moves to a new address). The editor makes the slug read-only, disables the Home page switch and hides Delete. `GET /schema` reports the rules as `pageRules`.
14
+
15
+ ### Patch Changes
16
+
17
+ - 1435da5: The New page form makes the slug from the title as you type it, until you edit the slug by hand, and numbers it when a page with that slug exists (`about-2`). Changing a title afterwards never changes the slug. A failed create now shows the server's reason in the form instead of doing nothing. `slugifyAnchor` writes accented letters as the plain letter (`ą` is `a`, `ł` is `l`, `ß` is `ss`) instead of turning them into hyphens, so `Łódź` is `lodz` and not `o-dz`; this also fixes section anchors suggested from non-ASCII headings.
18
+
3
19
  ## 1.11.0
4
20
 
5
21
  ### Minor Changes
package/dist/astro.d.ts CHANGED
@@ -1,6 +1,22 @@
1
- import { A as SectionRegistry, J as SiteDefinition, Y as SiteOf, Yt as ContentMigrator, k as ContentModel, t as Page, u as SectionOf } from "./page-BfI9cD8g.js";
2
- import { a as StoreKeyError, c as createFileStore, i as FileStoreOptions, n as EditorContext, o as StoreOperation, r as ContentStore, s as UploadStore, t as BearminionOptions } from "./options-NdG2XQv4.js";
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 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, StoreKeyError, type StoreOperation, type UploadStore, bearminion as default, createFileStore };
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
@@ -1,12 +1,12 @@
1
- import { a as imageFields, c as ContentReadError, l as ContentValidationError, r as loadThemePreview, t as PreviewUnavailableError } from "./preview-B_88I5Jm.js";
2
- import { t as defaultTheme } from "./theme-Dv7_7B56.js";
3
- import { i as isSystemPage, n as createPageSchema$1, r as createTolerantPageSchema, s as withoutOrphanSections, u as isOrphanSection } from "./page-X-WnOu7-.js";
1
+ import { a as imageFields, c as ContentReadError, l as ContentValidationError, r as loadThemePreview, t as PreviewUnavailableError } from "./preview-ImEm3T8k.js";
2
+ import { t as defaultTheme } from "./theme-BvqJ8UnS.js";
3
+ import { a as resolvePageRules, c as withoutOrphanSections, d as isOrphanSection, i as isSystemPage, n as createPageSchema$1, r as createTolerantPageSchema } from "./page-wlcQJAA-.js";
4
4
  import { a as DEFAULT_UPLOADS_DIR, i as DEFAULT_CONTENT_DIR, n as createMigrator, o as DEFAULT_VIDEOS_DIR, r as API_PREFIX, t as SCHEMA_VERSION_KEY } from "./migrate-b408EaLp.js";
5
5
  import { i as resolveMaxImageBytes, n as formatBytes, r as resolveConvert } from "./upload-rules-Cao9uY5K.js";
6
- import { a as isLocalRequest, c as resolveInside, i as isInside, n as JSON_BODY_LIMIT, o as readSlug, r as asDirectory, s as resolveDir, t as IMAGE_BYTE_LIMIT } from "./security-BA9KzK-2.js";
7
- import { a as resolveFormsConfig, n as formFile, r as formsAreLive, t as createFormsMiddleware } from "./forms-dev-DQoWfcMA.js";
6
+ import { a as isLocalRequest, c as resolveInside, i as isInside, n as JSON_BODY_LIMIT, o as readSlug, r as asDirectory, s as resolveDir, t as IMAGE_BYTE_LIMIT } from "./security-FLvgc2jD.js";
7
+ import { a as resolveFormsConfig, n as formFile, r as formsAreLive, t as createFormsMiddleware } from "./forms-dev-CEab55ss.js";
8
8
  import { S as isAssetPath, b as describeSiteRef, c as projectId, v as assetRefs, y as describePageRef } from "./draft-store-1Y4-sn45.js";
9
- import { n as contentReloadPlugin, r as dropEarlyReloadAfterSave } from "./reload-CU0U52ja.js";
9
+ import { n as contentReloadPlugin, r as dropEarlyReloadAfterSave } from "./reload-BIIa7pej.js";
10
10
  import { i as syncSections, r as staleSectionsMessage } from "./sections-manifest-CO9QfJPG.js";
11
11
  import { z } from "zod";
12
12
  import fs from "node:fs";
@@ -40,7 +40,7 @@ function editorClientPlugin() {
40
40
  }
41
41
  //#endregion
42
42
  //#region src/videos.ts
43
- const EXTENSION$1 = {
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$1[options.kind];
82
- const stem = safeStem$1(options.originalName);
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$1).includes(path.extname(entry.name).toLowerCase())) continue;
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$1).includes(path.extname(filename).toLowerCase())) return false;
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$1(originalName) {
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/images.ts
210
- const EXTENSION = {
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 = EXTENSION[options.kind];
240
- const stem = safeStem(options.originalName);
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(EXTENSION).includes(extension)) continue;
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(EXTENSION).includes(extension)) return false;
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`). */
@@ -445,6 +492,7 @@ function resolveEditorContext(options, rootInput) {
445
492
  videosDir,
446
493
  maxVideoBytes: options?.maxVideoBytes ?? 52428800,
447
494
  maxImageBytes: resolveMaxImageBytes(options?.maxImageBytes),
495
+ pageRules: resolvePageRules(options?.pages),
448
496
  imageConvert: resolveConvert(options?.imageConvert),
449
497
  sections: options.sections,
450
498
  site: options.site,
@@ -702,6 +750,14 @@ async function commitChanges(context, message, paths) {
702
750
  * so other middleware can continue. Every write is schema-checked first.
703
751
  */
704
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) {
705
761
  const pathname = stripTrailingSlash$1(new URL(request.url).pathname);
706
762
  if (pathname !== "/__bearminion/api" && !pathname.startsWith(`/__bearminion/api/`)) return null;
707
763
  if (!isLocalRequest(request.headers, meta.remoteAddress)) return problem(403, "forbidden", "The editor API only accepts requests from localhost.");
@@ -860,6 +916,7 @@ async function getSchema(context) {
860
916
  fieldImages,
861
917
  showWhen,
862
918
  sectionForms,
919
+ pageRules: context.pageRules,
863
920
  sectionDefaults,
864
921
  sectionLabels,
865
922
  sectionDescriptions,
@@ -900,7 +957,8 @@ async function readStoredJson(context, key, kind) {
900
957
  if (text === void 0) return void 0;
901
958
  const upgraded = context.migrator.upgrade(JSON.parse(text), kind);
902
959
  return upgraded.ok ? upgraded.value : void 0;
903
- } catch {
960
+ } catch (error) {
961
+ if (error instanceof StoreError) throw error;
904
962
  return;
905
963
  }
906
964
  }
@@ -1015,6 +1073,7 @@ async function planPageSave(context, input) {
1015
1073
  removals: [],
1016
1074
  after
1017
1075
  };
1076
+ if (!context.pageRules.rename) return { response: locked("rename") };
1018
1077
  if (from === "index") return { response: problem(409, "conflict", "The home page slug stays index. Set another page as home to move it.") };
1019
1078
  if (isSystemPage(from) || isSystemPage(target)) return { response: problem(409, "reserved_slug", "System pages cannot be renamed, and no page can take their slug.") };
1020
1079
  if (target !== "index") {
@@ -1143,7 +1202,11 @@ async function createPage(request, context) {
1143
1202
  await writeDocuments(context, [[key, validated.data]]);
1144
1203
  return json(201, validated.data);
1145
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
+ }
1146
1208
  async function deletePage(context, slug) {
1209
+ if (!context.pageRules.delete) return locked("delete");
1147
1210
  if (slug === "index") return problem(409, "conflict", "Refusing to delete the index page.");
1148
1211
  if (isSystemPage(slug)) return problem(409, "reserved_slug", `"${slug}" is a system page and cannot be deleted.`);
1149
1212
  const loaded = await loadStoredPages(context);
@@ -1165,6 +1228,7 @@ async function setHome(request, context, slug) {
1165
1228
  if (body.response) return body.response;
1166
1229
  const parsed = setHomeSchema.safeParse(body.value);
1167
1230
  if (!parsed.success) return validation(fieldIssues(parsed.error));
1231
+ if (!context.pageRules.rename) return locked("rename");
1168
1232
  if (slug === "index") return problem(409, "conflict", "That page is already the home page.");
1169
1233
  if (isSystemPage(slug)) return problem(409, "reserved_slug", `"${slug}" is a system page and cannot be the home page.`);
1170
1234
  const loaded = await loadStoredPages(context);
@@ -1207,6 +1271,7 @@ async function renamePage(request, context, slug) {
1207
1271
  const parsed = renameSchema.safeParse(body.value);
1208
1272
  if (!parsed.success) return validation(fieldIssues(parsed.error));
1209
1273
  const nextSlug = parsed.data.slug;
1274
+ if (!context.pageRules.rename) return locked("rename");
1210
1275
  if (nextSlug === slug) return problem(400, "invalid_slug", "The new slug is the same as the current slug.");
1211
1276
  if (slug === "index") return problem(409, "conflict", "Refusing to rename the index page.");
1212
1277
  if (isSystemPage(slug) || isSystemPage(nextSlug)) return problem(409, "reserved_slug", "System pages cannot be renamed, and no page can take their slug.");
@@ -1436,6 +1501,7 @@ async function postImage(request, context) {
1436
1501
  kind: sniffed
1437
1502
  }));
1438
1503
  } catch (error) {
1504
+ if (error instanceof StoreError) throw error;
1439
1505
  return problem(500, "write_failed", error instanceof Error ? error.message : "Upload failed.");
1440
1506
  }
1441
1507
  }
@@ -1536,6 +1602,7 @@ async function loadStoredPages(context, options = {}) {
1536
1602
  try {
1537
1603
  raw = JSON.parse(await context.store.read(key) ?? "");
1538
1604
  } catch (error) {
1605
+ if (error instanceof StoreError) throw error;
1539
1606
  if (error instanceof StoreKeyError) return { response: problem(400, "invalid_path", `Refusing to read ${name}.`) };
1540
1607
  return { response: problem(400, "invalid_json", `Invalid JSON in ${name}: ${error instanceof Error ? error.message : String(error)}`) };
1541
1608
  }
@@ -1616,6 +1683,7 @@ function contentLength(request) {
1616
1683
  return value;
1617
1684
  }
1618
1685
  function contentFailure(error) {
1686
+ if (error instanceof StoreError) throw error;
1619
1687
  if (error instanceof ContentValidationError) return json(422, {
1620
1688
  error: "validation",
1621
1689
  message: error.message,
@@ -1993,6 +2061,264 @@ function rootInput(root) {
1993
2061
  return process.cwd();
1994
2062
  }
1995
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
1996
2322
  //#region src/load.ts
1997
2323
  /**
1998
2324
  * Load `site.json` and `pages/*.json` from a content directory.
@@ -2088,4 +2414,4 @@ function isErrno(error) {
2088
2414
  */
2089
2415
  var astro_default = bearminion;
2090
2416
  //#endregion
2091
- 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/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { i as readDotEnv } from "./forms-dev-DQoWfcMA.js";
2
+ import { i as readDotEnv } from "./forms-dev-CEab55ss.js";
3
3
  import { i as syncSections, r as staleSectionsMessage, t as SectionsError } from "./sections-manifest-CO9QfJPG.js";
4
4
  import { i as writeLock, n as readLock, r as recordFiles, t as hashContent } from "./hash-BeBymBO1.js";
5
5
  import fs from "node:fs";
package/dist/content.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { k as ContentModel, t as Page, u as SectionOf } from "./page-BfI9cD8g.js";
1
+ import { A as ContentModel, d as SectionOf, t as Page } from "./page-CwbIDegI.js";
2
2
  import { z } from "zod";
3
3
  //#region src/content.d.ts
4
4
  export interface ContentCollectionsOptions {
package/dist/content.js CHANGED
@@ -1,6 +1,6 @@
1
- import { n as createPageSchema, r as createTolerantPageSchema } from "./page-X-WnOu7-.js";
1
+ import { n as createPageSchema, r as createTolerantPageSchema } from "./page-wlcQJAA-.js";
2
2
  import { n as createMigrator } from "./migrate-b408EaLp.js";
3
- import { t as CONTENT_COLLECTIONS_MARKER } from "./reload-CU0U52ja.js";
3
+ import { t as CONTENT_COLLECTIONS_MARKER } from "./reload-BIIa7pej.js";
4
4
  import { z } from "zod";
5
5
  import path from "node:path";
6
6
  import { pathToFileURL } from "node:url";
@@ -1,4 +1,4 @@
1
- import { s as resolveDir } from "./security-BA9KzK-2.js";
1
+ import { s as resolveDir } from "./security-FLvgc2jD.js";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { parseEnv } from "node:util";
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { $ as brandLogoSchema, $t as createMigrator, A as SectionRegistry, At as wireframeIssues, B as FooterColumn, Bt as themeModes, C as jsonLdWarnings, Ct as SectionDefinition, D as upsertJsonLd, Dt as Wireframe, E as siteJsonLdIds, Et as WireRect, F as defineTheme, Ft as NumberOption, G as SiteAnalytics, Gt as FieldIcons, H as Header, Ht as tones, I as BRAND_LOGO_HEIGHT, It as Option, J as SiteDefinition, Jt as ContentMigration, K as SiteConfig, Kt as ShowCondition, L as DEFAULT_MAX_FOOTER_COLUMNS, Lt as StringOption, M as ThemeDefinition, Mt as BooleanOption, N as ThemeFont, Nt as CountRule, O as API_PREFIX, Ot as defineWireframe, P as defaultTheme, Pt as EnumOption, Q as Theme, Qt as SCHEMA_VERSION_KEY, R as DEFAULT_MAX_HEADER_ACTIONS, Rt as buttonStyles, S as jsonLdSchema, St as SectionConfig, T as parseJsonLdInput, Tt as WireKind, U as HeaderConfig, Ut as variantOption, V as FooterConfig, Vt as toneOption, W as Site, Wt as FieldChoices, X as SiteSeo, Xt as ContentVersioning, Y as SiteOf, Yt as ContentMigrator, Z as SiteWith, Zt as DocumentKind, _ as SiteJsonLdSource, _t as textMarkSchema, a as isSystemPage, at as themeSchema, b as hasJsonLdId, bt as trackingIdSchema, c as BaseSection, ct as Link, d as anchorSchema, dt as Text, et as defineSite, f as createSectionSchema, ft as Tone, g as SiteJsonLdIds, gt as richTextSchema, h as JsonLdResult, ht as linkSchema, i as createPageSchema, it as themeColorsSchema, j as ThemeConfig, jt as OptionalContent, k as ContentModel, kt as wireKinds, l as PropsOf, lt as MAX_NAV_DEPTH, m as JsonLdBlock, mt as imageSchema, n as SYSTEM_PAGES, nt as siteConsentSchema, o as seoSchema, ot as ButtonStyle, p as sectionIdSchema, pt as htmlIdSchema, q as SiteConsent, qt as ShowWhen, r as Seo, rt as siteSeoSchema, s as withoutOrphanSections, st as Image, t as Page, tt as siteAnalyticsSchema, u as SectionOf, ut as RichText, v as formatJsonLd, vt as textSchema, w as mergeJsonLd, wt as defineSection, x as isPlaceholderSiteUrl, xt as withEmphasis, y as generateSiteJsonLd, yt as toneSchema, z as Footer, zt as motionOption } from "./page-BfI9cD8g.js";
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-NdG2XQv4.js";
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`. */
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { c as ContentReadError, i as enumFields, l as ContentValidationError, n as defineThemePreview, o as schemaProps, s as ContentError, u as formatContentIssues } from "./preview-B_88I5Jm.js";
2
- import { n as defineTheme, t as defaultTheme } from "./theme-Dv7_7B56.js";
3
- import { A as textSchema, C as MAX_NAV_DEPTH, D as linkSchema, E as imageSchema, F as DEFAULT_IMAGE_POSITION, G as tones, H as motionOption, I as IMAGE_FITS, K as variantOption, L as IMAGE_POSITIONS, M as trackingIdSchema, N as withEmphasis, O as richTextSchema, P as DEFAULT_IMAGE_FIT, R as isImageFit, S as upsertJsonLd, T as htmlIdSchema, U as themeModes, V as buttonStyles, W as toneOption, _ as jsonLdSchema, a as seoSchema, b as parseJsonLdInput, c as anchorSchema, d as sectionIdSchema, f as walkLinkIds, g as isPlaceholderSiteUrl, h as hasJsonLdId, i as isSystemPage, j as toneSchema, k as textMarkSchema, l as createSectionSchema, m as generateSiteJsonLd, n as createPageSchema, p as formatJsonLd, s as withoutOrphanSections, t as SYSTEM_PAGES, v as jsonLdWarnings, w as addMarkIssues, x as siteJsonLdIds, y as mergeJsonLd, z as isImagePosition } from "./page-X-WnOu7-.js";
1
+ import { c as ContentReadError, i as enumFields, l as ContentValidationError, n as defineThemePreview, o as schemaProps, s as ContentError, u as formatContentIssues } from "./preview-ImEm3T8k.js";
2
+ import { n as defineTheme, t as defaultTheme } from "./theme-BvqJ8UnS.js";
3
+ import { A as textMarkSchema, B as isImagePosition, C as upsertJsonLd, D as imageSchema, E as htmlIdSchema, F as DEFAULT_IMAGE_FIT, G as toneOption, H as buttonStyles, I as DEFAULT_IMAGE_POSITION, K as tones, L as IMAGE_FITS, M as toneSchema, N as trackingIdSchema, O as linkSchema, P as withEmphasis, R as IMAGE_POSITIONS, S as siteJsonLdIds, T as addMarkIssues, U as motionOption, W as themeModes, _ as isPlaceholderSiteUrl, b as mergeJsonLd, c as withoutOrphanSections, f as sectionIdSchema, g as hasJsonLdId, h as generateSiteJsonLd, i as isSystemPage, j as textSchema, k as richTextSchema, l as anchorSchema, m as formatJsonLd, n as createPageSchema, o as seoSchema, p as walkLinkIds, q as variantOption, t as SYSTEM_PAGES, u as createSectionSchema, v as jsonLdSchema, w as MAX_NAV_DEPTH, x as parseJsonLdInput, y as jsonLdWarnings, z as isImageFit } from "./page-wlcQJAA-.js";
4
4
  import { d as reconcileMarks, f as renderMarkedHtml, i as fontMarks, l as marksFromEmphasis, m as weightMarks, p as splitMarkedText, s as markClass, t as applyTextMark } from "./marks-DPBilumg.js";
5
5
  import { n as createMigrator, r as API_PREFIX, t as SCHEMA_VERSION_KEY } from "./migrate-b408EaLp.js";
6
6
  import { n as TURNSTILE_FIELD, t as HONEYPOT_FIELD } from "./form-contract-CIDTNab-.js";
@@ -1,6 +1,8 @@
1
- import { A as SectionRegistry, J as SiteDefinition, M as ThemeDefinition, Yt as ContentMigrator, k as ContentModel } from "./page-BfI9cD8g.js";
2
- //#region src/images.d.ts
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/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;
@@ -142,6 +140,13 @@ interface BearminionOptions extends ContentModel {
142
140
  * out larger is kept as it is. Default: off, images are uploaded as they are.
143
141
  */
144
142
  imageConvert?: false | ImageConvertOptions;
143
+ /**
144
+ * Which page operations the editor allows: `{ rename: false, delete: false }` for a site whose addresses must not
145
+ * change (they carry search ranking or are the target of redirects). Both default to true. A locked operation is
146
+ * refused by the API as well as hidden in the editor. `rename: false` also blocks making another page the home page,
147
+ * because that moves the old home page to a new address.
148
+ */
149
+ pages?: Partial<PageRules>;
145
150
  /**
146
151
  * Vite module id loaded by the dev server to render a draft page.
147
152
  * Default `/src/lib/render-preview.ts`. Preview never writes to disk.
@@ -182,6 +187,7 @@ interface EditorContext {
182
187
  videosDir: string;
183
188
  maxVideoBytes: number;
184
189
  maxImageBytes: number;
190
+ pageRules: PageRules;
185
191
  /** `imageConvert`, validated and with its defaults filled in. `null` when conversion is off. */
186
192
  imageConvert: UploadRules['convert'];
187
193
  sections: SectionRegistry;
@@ -196,4 +202,4 @@ interface EditorContext {
196
202
  formsDir?: string | null;
197
203
  }
198
204
  //#endregion
199
- export { StoreKeyError as a, createFileStore as c, FileStoreOptions as i, EditorContext as n, StoreOperation as o, ContentStore as r, UploadStore as s, BearminionOptions as t };
205
+ export { StoreOperation as a, FileStoreOptions as i, EditorContext as n, UploadStore as o, ContentStore as r, createFileStore as s, BearminionOptions as t };
@@ -275,10 +275,10 @@ declare const textMarkSchema: z.ZodObject<{
275
275
  start: z.ZodNumber;
276
276
  end: z.ZodNumber;
277
277
  weight: z.ZodOptional<z.ZodEnum<{
278
+ bold: "bold";
278
279
  regular: "regular";
279
280
  medium: "medium";
280
281
  semibold: "semibold";
281
- bold: "bold";
282
282
  }>>;
283
283
  italic: z.ZodOptional<z.ZodBoolean>;
284
284
  font: z.ZodOptional<z.ZodEnum<{
@@ -319,10 +319,10 @@ declare function withEmphasis<T extends z.ZodRawShape>(shape: T): z.ZodPipe<z.Zo
319
319
  start: z.ZodNumber;
320
320
  end: z.ZodNumber;
321
321
  weight: z.ZodOptional<z.ZodEnum<{
322
+ bold: "bold";
322
323
  regular: "regular";
323
324
  medium: "medium";
324
325
  semibold: "semibold";
325
- bold: "bold";
326
326
  }>>;
327
327
  italic: z.ZodOptional<z.ZodBoolean>;
328
328
  font: z.ZodOptional<z.ZodEnum<{
@@ -337,10 +337,10 @@ declare function withEmphasis<T extends z.ZodRawShape>(shape: T): z.ZodPipe<z.Zo
337
337
  start: z.ZodNumber;
338
338
  end: z.ZodNumber;
339
339
  weight: z.ZodOptional<z.ZodEnum<{
340
+ bold: "bold";
340
341
  regular: "regular";
341
342
  medium: "medium";
342
343
  semibold: "semibold";
343
- bold: "bold";
344
344
  }>>;
345
345
  italic: z.ZodOptional<z.ZodBoolean>;
346
346
  font: z.ZodOptional<z.ZodEnum<{
@@ -357,10 +357,10 @@ declare function withEmphasis<T extends z.ZodRawShape>(shape: T): z.ZodPipe<z.Zo
357
357
  start: z.ZodNumber;
358
358
  end: z.ZodNumber;
359
359
  weight: z.ZodOptional<z.ZodEnum<{
360
+ bold: "bold";
360
361
  regular: "regular";
361
362
  medium: "medium";
362
363
  semibold: "semibold";
363
- bold: "bold";
364
364
  }>>;
365
365
  italic: z.ZodOptional<z.ZodBoolean>;
366
366
  font: z.ZodOptional<z.ZodEnum<{
@@ -617,10 +617,10 @@ declare function createSiteSchema(header: HeaderParts, footer: FooterParts): z.Z
617
617
  start: z.ZodNumber;
618
618
  end: z.ZodNumber;
619
619
  weight: z.ZodOptional<z.ZodEnum<{
620
+ bold: "bold";
620
621
  regular: "regular";
621
622
  medium: "medium";
622
623
  semibold: "semibold";
623
- bold: "bold";
624
624
  }>>;
625
625
  italic: z.ZodOptional<z.ZodBoolean>;
626
626
  font: z.ZodOptional<z.ZodEnum<{
@@ -852,7 +852,7 @@ declare function createSiteSchema(header: HeaderParts, footer: FooterParts): z.Z
852
852
  nameMarks: {
853
853
  start: number;
854
854
  end: number;
855
- weight?: "regular" | "medium" | "semibold" | "bold" | undefined;
855
+ weight?: "bold" | "regular" | "medium" | "semibold" | undefined;
856
856
  italic?: boolean | undefined;
857
857
  font?: "sans" | "serif" | "mono" | undefined;
858
858
  }[] | undefined;
@@ -1110,7 +1110,7 @@ declare function createSiteSchema(header: HeaderParts, footer: FooterParts): z.Z
1110
1110
  nameMarks?: {
1111
1111
  start: number;
1112
1112
  end: number;
1113
- weight?: "regular" | "medium" | "semibold" | "bold" | undefined;
1113
+ weight?: "bold" | "regular" | "medium" | "semibold" | undefined;
1114
1114
  italic?: boolean | undefined;
1115
1115
  font?: "sans" | "serif" | "mono" | undefined;
1116
1116
  }[] | undefined;
@@ -1374,6 +1374,15 @@ declare const seoSchema: z.ZodObject<{
1374
1374
  * and refuses to create, delete, rename or promote them to the home page.
1375
1375
  */
1376
1376
  declare const SYSTEM_PAGES: readonly ["404"];
1377
+ /**
1378
+ * Which page operations the editor allows. Both default to true. A locked operation is refused by the API, whoever
1379
+ * asks (the editor, a script, an assistant), and its controls are hidden in the editor.
1380
+ */
1381
+ interface PageRules {
1382
+ /** Change a page's slug, including making another page the home page (that moves two pages to new addresses). */
1383
+ rename: boolean;
1384
+ delete: boolean;
1385
+ }
1377
1386
  declare function isSystemPage(slug: string): boolean;
1378
1387
  /** Validates a page document: its own fields, and every section against the registry. Cached per registry. */
1379
1388
  declare function createPageSchema<TRegistry extends SectionRegistry>(registry: TRegistry): z.ZodType<Page<SectionOf<TRegistry>>>;
@@ -1393,4 +1402,4 @@ declare function withoutOrphanSections<TPage extends {
1393
1402
  sections: readonly unknown[];
1394
1403
  }>(page: TPage, registry: SectionRegistry): TPage;
1395
1404
  //#endregion
1396
- export { brandLogoSchema as $, createMigrator as $t, SectionRegistry as A, wireframeIssues as At, FooterColumn as B, themeModes as Bt, jsonLdWarnings as C, SectionDefinition as Ct, upsertJsonLd as D, Wireframe as Dt, siteJsonLdIds as E, WireRect as Et, defineTheme as F, NumberOption as Ft, SiteAnalytics as G, FieldIcons as Gt, Header as H, tones as Ht, BRAND_LOGO_HEIGHT as I, Option as It, SiteDefinition as J, ContentMigration as Jt, SiteConfig as K, ShowCondition as Kt, DEFAULT_MAX_FOOTER_COLUMNS as L, StringOption as Lt, ThemeDefinition as M, BooleanOption as Mt, ThemeFont as N, CountRule as Nt, API_PREFIX as O, defineWireframe as Ot, defaultTheme as P, EnumOption as Pt, Theme as Q, SCHEMA_VERSION_KEY as Qt, DEFAULT_MAX_HEADER_ACTIONS as R, buttonStyles as Rt, jsonLdSchema as S, SectionConfig as St, parseJsonLdInput as T, WireKind as Tt, HeaderConfig as U, variantOption as Ut, FooterConfig as V, toneOption as Vt, Site as W, FieldChoices as Wt, SiteSeo as X, ContentVersioning as Xt, SiteOf as Y, ContentMigrator as Yt, SiteWith as Z, DocumentKind as Zt, SiteJsonLdSource as _, textMarkSchema as _t, isSystemPage as a, themeSchema as at, hasJsonLdId as b, trackingIdSchema as bt, BaseSection as c, Link as ct, anchorSchema as d, Text as dt, defineSite as et, createSectionSchema as f, Tone as ft, SiteJsonLdIds as g, richTextSchema as gt, JsonLdResult as h, linkSchema as ht, createPageSchema as i, themeColorsSchema as it, ThemeConfig as j, OptionalContent as jt, ContentModel as k, wireKinds as kt, PropsOf as l, MAX_NAV_DEPTH as lt, JsonLdBlock as m, imageSchema as mt, SYSTEM_PAGES as n, siteConsentSchema as nt, seoSchema as o, ButtonStyle as ot, sectionIdSchema as p, htmlIdSchema as pt, SiteConsent as q, ShowWhen as qt, Seo as r, siteSeoSchema as rt, withoutOrphanSections as s, Image as st, Page as t, siteAnalyticsSchema as tt, SectionOf as u, RichText as ut, formatJsonLd as v, textSchema as vt, mergeJsonLd as w, defineSection as wt, isPlaceholderSiteUrl as x, withEmphasis as xt, generateSiteJsonLd as y, toneSchema as yt, Footer as z, motionOption as zt };
1405
+ export { Theme as $, SCHEMA_VERSION_KEY as $t, ContentModel as A, wireKinds as At, Footer as B, motionOption as Bt, jsonLdSchema as C, SectionConfig as Ct, siteJsonLdIds as D, WireRect as Dt, parseJsonLdInput as E, WireKind as Et, defaultTheme as F, EnumOption as Ft, Site as G, FieldChoices as Gt, FooterConfig as H, toneOption as Ht, defineTheme as I, NumberOption as It, SiteConsent as J, ShowWhen as Jt, SiteAnalytics as K, FieldIcons as Kt, BRAND_LOGO_HEIGHT as L, Option as Lt, ThemeConfig as M, OptionalContent as Mt, ThemeDefinition as N, BooleanOption as Nt, upsertJsonLd as O, Wireframe as Ot, ThemeFont as P, CountRule as Pt, SiteWith as Q, DocumentKind as Qt, DEFAULT_MAX_FOOTER_COLUMNS as R, StringOption as Rt, isPlaceholderSiteUrl as S, withEmphasis as St, mergeJsonLd as T, defineSection as Tt, Header as U, tones as Ut, FooterColumn as V, themeModes as Vt, HeaderConfig as W, variantOption as Wt, SiteOf as X, ContentMigrator as Xt, SiteDefinition as Y, ContentMigration as Yt, SiteSeo as Z, ContentVersioning as Zt, SiteJsonLdIds as _, richTextSchema as _t, createPageSchema as a, themeColorsSchema as at, generateSiteJsonLd as b, toneSchema as bt, withoutOrphanSections as c, Image as ct, SectionOf as d, RichText as dt, createMigrator as en, brandLogoSchema as et, anchorSchema as f, Text as ft, JsonLdResult as g, linkSchema as gt, JsonLdBlock as h, imageSchema as ht, Seo as i, siteSeoSchema as it, SectionRegistry as j, wireframeIssues as jt, API_PREFIX as k, defineWireframe as kt, BaseSection as l, Link as lt, sectionIdSchema as m, htmlIdSchema as mt, PageRules as n, siteAnalyticsSchema as nt, isSystemPage as o, themeSchema as ot, createSectionSchema as p, Tone as pt, SiteConfig as q, ShowCondition as qt, SYSTEM_PAGES as r, siteConsentSchema as rt, seoSchema as s, ButtonStyle as st, Page as t, defineSite as tt, PropsOf as u, MAX_NAV_DEPTH as ut, SiteJsonLdSource as v, textMarkSchema as vt, jsonLdWarnings as w, SectionDefinition as wt, hasJsonLdId as x, trackingIdSchema as xt, formatJsonLd as y, textSchema as yt, DEFAULT_MAX_HEADER_ACTIONS as z, buttonStyles as zt };
@@ -503,6 +503,22 @@ const seoSchema = z.object({
503
503
  * and refuses to create, delete, rename or promote them to the home page.
504
504
  */
505
505
  const SYSTEM_PAGES = ["404"];
506
+ const DEFAULT_PAGE_RULES = {
507
+ rename: true,
508
+ delete: true
509
+ };
510
+ /** Check the `pages` option and fill in its defaults. */
511
+ function resolvePageRules(input) {
512
+ if (input === void 0) return DEFAULT_PAGE_RULES;
513
+ for (const [key, value] of Object.entries(input)) {
514
+ if (key !== "rename" && key !== "delete") throw new Error(`bearminion(): unknown option pages.${key}. Use pages.rename or pages.delete.`);
515
+ if (typeof value !== "boolean") throw new Error(`bearminion(): pages.${key} must be true or false.`);
516
+ }
517
+ return {
518
+ rename: input.rename ?? true,
519
+ delete: input.delete ?? true
520
+ };
521
+ }
506
522
  function isSystemPage(slug) {
507
523
  return SYSTEM_PAGES.includes(slug);
508
524
  }
@@ -547,4 +563,4 @@ function withoutOrphanSections(page, registry) {
547
563
  };
548
564
  }
549
565
  //#endregion
550
- export { textSchema as A, withImageLayout as B, MAX_NAV_DEPTH as C, linkSchema as D, imageSchema as E, DEFAULT_IMAGE_POSITION as F, tones as G, motionOption as H, IMAGE_FITS as I, variantOption as K, IMAGE_POSITIONS as L, trackingIdSchema as M, withEmphasis as N, richTextSchema as O, DEFAULT_IMAGE_FIT as P, isImageFit as R, upsertJsonLd as S, htmlIdSchema as T, themeModes as U, buttonStyles as V, toneOption as W, jsonLdSchema as _, seoSchema as a, parseJsonLdInput as b, anchorSchema as c, sectionIdSchema as d, walkLinkIds as f, isPlaceholderSiteUrl as g, hasJsonLdId as h, isSystemPage as i, toneSchema as j, textMarkSchema as k, createSectionSchema as l, generateSiteJsonLd as m, createPageSchema as n, slugSchema as o, formatJsonLd as p, createTolerantPageSchema as r, withoutOrphanSections as s, SYSTEM_PAGES as t, isOrphanSection as u, jsonLdWarnings as v, addMarkIssues as w, siteJsonLdIds as x, mergeJsonLd as y, isImagePosition as z };
566
+ export { textMarkSchema as A, isImagePosition as B, upsertJsonLd as C, imageSchema as D, htmlIdSchema as E, DEFAULT_IMAGE_FIT as F, toneOption as G, buttonStyles as H, DEFAULT_IMAGE_POSITION as I, tones as K, IMAGE_FITS as L, toneSchema as M, trackingIdSchema as N, linkSchema as O, withEmphasis as P, IMAGE_POSITIONS as R, siteJsonLdIds as S, addMarkIssues as T, motionOption as U, withImageLayout as V, themeModes as W, isPlaceholderSiteUrl as _, resolvePageRules as a, mergeJsonLd as b, withoutOrphanSections as c, isOrphanSection as d, sectionIdSchema as f, hasJsonLdId as g, generateSiteJsonLd as h, isSystemPage as i, textSchema as j, richTextSchema as k, anchorSchema as l, formatJsonLd as m, createPageSchema as n, seoSchema as o, walkLinkIds as p, variantOption as q, createTolerantPageSchema as r, slugSchema as s, SYSTEM_PAGES as t, createSectionSchema as u, jsonLdSchema as v, MAX_NAV_DEPTH as w, parseJsonLdInput as x, jsonLdWarnings as y, isImageFit as z };
@@ -1,4 +1,4 @@
1
- import { r as fieldKey } from "./theme-Dv7_7B56.js";
1
+ import { r as fieldKey } from "./theme-BvqJ8UnS.js";
2
2
  //#region src/errors.ts
3
3
  function formatContentIssues(issues) {
4
4
  return issues.map((issue) => {
@@ -1,4 +1,4 @@
1
- import { i as isInside } from "./security-BA9KzK-2.js";
1
+ import { i as isInside } from "./security-FLvgc2jD.js";
2
2
  import path from "node:path";
3
3
  //#region src/reload.ts
4
4
  const RELOAD_DELAY_MS = 50;
@@ -1,4 +1,4 @@
1
- import { o as slugSchema } from "./page-X-WnOu7-.js";
1
+ import { s as slugSchema } from "./page-wlcQJAA-.js";
2
2
  import { t as DEFAULT_IMAGE_BYTE_LIMIT } from "./upload-rules-Cao9uY5K.js";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
@@ -1,4 +1,4 @@
1
- import { G as tones, U as themeModes, V as buttonStyles } from "./page-X-WnOu7-.js";
1
+ import { H as buttonStyles, K as tones, W as themeModes } from "./page-wlcQJAA-.js";
2
2
  import { i as fontMarks } from "./marks-DPBilumg.js";
3
3
  //#region src/field-rules.ts
4
4
  /**
package/dist/ui/mount.js CHANGED
@@ -1,5 +1,5 @@
1
- import { a as sectionFieldKey, i as isPropShown, t as defaultTheme } from "../theme-Dv7_7B56.js";
2
- import { B as withImageLayout, F as DEFAULT_IMAGE_POSITION, I as IMAGE_FITS, L as IMAGE_POSITIONS, P as DEFAULT_IMAGE_FIT, R as isImageFit, S as upsertJsonLd, b as parseJsonLdInput, g as isPlaceholderSiteUrl, i as isSystemPage, m as generateSiteJsonLd, p as formatJsonLd, v as jsonLdWarnings, z as isImagePosition } from "../page-X-WnOu7-.js";
1
+ import { a as sectionFieldKey, i as isPropShown, t as defaultTheme } from "../theme-BvqJ8UnS.js";
2
+ import { B as isImagePosition, C as upsertJsonLd, F as DEFAULT_IMAGE_FIT, I as DEFAULT_IMAGE_POSITION, L as IMAGE_FITS, R as IMAGE_POSITIONS, V as withImageLayout, _ as isPlaceholderSiteUrl, h as generateSiteJsonLd, i as isSystemPage, m as formatJsonLd, x as parseJsonLdInput, y as jsonLdWarnings, z as isImageFit } from "../page-wlcQJAA-.js";
3
3
  import { d as reconcileMarks, f as renderMarkedHtml, i as fontMarks, l as marksFromEmphasis, t as applyTextMark } from "../marks-DPBilumg.js";
4
4
  import { _ as consentCopy, b as parseMediaSource, c as hasThemeColors, d as tokenToHex, f as CONSENT_COPY, h as CONSENT_LIMITS, i as contrastChecks, n as HEX_COLOR, o as derivePalette, r as OVERRIDE_TOKENS, s as hasOverrides, t as DEFAULT_BRAND, u as themeCss, v as consentTextIssues } from "../theme-colors-CHROGZkI.js";
5
5
  import { n as formatBytes, t as DEFAULT_IMAGE_BYTE_LIMIT } from "../upload-rules-Cao9uY5K.js";
@@ -948,8 +948,32 @@ function navHeight(link) {
948
948
  for (const child of children) max = Math.max(max, 1 + navHeight(child));
949
949
  return max;
950
950
  }
951
+ /** Letters that do not decompose into a base letter and an accent, with the plain letters they are written as. */
952
+ const PLAIN_LETTERS = {
953
+ ł: "l",
954
+ đ: "d",
955
+ ø: "o",
956
+ ð: "d",
957
+ þ: "th",
958
+ ß: "ss",
959
+ æ: "ae",
960
+ œ: "oe",
961
+ ı: "i"
962
+ };
963
+ /**
964
+ * A lowercase ASCII slug: accents are dropped (`ą` is `a`, `é` is `e`), letters with no accent form are written plainly
965
+ * (`ł` is `l`, `ß` is `ss`), and every other run of characters becomes one hyphen.
966
+ */
951
967
  function slugifyAnchor(value) {
952
- return value.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
968
+ return value.toLowerCase().normalize("NFKD").replace(/\p{M}+/gu, "").replace(/[łđøðþßæœı]/g, (letter) => PLAIN_LETTERS[letter] ?? letter).replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
969
+ }
970
+ /**
971
+ * The slug to offer for a new page titled `title`: the title as a slug, made unique among `taken`. Empty when the
972
+ * title has no letters or digits, so the editor does not offer a slug that says nothing.
973
+ */
974
+ function suggestPageSlug(title, taken) {
975
+ const stem = slugifyAnchor(title);
976
+ return stem === "" ? "" : uniqueAnchor(stem, taken);
953
977
  }
954
978
  function uniqueAnchor(base, taken) {
955
979
  const stem = slugifyAnchor(base) || "section";
@@ -22413,7 +22437,7 @@ function SeoCard({ page, siteName, siteUrl, siteOgImage, system, onEdit }) {
22413
22437
  }
22414
22438
  //#endregion
22415
22439
  //#region src/ui/forms/page-form.tsx
22416
- function PageForm({ page, labels, siteName, siteUrl, siteOgImage, selectedId, onChange, savedSlug, onHomeChange, onEditSeo, onSelectSection, onMoveSection, onReorderSections, onDuplicateSection, onRemoveSection, onAddSection }) {
22440
+ function PageForm({ page, labels, siteName, siteUrl, siteOgImage, selectedId, onChange, savedSlug, canRename, onHomeChange, onEditSeo, onSelectSection, onMoveSection, onReorderSections, onDuplicateSection, onRemoveSection, onAddSection }) {
22417
22441
  const [sectionDrag, setSectionDrag] = useState(null);
22418
22442
  const isHome = page.slug === "index";
22419
22443
  const isSystem = isSystemPage(page.slug);
@@ -22443,9 +22467,9 @@ function PageForm({ page, labels, siteName, siteUrl, siteOgImage, selectedId, on
22443
22467
  ...page,
22444
22468
  slug: value
22445
22469
  }),
22446
- disabled: isHome || isSystem,
22447
- mono: isHome || isSystem,
22448
- hint: isHome ? "The home page is served at / and keeps the slug index." : isSystem ? "A system page: the site serves it for unknown addresses, so its slug is fixed and it stays out of search results." : void 0
22470
+ disabled: isHome || isSystem || !canRename,
22471
+ mono: isHome || isSystem || !canRename,
22472
+ hint: isHome ? "The home page is served at / and keeps the slug index." : isSystem ? "A system page: the site serves it for unknown addresses, so its slug is fixed and it stays out of search results." : canRename ? void 0 : "Renaming pages is turned off for this site, so this address stays as it is."
22449
22473
  }),
22450
22474
  !isSystem && /* @__PURE__ */ jsxs("label", {
22451
22475
  class: "bm-switch-row",
@@ -22455,14 +22479,14 @@ function PageForm({ page, labels, siteName, siteUrl, siteOgImage, selectedId, on
22455
22479
  class: "bm-switch-title",
22456
22480
  children: ["Home page", /* @__PURE__ */ jsx(Info, {
22457
22481
  label: "About Home page",
22458
- text: savedHome ? "Set another page as home to move this one." : isHome ? "Becomes the home page when you save." : "Serve this page at / instead of its own URL."
22482
+ text: !canRename ? "Renaming pages is turned off for this site, and making a page home moves the old home page to a new address." : savedHome ? "Set another page as home to move this one." : isHome ? "Becomes the home page when you save." : "Serve this page at / instead of its own URL."
22459
22483
  })]
22460
22484
  })
22461
22485
  }), /* @__PURE__ */ jsx("input", {
22462
22486
  type: "checkbox",
22463
22487
  role: "switch",
22464
22488
  checked: isHome,
22465
- disabled: savedHome,
22489
+ disabled: savedHome || !canRename,
22466
22490
  onChange: (event) => onHomeChange(event.currentTarget.checked)
22467
22491
  })]
22468
22492
  })
@@ -22651,9 +22675,13 @@ function PageForm({ page, labels, siteName, siteUrl, siteOgImage, selectedId, on
22651
22675
  }
22652
22676
  //#endregion
22653
22677
  //#region src/ui/forms/pages-form.tsx
22654
- function PagesForm({ pages, labels, current, homeSlug, onCreated, onNavigate }) {
22655
- const [slug, setSlug] = useState("notes");
22678
+ function PagesForm({ pages, labels, current, homeSlug, canDelete, onCreated, onNavigate }) {
22679
+ const taken = new Set(pages.map((item) => item.slug));
22656
22680
  const [title, setTitle] = useState("Notes");
22681
+ const [slug, setSlug] = useState(() => suggestPageSlug("Notes", taken));
22682
+ /** True once the slug was typed by hand: from then on the title no longer changes it. */
22683
+ const [slugTyped, setSlugTyped] = useState(false);
22684
+ const [error, setError] = useState("");
22657
22685
  const [template, setTemplate] = useState("hero");
22658
22686
  const [creating, setCreating] = useState(false);
22659
22687
  return /* @__PURE__ */ jsxs("div", {
@@ -22711,7 +22739,7 @@ function PagesForm({ pages, labels, current, homeSlug, onCreated, onNavigate })
22711
22739
  class: "bm-badge bm-badge-on",
22712
22740
  children: "editing"
22713
22741
  }),
22714
- item.slug !== "index" && item.slug !== current && !item.system && /* @__PURE__ */ jsx("button", {
22742
+ canDelete && item.slug !== "index" && item.slug !== current && !item.system && /* @__PURE__ */ jsx("button", {
22715
22743
  type: "button",
22716
22744
  class: "bm-icon-btn bm-danger",
22717
22745
  "aria-label": `Delete ${item.title}`,
@@ -22730,15 +22758,23 @@ function PagesForm({ pages, labels, current, homeSlug, onCreated, onNavigate })
22730
22758
  creating && /* @__PURE__ */ jsxs("div", {
22731
22759
  class: "bm-card",
22732
22760
  children: [
22733
- /* @__PURE__ */ jsx(Field, {
22734
- label: "New slug",
22735
- value: slug,
22736
- onChange: setSlug
22737
- }),
22738
22761
  /* @__PURE__ */ jsx(Field, {
22739
22762
  label: "New title",
22740
22763
  value: title,
22741
- onChange: setTitle
22764
+ onChange: (value) => {
22765
+ setTitle(value);
22766
+ if (!slugTyped) setSlug(suggestPageSlug(value, taken));
22767
+ }
22768
+ }),
22769
+ /* @__PURE__ */ jsx(Field, {
22770
+ label: "New slug",
22771
+ value: slug,
22772
+ mono: true,
22773
+ hint: "The page address. Made from the title until you change it, and the title never changes it afterwards.",
22774
+ onChange: (value) => {
22775
+ setSlug(value);
22776
+ setSlugTyped(true);
22777
+ }
22742
22778
  }),
22743
22779
  /* @__PURE__ */ jsxs("label", {
22744
22780
  class: "bm-label",
@@ -22754,16 +22790,23 @@ function PagesForm({ pages, labels, current, homeSlug, onCreated, onNavigate })
22754
22790
  /* @__PURE__ */ jsx("button", {
22755
22791
  type: "button",
22756
22792
  class: "bm-primary",
22793
+ disabled: slug === "",
22757
22794
  onClick: () => {
22795
+ setError("");
22758
22796
  createPage({
22759
22797
  slug,
22760
22798
  title,
22761
22799
  template
22762
22800
  }).then((result) => {
22763
22801
  if (result.ok) onNavigate(pageHref(slug));
22802
+ else setError(result.status === 0 ? "Could not create the page." : result.message);
22764
22803
  });
22765
22804
  },
22766
22805
  children: "Create page"
22806
+ }),
22807
+ error && /* @__PURE__ */ jsx("p", {
22808
+ class: "bm-error",
22809
+ children: error
22767
22810
  })
22768
22811
  ]
22769
22812
  })
@@ -23178,6 +23221,7 @@ function PagesPanel({ catalog }) {
23178
23221
  labels: catalog.sectionLabels,
23179
23222
  current: savedSlug,
23180
23223
  homeSlug: page && page.slug === "index" ? savedSlug : "index",
23224
+ canDelete: catalog.pageRules?.delete !== false,
23181
23225
  onCreated: () => void session.load(doc.savedSlug.peek()),
23182
23226
  onNavigate: session.requestLeave
23183
23227
  }), page && /* @__PURE__ */ jsx(PageForm, {
@@ -23189,6 +23233,7 @@ function PagesPanel({ catalog }) {
23189
23233
  selectedId: ui.selectedId.value,
23190
23234
  onChange: (next) => edits.updatePage(next),
23191
23235
  savedSlug,
23236
+ canRename: catalog.pageRules?.rename !== false,
23192
23237
  onHomeChange: session.setHome,
23193
23238
  onEditSeo: () => {
23194
23239
  ui.dialog.value = { kind: "seo" };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bearminion",
3
- "version": "1.11.0",
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",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "template": "default",
4
- "version": "1.11.0",
4
+ "version": "1.13.0",
5
5
  "files": {
6
6
  "src/components/atoms/Button.astro": {
7
7
  "hash": "7be42b3dc3a3b59bec169de32a9d801904689e2705473d1945724658dc799043",