bearminion 1.14.0 → 1.16.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.
@@ -0,0 +1,735 @@
1
+ import { r as fieldKey } from "./theme-BvqJ8UnS.js";
2
+ import { n as createPageSchema, r as createTolerantPageSchema, s as slugSchema } from "./page-wlcQJAA-.js";
3
+ import { z } from "zod";
4
+ import { fromMarkdown } from "mdast-util-from-markdown";
5
+ import { gfmFromMarkdown } from "mdast-util-gfm";
6
+ import { gfm } from "micromark-extension-gfm";
7
+ import { Scalar, isAlias, isMap, isNode, isScalar, isSeq, parseDocument } from "yaml";
8
+ //#region src/errors.ts
9
+ function formatContentIssues(issues) {
10
+ return issues.map((issue) => {
11
+ return ` - ${issue.path.length > 0 ? issue.path.map(String).join(".") : "(root)"}: ${issue.message}`;
12
+ }).join("\n");
13
+ }
14
+ /** Base error for content that cannot be loaded. `filePath` is the file or directory involved. */
15
+ var ContentError = class extends Error {
16
+ filePath;
17
+ constructor(filePath, message) {
18
+ super(message);
19
+ this.name = new.target.name;
20
+ this.filePath = filePath;
21
+ }
22
+ };
23
+ /** `site.json` or a page file failed schema validation. */
24
+ var ContentValidationError = class extends ContentError {
25
+ issues;
26
+ constructor(filePath, issues) {
27
+ super(filePath, `Invalid content in ${filePath}:\n${formatContentIssues(issues)}`);
28
+ this.issues = issues;
29
+ }
30
+ };
31
+ /** A content file or directory is missing, unreadable, or not valid JSON. */
32
+ var ContentReadError = class extends ContentError {};
33
+ //#endregion
34
+ //#region src/section-fields.ts
35
+ const WRAPPERS = /* @__PURE__ */ new Set([
36
+ "optional",
37
+ "nullable",
38
+ "default",
39
+ "prefault",
40
+ "readonly",
41
+ "catch",
42
+ "nonoptional"
43
+ ]);
44
+ function defOf(schema) {
45
+ return schema._zod.def;
46
+ }
47
+ /** Strips optional, default, transforms and the like down to the schema that holds the data. */
48
+ function unwrap(schema) {
49
+ let current = schema;
50
+ for (let depth = 0; depth < 16; depth++) {
51
+ const def = defOf(current);
52
+ if (def.type === "pipe" && def.in) current = def.in;
53
+ else if (WRAPPERS.has(def.type) && def.innerType) current = def.innerType;
54
+ else return current;
55
+ }
56
+ return current;
57
+ }
58
+ /** Top-level prop names of a section schema. Empty when `props` is not an object. */
59
+ function schemaProps(schema) {
60
+ const def = defOf(unwrap(schema));
61
+ return def.type === "object" && def.shape ? Object.keys(def.shape) : [];
62
+ }
63
+ /**
64
+ * Every string enum inside a section's props, by field key (`kind`, `steps[].icon`).
65
+ * The sidebar offers these as choices instead of a free text box.
66
+ */
67
+ function enumFields(schema) {
68
+ const found = {};
69
+ const visit = (node, path) => {
70
+ const def = defOf(unwrap(node));
71
+ if (def.type === "enum" && def.entries) {
72
+ const values = Object.values(def.entries);
73
+ if (path !== "" && values.every((value) => typeof value === "string")) found[fieldKey(path)] = values;
74
+ return;
75
+ }
76
+ if (def.type === "array" && def.element) visit(def.element, `${path}.0`);
77
+ else if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) visit(child, path === "" ? key : `${path}.${key}`);
78
+ };
79
+ visit(schema, "");
80
+ return found;
81
+ }
82
+ /**
83
+ * Every image inside a section's props (an object with `src` and `alt`), by field key (`poster`, `items[].image`).
84
+ * The sidebar offers an image slot for these even while the prop is missing, whatever the prop is called.
85
+ */
86
+ function imageFields(schema) {
87
+ const found = [];
88
+ const visit = (node, path) => {
89
+ const def = defOf(unwrap(node));
90
+ if (def.type === "array" && def.element) visit(def.element, `${path}.0`);
91
+ else if (def.type === "object" && def.shape) {
92
+ if (path !== "" && "src" in def.shape && "alt" in def.shape) {
93
+ found.push(fieldKey(path));
94
+ return;
95
+ }
96
+ for (const [key, child] of Object.entries(def.shape)) visit(child, path === "" ? key : `${path}.${key}`);
97
+ }
98
+ };
99
+ visit(schema, "");
100
+ return found;
101
+ }
102
+ //#endregion
103
+ //#region src/preview.ts
104
+ /**
105
+ * Declare a theme's preview renderer. Default-export it from the module named by `previewModule`
106
+ * (default `/src/lib/render-preview.ts`). The model type ties the inputs to your section registry and site:
107
+ *
108
+ * ```ts
109
+ * export default defineThemePreview<typeof contentModel>({
110
+ * async page({ sections, motion }) { ... },
111
+ * async site({ site, pathname }) { ... },
112
+ * })
113
+ * ```
114
+ */
115
+ function defineThemePreview(preview) {
116
+ if (typeof preview?.page !== "function") throw new TypeError("defineThemePreview needs a `page` function.");
117
+ if (preview.site !== void 0 && typeof preview.site !== "function") throw new TypeError("defineThemePreview: `site` must be a function when given.");
118
+ return preview;
119
+ }
120
+ /** The theme has no renderer for this preview. The API answers 501 instead of 500. */
121
+ var PreviewUnavailableError = class extends Error {};
122
+ /** Load the preview module through the Vite SSR runner and check it default-exports a preview. */
123
+ async function loadThemePreview(environment, previewModule) {
124
+ const runner = environment.runner;
125
+ if (!runner?.import) throw new PreviewUnavailableError("The SSR dev environment cannot render a preview.");
126
+ const preview = (await runner.import(previewModule))?.default;
127
+ if (!preview || typeof preview.page !== "function") throw new Error(`${previewModule} must default-export defineThemePreview({ page, site? }).`);
128
+ return preview;
129
+ }
130
+ //#endregion
131
+ //#region src/entry-blocks.ts
132
+ const EDITABLE = /* @__PURE__ */ new Set([
133
+ "paragraph",
134
+ "heading",
135
+ "list",
136
+ "blockquote",
137
+ "code",
138
+ "thematicBreak",
139
+ "table"
140
+ ]);
141
+ const OPAQUE_INSIDE = /* @__PURE__ */ new Set([
142
+ "html",
143
+ "footnoteReference",
144
+ "footnoteDefinition",
145
+ "linkReference",
146
+ "imageReference",
147
+ "definition",
148
+ "yaml",
149
+ "toml",
150
+ "math",
151
+ "inlineMath"
152
+ ]);
153
+ function textOf(node) {
154
+ if ("value" in node && typeof node.value === "string") return node.value;
155
+ if ("children" in node) return node.children.map(textOf).join("");
156
+ return "";
157
+ }
158
+ function holdsOpaque(node) {
159
+ if (OPAQUE_INSIDE.has(node.type)) return true;
160
+ if ("children" in node) return node.children.some(holdsOpaque);
161
+ return false;
162
+ }
163
+ function isEditable(node, raw, options) {
164
+ if (!EDITABLE.has(node.type)) return false;
165
+ if (holdsOpaque(node)) return false;
166
+ if (node.type === "paragraph" && /^:{2,}/m.test(raw)) return false;
167
+ if (options.mdx && node.type !== "code") {
168
+ const text = textOf(node);
169
+ if (/^\s*(?:import|export)\s/.test(raw) || /[{}<]/.test(text) || /[{<]/.test(raw)) return false;
170
+ }
171
+ return true;
172
+ }
173
+ /** Parses a body (the text after the frontmatter). `body === joinBody(parseBody(body))`. */
174
+ function parseBody(body, options = {}) {
175
+ const eol = body.includes("\r\n") ? "\r\n" : "\n";
176
+ const tree = fromMarkdown(body, {
177
+ extensions: [gfm()],
178
+ mdastExtensions: [gfmFromMarkdown()]
179
+ });
180
+ const blocks = [];
181
+ let cursor = 0;
182
+ for (const node of tree.children) {
183
+ const start = node.position?.start.offset;
184
+ const end = node.position?.end.offset;
185
+ if (start === void 0 || end === void 0) continue;
186
+ const raw = body.slice(start, end);
187
+ blocks.push({
188
+ id: `b${blocks.length}`,
189
+ type: node.type,
190
+ raw,
191
+ leading: body.slice(cursor, start),
192
+ editable: isEditable(node, raw, options)
193
+ });
194
+ cursor = end;
195
+ }
196
+ return {
197
+ blocks,
198
+ trailing: body.slice(cursor),
199
+ eol
200
+ };
201
+ }
202
+ function withEol$1(text, eol) {
203
+ return eol === "\n" ? text : text.replace(/\r?\n/g, eol);
204
+ }
205
+ /**
206
+ * Rebuilds the body from `edits`, the blocks in their new order.
207
+ *
208
+ * - `{ id }`: the original text, byte for byte.
209
+ * - `{ id, markdown }`: the block replaced by `markdown`.
210
+ * - `{ markdown }`: a new block.
211
+ *
212
+ * Whitespace between two blocks that were already neighbours is kept. Around anything moved, inserted or after a
213
+ * deletion it is one blank line. The first block keeps the body's original leading whitespace and the body keeps its
214
+ * trailing whitespace, so deleting the first block or appending a block does not disturb the rest.
215
+ */
216
+ function applyBlocks(parsed, edits) {
217
+ const known = new Map(parsed.blocks.map((block, index) => [block.id, {
218
+ block,
219
+ index
220
+ }]));
221
+ const blank = parsed.eol + parsed.eol;
222
+ const firstLeading = parsed.blocks[0]?.leading ?? "";
223
+ let out = "";
224
+ let previous = null;
225
+ edits.forEach((edit, position) => {
226
+ const original = edit.id === void 0 ? void 0 : known.get(edit.id);
227
+ if (edit.id !== void 0 && !original) throw new Error(`Unknown block id "${edit.id}".`);
228
+ const text = edit.markdown === void 0 ? original?.block.raw ?? "" : withEol$1(edit.markdown, parsed.eol).replace(/(?:\r?\n)+$/, "");
229
+ const neighbour = original !== void 0 && previous !== null && original.index === previous + 1;
230
+ const leading = position === 0 ? firstLeading : neighbour ? original?.block.leading ?? blank : blank;
231
+ out += leading + text;
232
+ previous = original ? original.index : null;
233
+ });
234
+ if (parsed.blocks.length === 0 && out !== "") return out + (parsed.trailing === "" ? parsed.eol : parsed.trailing);
235
+ return out + parsed.trailing;
236
+ }
237
+ //#endregion
238
+ //#region src/entry-source.ts
239
+ var EntryError = class extends Error {
240
+ code;
241
+ constructor(code, message) {
242
+ super(message);
243
+ this.code = code;
244
+ this.name = "EntryError";
245
+ }
246
+ };
247
+ const OPEN = /^---[ \t]*\r?\n/;
248
+ /** Cuts an entry into parts. `joinEntry(splitEntry(source))` is `source`, byte for byte. */
249
+ function splitEntry(source) {
250
+ const bom = source.startsWith("") ? "" : "";
251
+ const text = source.slice(bom.length);
252
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
253
+ const open = OPEN.exec(text);
254
+ if (!open) return {
255
+ bom,
256
+ eol,
257
+ head: "",
258
+ frontmatter: "",
259
+ tail: "",
260
+ body: text
261
+ };
262
+ let position = open[0].length;
263
+ while (position <= text.length) {
264
+ const lineEnd = text.indexOf("\n", position);
265
+ const end = lineEnd === -1 ? text.length : lineEnd + 1;
266
+ const line = text.slice(position, end).replace(/\r?\n$/, "");
267
+ if (/^---[ \t]*$/.test(line)) return {
268
+ bom,
269
+ eol,
270
+ head: open[0],
271
+ frontmatter: text.slice(open[0].length, position),
272
+ tail: text.slice(position, end),
273
+ body: text.slice(end)
274
+ };
275
+ if (lineEnd === -1) break;
276
+ position = end;
277
+ }
278
+ return {
279
+ bom,
280
+ eol,
281
+ head: "",
282
+ frontmatter: "",
283
+ tail: "",
284
+ body: text
285
+ };
286
+ }
287
+ function joinEntry(parts) {
288
+ return parts.bom + parts.head + parts.frontmatter + parts.tail + parts.body;
289
+ }
290
+ function hasFrontmatter(parts) {
291
+ return parts.head !== "";
292
+ }
293
+ function mapOf(document, source) {
294
+ if (document.errors.length > 0) throw new EntryError("invalid_frontmatter", `The frontmatter is not valid YAML: ${document.errors[0]?.message ?? ""}`);
295
+ if (document.contents === null) return null;
296
+ if (!isMap(document.contents)) throw new EntryError("invalid_frontmatter", "The frontmatter is not a mapping.");
297
+ if (/^[ \t]*<<[ \t]*:/m.test(source)) throw new EntryError("read_only_field", "The frontmatter uses merge keys; edit it by hand.");
298
+ return document.contents;
299
+ }
300
+ /** Where a pair's value ends in the source (the key's end when the value is empty). */
301
+ function valueEnd(pair) {
302
+ const value = pair.value;
303
+ if (value && isNode(value) && value.range) return value.range[1];
304
+ const key = pair.key;
305
+ return isNode(key) && key.range ? key.range[1] : 0;
306
+ }
307
+ function findPair(map, key) {
308
+ return map.items.find((pair) => isScalar(pair.key) && pair.key.value === key);
309
+ }
310
+ /**
311
+ * The frontmatter as a plain object, read the way Astro reads it: YAML 1.2 plus timestamps, so `2026-01-05` is a
312
+ * Date. Returns `{}` when the frontmatter is empty.
313
+ */
314
+ function readFields(frontmatter) {
315
+ const document = parseDocument(frontmatter, { customTags: ["timestamp"] });
316
+ if (!mapOf(document, frontmatter)) return {};
317
+ return document.toJS() ?? {};
318
+ }
319
+ function detectIndent(source) {
320
+ const match = /^( +)\S/m.exec(source);
321
+ return match ? Math.min(Math.max(match[1]?.length ?? 2, 2), 8) : 2;
322
+ }
323
+ function withEol(text, eol) {
324
+ return eol === "\n" ? text : text.replace(/\n/g, eol);
325
+ }
326
+ /** Serializes `key: value` the way the field was already written (quote style, flow collections). */
327
+ function serializePair(key, value, previous, indent) {
328
+ const holder = parseDocument("{}");
329
+ holder.contents = holder.createNode({ [key]: value });
330
+ const node = holder.contents.items[0]?.value;
331
+ const before = previous?.value;
332
+ if (isScalar(node) && isScalar(before) && typeof value === "string") {
333
+ if (before.type === Scalar.QUOTE_DOUBLE || before.type === Scalar.QUOTE_SINGLE) node.type = before.type;
334
+ } else if (isSeq(node) && isSeq(before)) node.flow = before.flow;
335
+ else if (isMap(node) && isMap(before)) node.flow = before.flow;
336
+ const mapNode = holder.contents;
337
+ mapNode.flow = false;
338
+ return holder.toString({
339
+ lineWidth: 0,
340
+ indent
341
+ }).replace(/\r?\n$/, "");
342
+ }
343
+ /**
344
+ * Sets one top-level key. Only that key's own text changes; a new key is appended. Throws `EntryError`
345
+ * (`read_only_field`) for a key defined through an anchor, alias or merge key, and `invalid_frontmatter` when the
346
+ * frontmatter is not a YAML mapping.
347
+ */
348
+ function setField(frontmatter, key, value, eol = "\n") {
349
+ const map = mapOf(parseDocument(frontmatter), frontmatter);
350
+ const indent = detectIndent(frontmatter);
351
+ const pair = map ? findPair(map, key) : void 0;
352
+ if (!pair) {
353
+ const added = withEol(serializePair(key, value, void 0, indent), eol);
354
+ return `${frontmatter}${frontmatter === "" || frontmatter.endsWith("\n") ? "" : eol}${added}${eol}`;
355
+ }
356
+ const keyNode = pair.key;
357
+ const valueNode = pair.value;
358
+ if (isAlias(valueNode) || (isScalar(valueNode) || isMap(valueNode) || isSeq(valueNode) ? valueNode.anchor : false)) throw new EntryError("read_only_field", `"${key}" uses a YAML anchor or alias; edit it by hand.`);
359
+ if (!isScalar(keyNode) || !keyNode.range) throw new EntryError("invalid_frontmatter", `Cannot locate "${key}".`);
360
+ const start = keyNode.range[0];
361
+ let end = valueEnd(pair);
362
+ while (end > start && /\s/.test(frontmatter.charAt(end - 1))) end--;
363
+ const replacement = withEol(serializePair(key, value, pair, indent), eol);
364
+ return frontmatter.slice(0, start) + replacement + frontmatter.slice(end);
365
+ }
366
+ /** Removes one top-level key and the rest of its line. Comment lines above it stay. */
367
+ function removeField(frontmatter, key) {
368
+ const map = mapOf(parseDocument(frontmatter), frontmatter);
369
+ const pair = map ? findPair(map, key) : void 0;
370
+ if (!pair || !isScalar(pair.key) || !pair.key.range) return frontmatter;
371
+ const valueNode = pair.value;
372
+ if (isAlias(valueNode)) throw new EntryError("read_only_field", `"${key}" is an alias; edit it by hand.`);
373
+ const start = frontmatter.lastIndexOf("\n", pair.key.range[0] - 1) + 1;
374
+ let end = valueEnd(pair);
375
+ while (end > start && /\s/.test(frontmatter.charAt(end - 1))) end--;
376
+ const lineEnd = frontmatter.indexOf("\n", end);
377
+ return frontmatter.slice(0, start) + (lineEnd === -1 ? "" : frontmatter.slice(lineEnd + 1));
378
+ }
379
+ //#endregion
380
+ //#region src/store-error.ts
381
+ /** A key that is empty, has an empty or dot segment, or leaves its base directory. */
382
+ var StoreKeyError = class extends Error {
383
+ constructor(key) {
384
+ super(`"${key}" is not a valid store path.`);
385
+ this.name = "StoreKeyError";
386
+ }
387
+ };
388
+ /**
389
+ * A store that could not do what was asked, for a reason the person editing can act on (a refused token, a protected
390
+ * branch, a branch that moved). The editor API answers it with `status` and `code`, so the message reaches the page
391
+ * instead of becoming a bare 500.
392
+ */
393
+ var StoreError = class extends Error {
394
+ status;
395
+ code;
396
+ constructor(status, code, message) {
397
+ super(message);
398
+ this.name = "StoreError";
399
+ this.status = status;
400
+ this.code = code;
401
+ }
402
+ };
403
+ //#endregion
404
+ //#region src/store-core.ts
405
+ /** The key of a file by its path from the project root, for content outside the content directory. */
406
+ function repoKey(path) {
407
+ return `/${path}`;
408
+ }
409
+ /** Splits a store key and refuses anything empty, with empty or dot segments, or leaving its base. */
410
+ function parseKey(key) {
411
+ const base = key.startsWith("/") ? "root" : "content";
412
+ const parts = (base === "root" ? key.slice(1) : key).split("/");
413
+ if (key === "" || parts.some((part) => part === "" || part === "." || part === "..")) throw new StoreKeyError(key);
414
+ return {
415
+ base,
416
+ parts
417
+ };
418
+ }
419
+ const SITE_KEY = "site.json";
420
+ const PAGES_DIR = "pages";
421
+ /** The key of the page with this slug. The slug must already be validated (`readSlug`). */
422
+ function pageKey(slug) {
423
+ return `${PAGES_DIR}/${slug}.json`;
424
+ }
425
+ //#endregion
426
+ //#region src/validate.ts
427
+ function fieldIssues(error) {
428
+ return error.issues.map((issue) => ({
429
+ path: issue.path.length > 0 ? issue.path.map((part) => String(part)).join(".") : "(root)",
430
+ message: issue.message
431
+ }));
432
+ }
433
+ function validateSite(input, site) {
434
+ return site.schema.safeParse(input);
435
+ }
436
+ /** Validate a page document: its own fields, and each section against the registry's schema for its type. */
437
+ function validatePage(input, registry) {
438
+ return createPageSchema(registry).safeParse(input);
439
+ }
440
+ /**
441
+ * Validate a page for the editor: like {@link validatePage}, but a section of a type the registry no longer
442
+ * defines is kept as it is. The site build still rejects such a page until the section is removed.
443
+ */
444
+ function validateEditorPage(input, registry) {
445
+ return createTolerantPageSchema(registry).safeParse(input);
446
+ }
447
+ //#endregion
448
+ //#region src/collections.ts
449
+ const TEMPLATE = /^((?:[A-Za-z0-9_.-]+\/)+)\{slug\}(\.mdx?)$/;
450
+ const ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
451
+ const FIELD_NAME_RULE = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
452
+ const FORBIDDEN_FIELDS = /* @__PURE__ */ new Set([
453
+ "__proto__",
454
+ "constructor",
455
+ "prototype"
456
+ ]);
457
+ /** Declares a collection. Checks the options now, so a typo fails when the config loads, not on the first save. */
458
+ function collection(options) {
459
+ parseTemplate(options.path);
460
+ return options;
461
+ }
462
+ function parseTemplate(path) {
463
+ const match = TEMPLATE.exec(path);
464
+ if (!match || path.split("/").some((part) => part === "." || part === "..")) throw new Error(`bearminion(): a collection path must look like "src/content/blog/{slug}.md" (a folder, then {slug} and .md or .mdx), got "${path}".`);
465
+ return {
466
+ dir: (match[1] ?? "").replace(/\/$/, ""),
467
+ ext: match[2]
468
+ };
469
+ }
470
+ /** Astro's `image()` stands in as a string path, marked so the editor can offer the uploader. */
471
+ const imageField = () => z.string().meta({ bearminion: "image" });
472
+ /** Checks the `collections` option and resolves each schema. */
473
+ function resolveCollections(input) {
474
+ const result = {};
475
+ for (const [id, options] of Object.entries(input ?? {})) {
476
+ if (!ID.test(id)) throw new Error(`bearminion(): collection id "${id}" must be lowercase kebab-case.`);
477
+ const { dir, ext } = parseTemplate(options.path);
478
+ const schema = typeof options.schema === "function" ? options.schema({ image: imageField }) : options.schema;
479
+ result[id] = {
480
+ id,
481
+ label: options.label ?? id,
482
+ dir,
483
+ ext,
484
+ schema,
485
+ rename: options.rename === true,
486
+ delete: options.delete === true
487
+ };
488
+ }
489
+ return result;
490
+ }
491
+ function entryKey(collection, slug) {
492
+ return repoKey(`${collection.dir}/${slug}${collection.ext}`);
493
+ }
494
+ /** Dates have no JSON Schema form; the editor edits them as text in a date picker. */
495
+ const dateOverride = (context) => {
496
+ if (context.zodSchema._zod.def.type === "date") {
497
+ context.jsonSchema.type = "string";
498
+ context.jsonSchema.format = "date-time";
499
+ context.jsonSchema["x-bm"] = "date";
500
+ }
501
+ };
502
+ /**
503
+ * The form fields of a collection's schema, one per top-level key. Advisory: refinements and transforms are invisible
504
+ * here, and the real schema validates every save. A field that cannot be described comes back read-only, never dropped.
505
+ */
506
+ function fieldDefinitions(schema) {
507
+ const shape = schema.shape;
508
+ if (shape === void 0 || typeof shape !== "object") return null;
509
+ return Object.entries(shape).map(([name, field]) => {
510
+ try {
511
+ const converted = z.toJSONSchema(z.object({ [name]: field }), {
512
+ io: "input",
513
+ unrepresentable: "any",
514
+ override: dateOverride
515
+ });
516
+ const property = converted.properties?.[name] ?? null;
517
+ const described = property !== null && [
518
+ "type",
519
+ "enum",
520
+ "const",
521
+ "anyOf",
522
+ "oneOf",
523
+ "$ref"
524
+ ].some((key) => key in property);
525
+ return {
526
+ name,
527
+ required: converted.required?.includes(name) === true,
528
+ schema: property,
529
+ readOnly: !described
530
+ };
531
+ } catch {
532
+ return {
533
+ name,
534
+ required: false,
535
+ schema: null,
536
+ readOnly: true
537
+ };
538
+ }
539
+ });
540
+ }
541
+ function jsonSafe(value) {
542
+ if (value instanceof Date) {
543
+ const iso = value.toISOString();
544
+ return iso.endsWith("T00:00:00.000Z") ? iso.slice(0, 10) : iso;
545
+ }
546
+ if (Array.isArray(value)) return value.map(jsonSafe);
547
+ if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, jsonSafe(inner)]));
548
+ return value;
549
+ }
550
+ function describe(collection, slug, source) {
551
+ const parts = splitEntry(source);
552
+ const format = collection.ext === ".mdx" ? "mdx" : "md";
553
+ const parsed = parseBody(parts.body, { mdx: format === "mdx" });
554
+ return {
555
+ slug,
556
+ format,
557
+ fields: jsonSafe(hasFrontmatter(parts) ? readFields(parts.frontmatter) : {}),
558
+ blocks: parsed.blocks.map(({ id, type, raw, editable }) => ({
559
+ id,
560
+ type,
561
+ raw,
562
+ editable
563
+ }))
564
+ };
565
+ }
566
+ const fail = (status, code, message, issues) => ({
567
+ ok: false,
568
+ status,
569
+ code,
570
+ message,
571
+ ...issues ? { issues } : {}
572
+ });
573
+ function entryFailure(error) {
574
+ if (error instanceof EntryError) return fail(error.code === "read_only_field" ? 409 : 422, error.code, error.message);
575
+ throw error;
576
+ }
577
+ async function validate(collection, source) {
578
+ const parts = splitEntry(source);
579
+ const result = await collection.schema.safeParseAsync(hasFrontmatter(parts) ? readFields(parts.frontmatter) : {});
580
+ if (result.success) return [];
581
+ return fieldIssues(result.error);
582
+ }
583
+ async function listEntries(store, collection) {
584
+ const names = await store.list(repoKey(collection.dir)) ?? [];
585
+ const slugs = [];
586
+ const skipped = [];
587
+ for (const name of names) {
588
+ if (!name.endsWith(collection.ext)) continue;
589
+ const slug = name.slice(0, -collection.ext.length);
590
+ if (slugSchema.safeParse(slug).success) slugs.push(slug);
591
+ else skipped.push(name);
592
+ }
593
+ return {
594
+ slugs,
595
+ skipped
596
+ };
597
+ }
598
+ async function readEntry(store, collection, slug) {
599
+ const source = await store.read(entryKey(collection, slug));
600
+ if (source === void 0) return fail(404, "not_found", `No entry "${slug}" in ${collection.label}.`);
601
+ try {
602
+ return {
603
+ ok: true,
604
+ value: describe(collection, slug, source)
605
+ };
606
+ } catch (error) {
607
+ return entryFailure(error);
608
+ }
609
+ }
610
+ function checkFieldName(name) {
611
+ if (!FIELD_NAME_RULE.test(name) || FORBIDDEN_FIELDS.has(name)) return fail(400, "invalid_field", `"${name}" is not a field name the editor can write.`);
612
+ return null;
613
+ }
614
+ async function updateEntry(store, collection, slug, patch) {
615
+ const key = entryKey(collection, slug);
616
+ const source = await store.read(key);
617
+ if (source === void 0) return fail(404, "not_found", `No entry "${slug}" in ${collection.label}.`);
618
+ try {
619
+ const parts = splitEntry(source);
620
+ let frontmatter = parts.frontmatter;
621
+ let head = parts.head;
622
+ let tail = parts.tail;
623
+ for (const name of [...Object.keys(patch.set ?? {}), ...patch.unset ?? []]) {
624
+ const bad = checkFieldName(name);
625
+ if (bad) return bad;
626
+ }
627
+ if (patch.set && Object.keys(patch.set).length > 0 || patch.unset && patch.unset.length > 0) {
628
+ if (!hasFrontmatter(parts)) {
629
+ head = `---${parts.eol}`;
630
+ tail = `---${parts.eol}`;
631
+ frontmatter = "";
632
+ }
633
+ for (const [name, value] of Object.entries(patch.set ?? {})) frontmatter = setField(frontmatter, name, value, parts.eol);
634
+ for (const name of patch.unset ?? []) frontmatter = removeField(frontmatter, name);
635
+ }
636
+ let body = parts.body;
637
+ if (patch.blocks) {
638
+ const parsed = parseBody(parts.body, { mdx: collection.ext === ".mdx" });
639
+ const byId = new Map(parsed.blocks.map((block) => [block.id, block]));
640
+ for (const edit of patch.blocks) {
641
+ if (edit.id !== void 0 && !byId.has(edit.id)) return fail(400, "unknown_block", `Block "${edit.id}" does not exist.`);
642
+ if (edit.id !== void 0 && edit.markdown !== void 0 && byId.get(edit.id)?.editable === false) return fail(409, "block_locked", `Block "${edit.id}" holds content the editor cannot edit (HTML, MDX, footnotes or similar).`);
643
+ }
644
+ body = applyBlocks(parsed, patch.blocks);
645
+ }
646
+ const next = joinEntry({
647
+ ...parts,
648
+ head,
649
+ frontmatter,
650
+ tail,
651
+ body
652
+ });
653
+ const issues = await validate(collection, next);
654
+ if (issues.length > 0) return fail(400, "validation", "The entry failed schema validation.", issues);
655
+ if (next !== source) await store.apply([{
656
+ type: "write",
657
+ key,
658
+ text: next
659
+ }]);
660
+ return {
661
+ ok: true,
662
+ value: describe(collection, slug, next)
663
+ };
664
+ } catch (error) {
665
+ return entryFailure(error);
666
+ }
667
+ }
668
+ async function createEntry(store, collection, input) {
669
+ if (!slugSchema.safeParse(input.slug).success) return fail(400, "invalid_slug", "Slug must be lowercase kebab-case and must not contain a path.");
670
+ const key = entryKey(collection, input.slug);
671
+ if (await store.exists(key)) return fail(409, "conflict", `"${input.slug}" already exists in ${collection.label}.`);
672
+ try {
673
+ let frontmatter = "";
674
+ for (const [name, value] of Object.entries(input.fields ?? {})) {
675
+ const bad = checkFieldName(name);
676
+ if (bad) return bad;
677
+ frontmatter = setField(frontmatter, name, value);
678
+ }
679
+ const body = (input.body ?? "").replace(/(?:\r?\n)+$/, "");
680
+ const source = `---\n${frontmatter}---\n${body === "" ? "" : `\n${body}\n`}`;
681
+ const issues = await validate(collection, source);
682
+ if (issues.length > 0) return fail(400, "validation", "The entry failed schema validation.", issues);
683
+ await store.apply([{
684
+ type: "write",
685
+ key,
686
+ text: source
687
+ }]);
688
+ return {
689
+ ok: true,
690
+ value: describe(collection, input.slug, source)
691
+ };
692
+ } catch (error) {
693
+ return entryFailure(error);
694
+ }
695
+ }
696
+ async function deleteEntry(store, collection, slug) {
697
+ if (!collection.delete) return fail(409, "operation_locked", `Deleting entries is turned off for ${collection.label} (delete in its collection() options).`);
698
+ const key = entryKey(collection, slug);
699
+ if (!await store.exists(key)) return fail(404, "not_found", `No entry "${slug}" in ${collection.label}.`);
700
+ await store.apply([{
701
+ type: "remove",
702
+ key
703
+ }]);
704
+ return {
705
+ ok: true,
706
+ value: { slug }
707
+ };
708
+ }
709
+ async function renameEntry(store, collection, slug, next) {
710
+ if (!collection.rename) return fail(409, "operation_locked", `Renaming entries is turned off for ${collection.label} (rename in its collection() options).`);
711
+ if (!slugSchema.safeParse(next).success) return fail(400, "invalid_slug", "Slug must be lowercase kebab-case and must not contain a path.");
712
+ const from = entryKey(collection, slug);
713
+ const to = entryKey(collection, next);
714
+ const source = await store.read(from);
715
+ if (source === void 0) return fail(404, "not_found", `No entry "${slug}" in ${collection.label}.`);
716
+ if (next === slug) return {
717
+ ok: true,
718
+ value: { slug }
719
+ };
720
+ if (await store.exists(to)) return fail(409, "conflict", `"${next}" already exists in ${collection.label}.`);
721
+ await store.apply([{
722
+ type: "write",
723
+ key: to,
724
+ text: source
725
+ }, {
726
+ type: "remove",
727
+ key: from
728
+ }]);
729
+ return {
730
+ ok: true,
731
+ value: { slug: next }
732
+ };
733
+ }
734
+ //#endregion
735
+ export { enumFields as C, ContentReadError as D, ContentError as E, ContentValidationError as O, loadThemePreview as S, schemaProps as T, parseKey as _, listEntries as a, PreviewUnavailableError as b, resolveCollections as c, validateEditorPage as d, validatePage as f, pageKey as g, SITE_KEY as h, fieldDefinitions as i, formatContentIssues as k, updateEntry as l, PAGES_DIR as m, createEntry as n, readEntry as o, validateSite as p, deleteEntry as r, renameEntry as s, collection as t, fieldIssues as u, StoreError as v, imageFields as w, defineThemePreview as x, StoreKeyError as y };