bearminion 1.20.0 → 1.22.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +3 -3
  3. package/dist/astro.d.ts +16 -7
  4. package/dist/astro.js +212 -93
  5. package/dist/cli.js +903 -4
  6. package/dist/content-types-46XqPaW4.js +505 -0
  7. package/dist/content.d.ts +24 -3
  8. package/dist/content.js +83 -6
  9. package/dist/{editor-context-DzRwKENi.d.ts → editor-context-D1yfPp21.d.ts} +95 -8
  10. package/dist/{github-store-Dt_YuOPD.js → github-store-B2folBeq.js} +551 -206
  11. package/dist/{github-store-DsLCe5MR.d.ts → github-store-CuhvbFCh.d.ts} +1 -1
  12. package/dist/hosted-astro.js +1 -1
  13. package/dist/{hosted-middleware-CsROahka.js → hosted-middleware-DHLIedeV.js} +1 -1
  14. package/dist/hosted-overlay.js +1 -1
  15. package/dist/hosted.d.ts +10 -4
  16. package/dist/hosted.js +68 -9
  17. package/dist/index.d.ts +4 -4
  18. package/dist/index.js +11 -6
  19. package/dist/{migrate-b408EaLp.js → migrate-Cm30puW8.js} +2 -2
  20. package/dist/{page-wlcQJAA-.js → page-C7zE_HD1.js} +5 -1
  21. package/dist/{page-BGSTL63-.d.ts → page-CpVElMPH.d.ts} +193 -37
  22. package/dist/{request-guards-BcSUj8Gc.js → request-guards-DtNVdqQ7.js} +1 -1
  23. package/dist/{collections-Bm3RWg2K.js → routing-jKeq4LwO.js} +213 -57
  24. package/dist/routing-yPy8hEfZ.d.ts +137 -0
  25. package/dist/{theme-BvqJ8UnS.js → theme-DTVVNMlr.js} +1 -1
  26. package/dist/ui/mount.js +3294 -1259
  27. package/package.json +2 -2
  28. package/registry/default/files/src/components/organisms/EntryList.astro +83 -0
  29. package/registry/default/files/src/components/organisms/Pagination.astro +56 -0
  30. package/registry/default/files/src/components/sections/contact/definition.ts +6 -2
  31. package/registry/default/files/src/components/sections/faq/definition.ts +2 -2
  32. package/registry/default/files/src/components/sections/media/Media.astro +2 -2
  33. package/registry/default/files/src/components/sections/media/MediaPlayer.astro +2 -2
  34. package/registry/default/files/src/components/sections/pricing/definition.ts +16 -1
  35. package/registry/default/files/src/components/sections/shared.ts +3 -0
  36. package/registry/default/files/src/components/sections/stats/definition.ts +6 -1
  37. package/registry/default/files/src/components/sections/testimonials/definition.ts +13 -1
  38. package/registry/default/files/src/components/sections/text-image/definition.ts +1 -1
  39. package/registry/default/files/src/components/seo/Seo.astro +3 -1
  40. package/registry/default/files/src/content.config.ts +21 -0
  41. package/registry/default/files/src/env.d.ts +2 -0
  42. package/registry/default/files/src/lib/content.ts +81 -0
  43. package/registry/default/files/src/lib/editing.ts +6 -0
  44. package/registry/default/files/src/lib/sitemap.ts +48 -0
  45. package/registry/default/files/src/pages/[...slug].astro +30 -16
  46. package/registry/default/registry.json +77 -21
  47. package/dist/preview-DFLna-Be.d.ts +0 -42
@@ -0,0 +1,505 @@
1
+ import { P as textSchema, c as seoSchema, f as createSectionSchema, i as createTolerantPageSchema, l as slugSchema, n as addSectionIdentityIssues, o as pageStatusSchema, p as createTolerantSectionSchema, r as createPageSchema } from "./page-C7zE_HD1.js";
2
+ import { z } from "zod";
3
+ //#region src/store-error.ts
4
+ /** A key that is empty, has an empty or dot segment, or leaves its base directory. */
5
+ var StoreKeyError = class extends Error {
6
+ constructor(key) {
7
+ super(`"${key}" is not a valid store path.`);
8
+ this.name = "StoreKeyError";
9
+ }
10
+ };
11
+ /**
12
+ * A store that could not do what was asked, for a reason the person editing can act on (a refused token, a protected
13
+ * branch, a branch that moved). The editor API answers it with `status` and `code`, so the message reaches the page
14
+ * instead of becoming a bare 500.
15
+ */
16
+ var StoreError = class extends Error {
17
+ status;
18
+ code;
19
+ constructor(status, code, message) {
20
+ super(message);
21
+ this.name = "StoreError";
22
+ this.status = status;
23
+ this.code = code;
24
+ }
25
+ };
26
+ //#endregion
27
+ //#region src/store-core.ts
28
+ /** The key of a file by its path from the project root, for content outside the content directory. */
29
+ function repoKey(path) {
30
+ return `/${path}`;
31
+ }
32
+ /** Splits a store key and refuses anything empty, with empty or dot segments, or leaving its base. */
33
+ function parseKey(key) {
34
+ const base = key.startsWith("/") ? "root" : "content";
35
+ const parts = (base === "root" ? key.slice(1) : key).split("/");
36
+ if (key === "" || parts.some((part) => part === "" || part === "." || part === "..")) throw new StoreKeyError(key);
37
+ return {
38
+ base,
39
+ parts
40
+ };
41
+ }
42
+ const SITE_KEY = "site.json";
43
+ const PAGES_DIR = "pages";
44
+ /** The key of the page with this slug. The slug must already be validated (`readSlug`). */
45
+ function pageKey(slug) {
46
+ return `${PAGES_DIR}/${slug}.json`;
47
+ }
48
+ //#endregion
49
+ //#region src/content-types.ts
50
+ const HOME_TYPE = "home";
51
+ const NOT_FOUND_TYPE = "not-found";
52
+ const PAGES_TYPE = "pages";
53
+ /** Store directory of the singles a site declares. The built-in home and 404 documents stay in `pages/`. */
54
+ const SINGLES_DIR = "singles";
55
+ /** The slug the home page is stored under. */
56
+ const HOME_SLUG = "index";
57
+ /** The file of a type's listing page. An underscore cannot start a slug, so no entry can take the name. */
58
+ const LISTING_FILE = "_listing.json";
59
+ /** `/blog/page/2`: the segment before the page number. An entry cannot use it as its slug when the listing shares its prefix. */
60
+ const PAGINATION_SEGMENT = "page";
61
+ /** The Astro collection of listing page documents, one per type that has a listing. Entry id = type id. */
62
+ const LISTINGS_COLLECTION = "bm-listings";
63
+ /** The Astro collection of the singles a model declares. Entry id = type id. */
64
+ const SINGLES_COLLECTION = "bm-singles";
65
+ /** What a migration is told a listing page document is, in place of a content type's id. */
66
+ const LISTING_MIGRATION_TYPE = "listing";
67
+ const ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
68
+ const PATH = /^\/([a-z0-9]+(?:-[a-z0-9]+)*)\/\{slug\}$/;
69
+ const SINGLE_PATH = /^\/([a-z0-9]+(?:-[a-z0-9]+)*)$/;
70
+ const PAGES_PATH = "/{slug}";
71
+ /** Ids that would be mistaken for a built-in type, a store file, a pull-request scope or one of the editor's own collections. */
72
+ const RESERVED_IDS = /* @__PURE__ */ new Set([
73
+ HOME_TYPE,
74
+ NOT_FOUND_TYPE,
75
+ HOME_SLUG,
76
+ SINGLES_DIR,
77
+ "site",
78
+ "page",
79
+ "collection",
80
+ "edits",
81
+ "uploads",
82
+ "listing",
83
+ LISTINGS_COLLECTION,
84
+ SINGLES_COLLECTION
85
+ ]);
86
+ /** Root addresses a type or a listing cannot take. */
87
+ const RESERVED_SEGMENTS = /* @__PURE__ */ new Set([HOME_SLUG, "404"]);
88
+ const SINGLE_KEYS = /* @__PURE__ */ new Set([
89
+ "kind",
90
+ "path",
91
+ "label",
92
+ "fields",
93
+ "sections"
94
+ ]);
95
+ const OPTION_KEYS = /* @__PURE__ */ new Set([
96
+ "kind",
97
+ "path",
98
+ "label",
99
+ "fields",
100
+ "sections",
101
+ "sort",
102
+ "listing",
103
+ "rename",
104
+ "delete"
105
+ ]);
106
+ const SORTABLE = /* @__PURE__ */ new Set([
107
+ "string",
108
+ "number",
109
+ "boolean",
110
+ "enum",
111
+ "date"
112
+ ]);
113
+ const WRAPPERS = /* @__PURE__ */ new Set([
114
+ "default",
115
+ "prefault",
116
+ "readonly",
117
+ "catch",
118
+ "nonoptional"
119
+ ]);
120
+ var TypesError = class extends Error {
121
+ constructor(message) {
122
+ super(`Content types: ${message}`);
123
+ this.name = "ContentTypesError";
124
+ }
125
+ };
126
+ function defOf(schema) {
127
+ return schema._zod.def;
128
+ }
129
+ function isObjectSchema(value) {
130
+ if (typeof value !== "object" || value === null || !("_zod" in value)) return false;
131
+ const def = defOf(value);
132
+ return def.type === "object" && typeof def.shape === "object";
133
+ }
134
+ /** The kind of value a sort field holds, or why it cannot be sorted by. */
135
+ function sortKind(field) {
136
+ let current = field;
137
+ for (let depth = 0; depth < 16; depth++) {
138
+ const def = defOf(current);
139
+ if (def.type === "optional" || def.type === "nullable") return { reason: "it is optional, so some entries would have no value" };
140
+ if (def.type === "pipe" && def.in) current = def.in;
141
+ else if (WRAPPERS.has(def.type) && def.innerType) current = def.innerType;
142
+ else return SORTABLE.has(def.type) ? { kind: def.type } : { reason: `a ${def.type} has no order` };
143
+ }
144
+ return { reason: "its schema is nested too deep" };
145
+ }
146
+ function defaultLabel(id) {
147
+ const words = id.replaceAll("-", " ");
148
+ return words.charAt(0).toUpperCase() + words.slice(1);
149
+ }
150
+ /** Declares a type with many entries. Checks the options that need nothing else now, so a typo fails where it was written. */
151
+ function multi(options = {}) {
152
+ checkOptions("multi()", options);
153
+ return {
154
+ ...options,
155
+ kind: "multi"
156
+ };
157
+ }
158
+ /** Declares a type with one document at a fixed address: `single({ path: '/about' })`. */
159
+ function single(options) {
160
+ const declared = {
161
+ ...options,
162
+ kind: "single"
163
+ };
164
+ checkSingle("single()", declared);
165
+ return declared;
166
+ }
167
+ function checkShared(where, options) {
168
+ if (options.label !== void 0 && (typeof options.label !== "string" || options.label.trim() === "")) throw new TypesError(`${where}: label must be a non-empty string.`);
169
+ if (options.fields !== void 0 && !isObjectSchema(options.fields)) throw new TypesError(`${where}: fields must be a z.object({...}).`);
170
+ if (options.sections !== void 0) {
171
+ if (!Array.isArray(options.sections) || options.sections.some((name) => typeof name !== "string")) throw new TypesError(`${where}: sections must be a list of section types.`);
172
+ if (options.sections.length === 0) throw new TypesError(`${where}: sections is empty, so nothing could be added. Leave it out to allow all.`);
173
+ }
174
+ }
175
+ /** Checks a single's options and returns its address segment. */
176
+ function checkSingle(where, options) {
177
+ if (typeof options !== "object" || options === null) throw new TypesError(`${where} needs an options object.`);
178
+ for (const key of Object.keys(options)) if (!SINGLE_KEYS.has(key)) throw new TypesError(`${where} has an unknown option "${key}". A single takes: path, label, fields, sections.`);
179
+ const match = typeof options.path === "string" ? SINGLE_PATH.exec(options.path) : null;
180
+ if (!match) throw new TypesError(`${where}: path must be one segment, like "/about", got "${String(options.path)}".`);
181
+ checkShared(where, options);
182
+ return match[1];
183
+ }
184
+ /** Declares the site's types. Checks every type and that no two share an address. */
185
+ function defineTypes(types) {
186
+ resolveTypes({ types });
187
+ return types;
188
+ }
189
+ function checkOptions(where, options) {
190
+ if (typeof options !== "object" || options === null) throw new TypesError(`${where} needs an options object.`);
191
+ for (const key of Object.keys(options)) if (!OPTION_KEYS.has(key)) throw new TypesError(`${where} has an unknown option "${key}". Known: ${[...OPTION_KEYS].join(", ")}.`);
192
+ if (options.kind !== void 0 && options.kind !== "multi") throw new TypesError(`${where}: kind must be "multi" here.`);
193
+ for (const key of ["rename", "delete"]) if (options[key] !== void 0 && typeof options[key] !== "boolean") throw new TypesError(`${where}: ${key} must be true or false.`);
194
+ checkShared(where, options);
195
+ const listing = options.listing;
196
+ if (listing !== void 0 && listing !== false) {
197
+ if (typeof listing !== "object" || listing === null) throw new TypesError(`${where}: listing must be false or { slug, perPage }.`);
198
+ for (const key of Object.keys(listing)) if (key !== "slug" && key !== "perPage") throw new TypesError(`${where}: unknown option listing.${key}. Use listing.slug or listing.perPage.`);
199
+ const perPage = listing.perPage;
200
+ if (perPage !== void 0 && (!Number.isInteger(perPage) || perPage < 1 || perPage > 100)) throw new TypesError(`${where}: listing.perPage must be a whole number from 1 to 100.`);
201
+ if (listing.slug !== void 0 && (typeof listing.slug !== "string" || !ID.test(listing.slug))) throw new TypesError(`${where}: listing.slug must be one lowercase kebab-case segment, like "news".`);
202
+ }
203
+ const sort = options.sort;
204
+ if (sort !== void 0) {
205
+ if (typeof sort !== "object" || sort === null || typeof sort.by !== "string" || sort.by === "") throw new TypesError(`${where}: sort must be { by, order }, with by set to "title" or a field name.`);
206
+ if (sort.order !== void 0 && sort.order !== "asc" && sort.order !== "desc") throw new TypesError(`${where}: sort.order must be "asc" or "desc".`);
207
+ for (const key of Object.keys(sort)) if (key !== "by" && key !== "order") throw new TypesError(`${where}: unknown option sort.${key}. Use sort.by or sort.order.`);
208
+ }
209
+ }
210
+ function resolveSort(where, options, fallback) {
211
+ const sort = options.sort;
212
+ if (sort === void 0) return fallback;
213
+ if (sort.by !== "title") {
214
+ const shape = options.fields ? defOf(options.fields).shape : void 0;
215
+ const field = shape && Object.hasOwn(shape, sort.by) ? shape[sort.by] : void 0;
216
+ if (field === void 0) {
217
+ const known = ["title", ...Object.keys(shape ?? {})].join(", ");
218
+ throw new TypesError(`${where}: sort.by "${sort.by}" is not a field of this type. Known: ${known}.`);
219
+ }
220
+ const kind = sortKind(field);
221
+ if ("reason" in kind) throw new TypesError(`${where}: cannot sort by "${sort.by}": ${kind.reason}. Use a required date, string, number, boolean or enum field.`);
222
+ }
223
+ return {
224
+ by: sort.by,
225
+ order: sort.order ?? "asc"
226
+ };
227
+ }
228
+ const resolved = /* @__PURE__ */ new WeakMap();
229
+ let builtIn;
230
+ /**
231
+ * The site's types with every default filled in: the three built-in ones plus what `types` declares. Throws when the
232
+ * config is wrong, with the type and option to fix. Cached per `types` object.
233
+ */
234
+ function resolveTypes(model, pageRules) {
235
+ const input = model.types;
236
+ if (pageRules === void 0) {
237
+ const cached = input === void 0 ? builtIn : resolved.get(input);
238
+ if (cached) {
239
+ checkSections(cached, model.sections);
240
+ return cached;
241
+ }
242
+ }
243
+ const result = build(input ?? {}, pageRules);
244
+ checkSections(result, model.sections);
245
+ if (pageRules === void 0) {
246
+ if (input === void 0) builtIn = result;
247
+ else resolved.set(input, result);
248
+ }
249
+ return result;
250
+ }
251
+ function build(input, pageRules) {
252
+ if (typeof input !== "object" || input === null) throw new TypesError("`types` must be an object of types by id.");
253
+ const home = {
254
+ kind: "single",
255
+ id: HOME_TYPE,
256
+ label: "Home",
257
+ path: "/",
258
+ slug: HOME_SLUG,
259
+ key: `${PAGES_DIR}/${HOME_SLUG}.json`,
260
+ fields: null,
261
+ sections: null,
262
+ builtIn: true
263
+ };
264
+ const notFound = {
265
+ kind: "single",
266
+ id: NOT_FOUND_TYPE,
267
+ label: "404",
268
+ path: `/404`,
269
+ slug: "404",
270
+ key: `${PAGES_DIR}/404.json`,
271
+ fields: null,
272
+ sections: null,
273
+ builtIn: true
274
+ };
275
+ const pagesOptions = Object.hasOwn(input, "pages") ? input[PAGES_TYPE] : {};
276
+ if (pagesOptions.kind === "single") throw new TypesError(`types.${PAGES_TYPE}: the built-in pages type has many entries. Give the single another id.`);
277
+ checkOptions(`types.${PAGES_TYPE}`, pagesOptions);
278
+ if (pagesOptions.path !== void 0 && pagesOptions.path !== PAGES_PATH) throw new TypesError(`types.${PAGES_TYPE}: the built-in pages type is always at "${PAGES_PATH}". Remove path, or add another type for "${pagesOptions.path}".`);
279
+ if (pagesOptions.listing !== void 0 && pagesOptions.listing !== false) throw new TypesError(`types.${PAGES_TYPE}: the built-in pages type has no listing page. Add another type for a list of entries.`);
280
+ const pages = {
281
+ kind: "multi",
282
+ id: PAGES_TYPE,
283
+ label: pagesOptions.label ?? "Pages",
284
+ prefix: "",
285
+ dir: PAGES_DIR,
286
+ fields: pagesOptions.fields ?? null,
287
+ sections: pagesOptions.sections ?? null,
288
+ sort: resolveSort(`types.${PAGES_TYPE}`, pagesOptions, null),
289
+ listing: null,
290
+ rename: pagesOptions.rename ?? pageRules?.rename ?? true,
291
+ delete: pagesOptions.delete ?? pageRules?.delete ?? true
292
+ };
293
+ const all = [pages];
294
+ const singles = [home, notFound];
295
+ /** Root address segment to what holds it, for the collision message. */
296
+ const taken = /* @__PURE__ */ new Map();
297
+ for (const [id, options] of Object.entries(input)) {
298
+ if (id === "pages") continue;
299
+ const where = `types.${id}`;
300
+ if (!ID.test(id)) throw new TypesError(`the type id "${id}" must be lowercase kebab-case.`);
301
+ if (RESERVED_IDS.has(id)) throw new TypesError(`"${id}" cannot be a type id.${id === "home" || id === "not-found" ? " It is built in and has no options." : ""}`);
302
+ if (options.kind === "single") {
303
+ const segment = checkSingle(where, options);
304
+ claim(taken, segment, `the single "${id}"`, where);
305
+ singles.push({
306
+ kind: "single",
307
+ id,
308
+ label: options.label ?? defaultLabel(id),
309
+ path: `/${segment}`,
310
+ slug: segment,
311
+ key: `${SINGLES_DIR}/${id}.json`,
312
+ fields: options.fields ?? null,
313
+ sections: options.sections ?? null,
314
+ builtIn: false
315
+ });
316
+ continue;
317
+ }
318
+ checkOptions(where, options);
319
+ const path = options.path ?? `/${id}/{slug}`;
320
+ const match = PATH.exec(path);
321
+ if (!match) throw new TypesError(`${where}: path must look like "/blog/{slug}" (one segment, then {slug}), got "${path}".`);
322
+ const prefix = match[1];
323
+ claim(taken, prefix, `the entries of "${id}"`, where);
324
+ const listing = options.listing === void 0 || options.listing === false ? null : options.listing;
325
+ const listingSlug = listing?.slug ?? prefix;
326
+ if (listing && listingSlug !== prefix) claim(taken, listingSlug, `the listing of "${id}"`, where);
327
+ all.push({
328
+ kind: "multi",
329
+ id,
330
+ label: options.label ?? defaultLabel(id),
331
+ prefix,
332
+ dir: id,
333
+ fields: options.fields ?? null,
334
+ sections: options.sections ?? null,
335
+ sort: resolveSort(where, options, {
336
+ by: "title",
337
+ order: "asc"
338
+ }),
339
+ listing: listing ? {
340
+ slug: listingSlug,
341
+ perPage: listing.perPage ?? 10
342
+ } : null,
343
+ rename: options.rename ?? true,
344
+ delete: options.delete ?? true
345
+ });
346
+ }
347
+ const byId = new Map([...singles, ...all].map((type) => [type.id, type]));
348
+ return {
349
+ home,
350
+ notFound,
351
+ singles,
352
+ pages,
353
+ multi: all,
354
+ get: (id) => byId.get(id)
355
+ };
356
+ }
357
+ function claim(taken, segment, what, where) {
358
+ if (RESERVED_SEGMENTS.has(segment)) throw new TypesError(`${where}: "/${segment}" is the address of a built-in page.`);
359
+ const holder = taken.get(segment);
360
+ if (holder !== void 0) throw new TypesError(`${where}: "/${segment}" is already the address of ${holder}.`);
361
+ taken.set(segment, what);
362
+ }
363
+ function checkSections(types, registry) {
364
+ if (registry === void 0) return;
365
+ for (const type of [...types.singles, ...types.multi]) for (const name of type.sections ?? []) if (!Object.hasOwn(registry, name)) throw new TypesError(`types.${type.id}: sections names "${name}", which the site does not define. Known: ${Object.keys(registry).join(", ")}.`);
366
+ }
367
+ /** Store key of the entry `slug` of a multi type. The slug must already be validated. */
368
+ function entryKey(type, slug) {
369
+ return `${type.dir}/${slug}.json`;
370
+ }
371
+ /** Store key of a type's listing page document. */
372
+ function listingKey(type) {
373
+ return `${type.dir}/${LISTING_FILE}`;
374
+ }
375
+ /**
376
+ * The slugs an entry of `type` cannot take, because the address belongs to something else: a page cannot be named
377
+ * like another type's prefix or a listing, and an entry cannot be `page` when the listing's page numbers live there.
378
+ * The home and 404 slugs are reserved in `pages`, where their documents are stored.
379
+ */
380
+ function reservedSlugs(types, type) {
381
+ const reserved = /* @__PURE__ */ new Set();
382
+ if (type.id === "pages") {
383
+ reserved.add(HOME_SLUG);
384
+ reserved.add("404");
385
+ for (const other of types.multi) {
386
+ if (other.prefix !== "") reserved.add(other.prefix);
387
+ if (other.listing) reserved.add(other.listing.slug);
388
+ }
389
+ for (const other of types.singles) reserved.add(other.slug);
390
+ } else if (type.listing && type.listing.slug === type.prefix) reserved.add(PAGINATION_SEGMENT);
391
+ return reserved;
392
+ }
393
+ /** The address of an entry: `/about`, `/blog/first-post`. */
394
+ function entryPath(type, slug) {
395
+ return type.prefix === "" ? `/${slug}` : `/${type.prefix}/${slug}`;
396
+ }
397
+ function sectionList(registry, type, tolerant) {
398
+ const section = tolerant ? createTolerantSectionSchema(registry) : createSectionSchema(registry);
399
+ const allowed = type?.sections ?? null;
400
+ return z.array(section).superRefine((sections, ctx) => {
401
+ addSectionIdentityIssues(sections, ctx);
402
+ if (allowed === null) return;
403
+ sections.forEach((item, index) => {
404
+ const name = item.type;
405
+ if (typeof name !== "string" || !Object.hasOwn(registry, name) || allowed.includes(name)) return;
406
+ ctx.addIssue({
407
+ code: "custom",
408
+ message: `Section type "${name}" is not allowed in ${type?.label ?? "this type"}. Allowed: ${allowed.join(", ")}.`,
409
+ path: [index, "type"]
410
+ });
411
+ });
412
+ });
413
+ }
414
+ const entrySchemas = /* @__PURE__ */ new WeakMap();
415
+ /**
416
+ * Validates an entry of `type`: the page fields, each section against the registry and the type's allowed list, and
417
+ * `fields` against the type's own schema. For a type with neither fields nor a section list this is the page schema
418
+ * itself, so the built-in `pages` type validates exactly as pages always have.
419
+ */
420
+ function createEntrySchema(registry, type, options = {}) {
421
+ const tolerant = options.tolerateOrphans === true;
422
+ if (type.fields === null && type.sections === null) return tolerant ? createTolerantPageSchema(registry) : createPageSchema(registry);
423
+ let perRegistry = entrySchemas.get(type);
424
+ if (!perRegistry) {
425
+ perRegistry = /* @__PURE__ */ new WeakMap();
426
+ entrySchemas.set(type, perRegistry);
427
+ }
428
+ let pair = perRegistry.get(registry);
429
+ if (!pair) {
430
+ pair = [];
431
+ perRegistry.set(registry, pair);
432
+ }
433
+ const index = tolerant ? 1 : 0;
434
+ const cached = pair[index];
435
+ if (cached) return cached;
436
+ const schema = z.object({
437
+ slug: slugSchema,
438
+ title: textSchema,
439
+ status: pageStatusSchema.optional(),
440
+ seo: seoSchema,
441
+ sections: sectionList(registry, type, tolerant),
442
+ ...type.fields ? { fields: type.fields } : {}
443
+ }).strict();
444
+ pair[index] = schema;
445
+ return schema;
446
+ }
447
+ const listingSchemas = /* @__PURE__ */ new WeakMap();
448
+ /** Validates a listing page document. Its sections may be any the site defines: the type's list limits entries only. */
449
+ function createListingSchema(registry, options = {}) {
450
+ const tolerant = options.tolerateOrphans === true;
451
+ let pair = listingSchemas.get(registry);
452
+ if (!pair) {
453
+ pair = [];
454
+ listingSchemas.set(registry, pair);
455
+ }
456
+ const index = tolerant ? 1 : 0;
457
+ const cached = pair[index];
458
+ if (cached) return cached;
459
+ const schema = z.object({
460
+ title: textSchema,
461
+ seo: seoSchema,
462
+ sections: sectionList(registry, null, tolerant)
463
+ }).strict();
464
+ pair[index] = schema;
465
+ return schema;
466
+ }
467
+ function rank(left, right, collator) {
468
+ if (left instanceof Date && right instanceof Date) return left.getTime() - right.getTime();
469
+ if (typeof left === "number" && typeof right === "number") return left - right;
470
+ if (typeof left === "boolean" && typeof right === "boolean") return Number(left) - Number(right);
471
+ return collator.compare(String(left), String(right));
472
+ }
473
+ /**
474
+ * Orders entries by the type's sort rule. Equal values fall back to the slug, A to Z by code point, so the same
475
+ * content gives the same order on every machine and pagination never shuffles between builds. Strings compare with
476
+ * `Intl.Collator` in `locale` (default `en`, fixed so the build host's own locale has no say), numbers inside them
477
+ * by value.
478
+ */
479
+ function sortEntries(type, entries, locale = "en") {
480
+ const sort = type.sort;
481
+ if (sort === null) return [...entries];
482
+ const collator = new Intl.Collator(locale, {
483
+ numeric: true,
484
+ sensitivity: "base"
485
+ });
486
+ const direction = sort.order === "desc" ? -1 : 1;
487
+ const value = (entry) => sort.by === "title" ? entry.title : entry.fields?.[sort.by];
488
+ return [...entries].sort((left, right) => {
489
+ const order = rank(value(left), value(right), collator) * direction;
490
+ if (order !== 0) return order;
491
+ return left.slug < right.slug ? -1 : left.slug > right.slug ? 1 : 0;
492
+ });
493
+ }
494
+ /** How many listing pages `count` entries need. A type with no entries still has page 1. */
495
+ function listingPageCount(type, count) {
496
+ if (!type.listing) return 0;
497
+ return Math.max(1, Math.ceil(count / type.listing.perPage));
498
+ }
499
+ /** The address of a listing page: `/blog`, `/blog/page/2`. */
500
+ function listingPath(type, page = 1) {
501
+ if (!type.listing) throw new TypesError(`types.${type.id} has no listing.`);
502
+ return page <= 1 ? `/${type.listing.slug}` : `/${type.listing.slug}/${PAGINATION_SEGMENT}/${page}`;
503
+ }
504
+ //#endregion
505
+ export { pageKey as C, StoreKeyError as D, StoreError as E, SITE_KEY as S, repoKey as T, multi as _, PAGES_TYPE as a, single as b, SINGLES_DIR as c, defineTypes as d, entryKey as f, listingPath as g, listingPageCount as h, LISTING_MIGRATION_TYPE as i, createEntrySchema as l, listingKey as m, LISTINGS_COLLECTION as n, PAGINATION_SEGMENT as o, entryPath as p, LISTING_FILE as r, SINGLES_COLLECTION as s, HOME_SLUG as t, createListingSchema as u, reservedSlugs as v, parseKey as w, sortEntries as x, resolveTypes as y };
package/dist/content.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { d as SectionOf, g as ContentModel, t as Page } from "./page-BGSTL63-.js";
1
+ import { N as SINGLES_COLLECTION, O as LISTINGS_COLLECTION, f as ContentModel, o as createPageSchema } from "./page-CpVElMPH.js";
2
2
  import { z } from "zod";
3
+ import { glob } from "astro/loaders";
3
4
  //#region src/content.d.ts
4
5
  export interface ContentCollectionsOptions {
5
6
  /** Directory that contains `site.json` and `pages/`. Default `content`, resolved from the project root. */
@@ -24,16 +25,36 @@ export interface ContentCollectionsOptions {
24
25
  * model's schemas, typed in `getCollection()` / `getEntry()`, and refreshed in dev when a file changes.
25
26
  * `entry.data` is the same object `loadPages()` and `loadSite()` return.
26
27
  *
28
+ * A model that declares content types gets more collections under `types`, to spread into the same object:
29
+ *
30
+ * ```ts
31
+ * const { pages, site, types } = contentCollections(contentModel)
32
+ * export const collections = {
33
+ * pages: defineCollection(pages),
34
+ * site: defineCollection(site),
35
+ * ...Object.fromEntries(Object.entries(types).map(([name, collection]) => [name, defineCollection(collection)])),
36
+ * }
37
+ * ```
38
+ *
39
+ * `types` has one collection per declared multi type, named by its id (entry id = slug), plus `bm-listings` (entry id =
40
+ * type id) when a type has a listing page and `bm-singles` (entry id = type id) when the model declares singles. It is
41
+ * empty for a model with no types, so the two collections above are all a site without types has.
42
+ *
27
43
  * `astro.config.ts` runs before Astro loads collections, so it keeps using `loadContent()`.
28
44
  */
29
45
  export declare function contentCollections<TModel extends ContentModel>(model: TModel, options?: ContentCollectionsOptions): {
46
+ types: Record<string, {
47
+ loader: ReturnType<typeof glob>;
48
+ schema: z.ZodType;
49
+ }>;
30
50
  pages: {
31
51
  loader: import("astro/loaders").Loader;
32
- schema: z.ZodType<Page<SectionOf<TModel["sections"]>>, unknown, z.core.$ZodTypeInternals<Page<SectionOf<TModel["sections"]>>, unknown>>;
52
+ schema: ReturnType<typeof createPageSchema<TModel["sections"]>>;
33
53
  };
34
54
  site: {
35
55
  loader: import("astro/loaders").Loader;
36
56
  schema: TModel["site"]["schema"];
37
57
  };
38
58
  };
39
- //#endregion
59
+ //#endregion
60
+ export { LISTINGS_COLLECTION, SINGLES_COLLECTION };
package/dist/content.js CHANGED
@@ -1,5 +1,6 @@
1
- import { n as createPageSchema, r as createTolerantPageSchema } from "./page-wlcQJAA-.js";
2
- import { n as createMigrator } from "./migrate-b408EaLp.js";
1
+ import { i as createTolerantPageSchema, r as createPageSchema } from "./page-C7zE_HD1.js";
2
+ import { c as SINGLES_DIR, i as LISTING_MIGRATION_TYPE, l as createEntrySchema, n as LISTINGS_COLLECTION, r as LISTING_FILE, s as SINGLES_COLLECTION, u as createListingSchema, y as resolveTypes } from "./content-types-46XqPaW4.js";
3
+ import { n as createMigrator } from "./migrate-Cm30puW8.js";
3
4
  import { t as CONTENT_COLLECTIONS_MARKER } from "./reload-BzVw721A.js";
4
5
  import { z } from "zod";
5
6
  import path from "node:path";
@@ -19,6 +20,21 @@ import { glob } from "astro/loaders";
19
20
  * model's schemas, typed in `getCollection()` / `getEntry()`, and refreshed in dev when a file changes.
20
21
  * `entry.data` is the same object `loadPages()` and `loadSite()` return.
21
22
  *
23
+ * A model that declares content types gets more collections under `types`, to spread into the same object:
24
+ *
25
+ * ```ts
26
+ * const { pages, site, types } = contentCollections(contentModel)
27
+ * export const collections = {
28
+ * pages: defineCollection(pages),
29
+ * site: defineCollection(site),
30
+ * ...Object.fromEntries(Object.entries(types).map(([name, collection]) => [name, defineCollection(collection)])),
31
+ * }
32
+ * ```
33
+ *
34
+ * `types` has one collection per declared multi type, named by its id (entry id = slug), plus `bm-listings` (entry id =
35
+ * type id) when a type has a listing page and `bm-singles` (entry id = type id) when the model declares singles. It is
36
+ * empty for a model with no types, so the two collections above are all a site without types has.
37
+ *
22
38
  * `astro.config.ts` runs before Astro loads collections, so it keeps using `loadContent()`.
23
39
  */
24
40
  function contentCollections(model, options = {}) {
@@ -26,14 +42,47 @@ function contentCollections(model, options = {}) {
26
42
  globalThis[CONTENT_COLLECTIONS_MARKER] = true;
27
43
  const migrator = createMigrator(model);
28
44
  const directoryUrl = (directory) => pathToFileURL(directory + path.sep);
45
+ const tolerateOrphans = options.tolerateOrphans === true;
46
+ const resolved = resolveTypes(model);
47
+ const documentSchema = (type) => upgraded(migrator, "page", createEntrySchema(model.sections, type, { tolerateOrphans }), type.id);
48
+ const types = {};
49
+ const declared = resolved.multi.filter((type) => type !== resolved.pages);
50
+ for (const type of declared) types[type.id] = {
51
+ loader: glob({
52
+ pattern: ["*.json", "!_*.json"],
53
+ base: directoryUrl(path.join(contentDir, type.dir)),
54
+ generateId: ({ data }) => String(data.slug)
55
+ }),
56
+ schema: documentSchema(type)
57
+ };
58
+ const listed = declared.filter((type) => type.listing);
59
+ if (listed.length > 0) types[LISTINGS_COLLECTION] = {
60
+ loader: glob({
61
+ pattern: listed.map((type) => `${type.dir}/${LISTING_FILE}`),
62
+ base: directoryUrl(contentDir),
63
+ generateId: ({ entry }) => entry.split("/")[0] ?? entry
64
+ }),
65
+ schema: upgraded(migrator, "page", createListingSchema(model.sections, { tolerateOrphans }), LISTING_MIGRATION_TYPE)
66
+ };
67
+ const singles = resolved.singles.filter((type) => !type.builtIn);
68
+ if (singles.length > 0) types[SINGLES_COLLECTION] = {
69
+ loader: glob({
70
+ pattern: singles.map((type) => `${type.id}.json`),
71
+ base: directoryUrl(path.join(contentDir, SINGLES_DIR)),
72
+ generateId: ({ entry }) => entry.replace(/\.json$/, "")
73
+ }),
74
+ schema: bySlug((slug) => singles.find((type) => type.slug === slug), documentSchema, "No single is declared for this file.")
75
+ };
76
+ const tuned = resolved.pages.fields !== null || resolved.pages.sections !== null;
29
77
  return {
78
+ types,
30
79
  pages: {
31
80
  loader: glob({
32
81
  pattern: "*.json",
33
82
  base: directoryUrl(path.join(contentDir, "pages")),
34
83
  generateId: ({ data }) => String(data.slug)
35
84
  }),
36
- schema: upgraded(migrator, "page", options.tolerateOrphans ? createTolerantPageSchema(model.sections) : createPageSchema(model.sections))
85
+ schema: tuned ? bySlug((slug) => pageType(resolved, slug), documentSchema, "") : upgraded(migrator, "page", options.tolerateOrphans ? createTolerantPageSchema(model.sections) : createPageSchema(model.sections), (raw) => pageType(resolved, slugOf(raw)).id)
37
86
  },
38
87
  site: {
39
88
  loader: glob({
@@ -45,10 +94,38 @@ function contentCollections(model, options = {}) {
45
94
  }
46
95
  };
47
96
  }
97
+ function pageType(types, slug) {
98
+ return slug === types.home.slug ? types.home : slug === types.notFound.slug ? types.notFound : types.pages;
99
+ }
100
+ const slugOf = (raw) => typeof raw === "object" && raw !== null && "slug" in raw && typeof raw.slug === "string" ? raw.slug : "";
101
+ /** A schema for a folder whose files are of different types: the `slug` inside a file picks the schema it must pass. */
102
+ function bySlug(typeOf, schemaOf, unknown) {
103
+ return z.unknown().transform((raw, ctx) => {
104
+ const type = typeOf(slugOf(raw));
105
+ if (!type) {
106
+ ctx.issues.push({
107
+ code: "custom",
108
+ message: unknown,
109
+ input: raw,
110
+ path: ["slug"]
111
+ });
112
+ return z.NEVER;
113
+ }
114
+ const result = schemaOf(type).safeParse(raw);
115
+ if (result.success) return result.data;
116
+ for (const issue of result.error.issues) ctx.issues.push({
117
+ code: "custom",
118
+ message: issue.message,
119
+ path: issue.path,
120
+ input: raw
121
+ });
122
+ return z.NEVER;
123
+ });
124
+ }
48
125
  /** Runs the content migrations before the schema, so collections accept files written under an older `schemaVersion`. */
49
- function upgraded(migrator, kind, schema) {
126
+ function upgraded(migrator, kind, schema, type) {
50
127
  return z.preprocess((raw, ctx) => {
51
- const result = migrator.upgrade(raw, kind);
128
+ const result = migrator.upgrade(raw, kind, typeof type === "function" ? type(raw) : type);
52
129
  if (result.ok) return result.value;
53
130
  ctx.issues.push({
54
131
  code: "custom",
@@ -60,4 +137,4 @@ function upgraded(migrator, kind, schema) {
60
137
  }, schema);
61
138
  }
62
139
  //#endregion
63
- export { contentCollections };
140
+ export { LISTINGS_COLLECTION, SINGLES_COLLECTION, contentCollections };