ferst-core 0.15.0 → 0.17.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 (74) hide show
  1. package/NOTICE +63 -31
  2. package/README.md +13 -4
  3. package/bin/ferst-media.mjs +96 -0
  4. package/bin/ferst-modules.mjs +17 -2
  5. package/components/BlockRenderer.astro +131 -129
  6. package/components/Card.astro +53 -51
  7. package/components/MembersAccount.astro +370 -0
  8. package/components/PostCard.astro +138 -136
  9. package/components/SiteHeader.astro +32 -14
  10. package/components/blocks/Grid.astro +49 -48
  11. package/components/blocks/Heading.astro +4 -1
  12. package/components/islands/BookMonth.tsx +95 -0
  13. package/components/islands/MembersAccount.tsx +392 -0
  14. package/components/recipes/Banner.astro +146 -146
  15. package/components/recipes/Book.astro +1147 -926
  16. package/components/recipes/FeatureCards.astro +112 -118
  17. package/components/recipes/Gallery.astro +57 -59
  18. package/components/recipes/Hero.astro +112 -10
  19. package/components/recipes/LatestPosts.astro +295 -292
  20. package/components/recipes/Locations.astro +146 -143
  21. package/components/recipes/Marquee.astro +75 -75
  22. package/components/recipes/MediaCards.astro +213 -219
  23. package/components/recipes/MembersContent.astro +176 -0
  24. package/components/recipes/Pricing.astro +149 -150
  25. package/components/recipes/Stats.astro +150 -157
  26. package/components/recipes/Tiles.astro +342 -296
  27. package/content/blocks.ts +1091 -1024
  28. package/content/cookies.ts +14 -0
  29. package/content/imageSlots.mjs +542 -0
  30. package/content/recipe-questions.ts +81 -80
  31. package/content/schemas.ts +13 -11
  32. package/examples/recipes.ts +5 -0
  33. package/fonts/OFL.txt +1332 -287
  34. package/fonts/anton-latin-400-normal.woff2 +0 -0
  35. package/fonts/bangers-latin-400-normal.woff2 +0 -0
  36. package/fonts/bebas-neue-latin-400-normal.woff2 +0 -0
  37. package/fonts/bowlby-one-latin-400-normal.woff2 +0 -0
  38. package/fonts/fredoka-latin-400-normal.woff2 +0 -0
  39. package/fonts/fredoka-latin-600-normal.woff2 +0 -0
  40. package/fonts/fredoka-latin-700-normal.woff2 +0 -0
  41. package/fonts/knewave-latin-400-normal.woff2 +0 -0
  42. package/fonts/lora-latin-400-normal.woff2 +0 -0
  43. package/fonts/lora-latin-600-normal.woff2 +0 -0
  44. package/fonts/lora-latin-700-normal.woff2 +0 -0
  45. package/fonts/merriweather-latin-400-normal.woff2 +0 -0
  46. package/fonts/merriweather-latin-600-normal.woff2 +0 -0
  47. package/fonts/merriweather-latin-700-normal.woff2 +0 -0
  48. package/fonts/nunito-latin-400-normal.woff2 +0 -0
  49. package/fonts/nunito-latin-600-normal.woff2 +0 -0
  50. package/fonts/nunito-latin-700-normal.woff2 +0 -0
  51. package/fonts/oswald-latin-400-normal.woff2 +0 -0
  52. package/fonts/oswald-latin-600-normal.woff2 +0 -0
  53. package/fonts/oswald-latin-700-normal.woff2 +0 -0
  54. package/fonts/rubik-dirt-latin-400-normal.woff2 +0 -0
  55. package/integration.mjs +319 -263
  56. package/layouts/Base.astro +8 -16
  57. package/lib/book.ts +416 -378
  58. package/lib/fonts.ts +130 -0
  59. package/lib/gridRows.ts +197 -0
  60. package/lib/image-fields.ts +140 -0
  61. package/lib/image-size.mjs +108 -73
  62. package/lib/image-sizes.ts +16 -0
  63. package/lib/logo-header.ts +46 -0
  64. package/lib/media-check.mjs +524 -0
  65. package/lib/members-account.ts +276 -0
  66. package/lib/members.ts +115 -0
  67. package/lib/theme-preview.ts +203 -140
  68. package/lib/themeTokens.ts +235 -220
  69. package/package.json +80 -71
  70. package/routes/account.astro +16 -0
  71. package/routes/cookie-policy.astro +28 -28
  72. package/styles/fonts.css +239 -76
  73. package/styles/theme.css +228 -160
  74. package/lib/gridColumns.ts +0 -22
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The site's own images and their width and height, read at build time by the ferst()
3
+ * integration (lib/image-size.mjs) from everything in `public/`. A component uses it to
4
+ * give an `<img>` its real width and height, so the page keeps the picture's shape before
5
+ * it arrives: no jump, no wrong-shaped box. Empty outside a ferst() build (the showcase,
6
+ * the preview renderer), where an image simply has no reserved size.
7
+ */
8
+ // Written exactly as `import.meta.env.FERST_IMAGE_SIZES`: the build replaces that text.
9
+ const SIZES = (import.meta.env.FERST_IMAGE_SIZES ?? {}) as Record<string, [number, number]>;
10
+
11
+ /** A site image's own size by its address (`/uploads/badge.png`), if the build read it. */
12
+ export function imageSizeOf(src: string | undefined): { width: number; height: number } | undefined {
13
+ if (!src) return undefined;
14
+ const found = SIZES[src.split(/[?#]/)[0]];
15
+ return found ? { width: found[0], height: found[1] } : undefined;
16
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The header logo's size and placement (logoSettings.header) as attributes on the site
3
+ * header. One function for both places that draw a header: SiteHeader at build time, and
4
+ * the live preview in the browser (lib/theme-preview.ts), which applies an editor's draft
5
+ * logo settings to a loaded page. The CSS that reads these attributes is SiteHeader's.
6
+ *
7
+ * Only a setting that differs from the default produces an attribute, so a site that sets
8
+ * nothing gets exactly the header it always had.
9
+ */
10
+ import type { LogoHeader } from '../content/schemas';
11
+
12
+ /** Every attribute this can set, so a preview can clear the previous draft's. */
13
+ export const LOGO_HEADER_ATTRIBUTES = ['data-logo-size', 'data-logo-placement', 'data-logo-hang', 'data-logo-shadow'] as const;
14
+
15
+ export interface LogoHeaderLayout {
16
+ attributes: Partial<Record<(typeof LOGO_HEADER_ATTRIBUTES)[number], string>>;
17
+ /** A hanging logo's width over its height, when its size is known: the bar keeps that much room. */
18
+ ratio?: number;
19
+ }
20
+
21
+ export function logoHeaderLayout({
22
+ header = {},
23
+ hasLogo,
24
+ size,
25
+ }: {
26
+ header?: Partial<LogoHeader>;
27
+ /** False when the site shows its name as text: the settings apply to an image only. */
28
+ hasLogo: boolean;
29
+ /** The image's own width and height, when known. */
30
+ size?: { width: number; height: number };
31
+ }): LogoHeaderLayout {
32
+ const attributes: LogoHeaderLayout['attributes'] = {};
33
+ if (!hasLogo) return { attributes };
34
+ if (header.size && header.size !== 'standard') attributes['data-logo-size'] = header.size;
35
+ if (header.placement === 'overhang') {
36
+ attributes['data-logo-placement'] = 'overhang';
37
+ if (header.shrinkOnScroll === false) attributes['data-logo-hang'] = '';
38
+ }
39
+ if (header.shadow) attributes['data-logo-shadow'] = '';
40
+ // Only a hanging logo needs its shape up front: the bar keeps that much room beside it.
41
+ const ratio =
42
+ attributes['data-logo-placement'] && size && size.width > 0 && size.height > 0
43
+ ? +(size.width / size.height).toFixed(4)
44
+ : undefined;
45
+ return ratio ? { attributes, ratio } : { attributes };
46
+ }
@@ -0,0 +1,524 @@
1
+ /**
2
+ * The site's pictures against the places they're used (content/imageSlots.mjs): what `npx
3
+ * ferst-media check` and `npx ferst-media brief` print. It walks the site's pages, posts and
4
+ * settings, finds every picture each image slot shows, reads its size (lib/image-size.mjs)
5
+ * and says, per use, whether it is ok, fixable (close to the place's shape, too big, or a
6
+ * plain border baked in) or should be remade (too far off, or too small). It also lists the
7
+ * media rules each file breaks: names in lower case with hyphens, nothing wider than 2400px,
8
+ * no location data. Advice only: nothing here changes a file or fails a build.
9
+ *
10
+ * Plain Node, no TypeScript, so a client site runs it with npx. `sharp` (installed with Astro)
11
+ * is optional: with it, a plain border baked into a picture is found too.
12
+ */
13
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
14
+ import { basename, extname, join, relative } from 'node:path';
15
+ import { imageSize } from './image-size.mjs';
16
+ import {
17
+ IMAGE_SLOTS,
18
+ MAX_WIDTH,
19
+ resolveShape,
20
+ shapeValue,
21
+ sizeFor,
22
+ slotModes,
23
+ splitKey,
24
+ } from '../content/imageSlots.mjs';
25
+
26
+ /** How far off a shape may be. `same`: no one would notice. `fit`: a slight trim (or, for a
27
+ * cropped place, a crop no one would notice). `crop`: the most a cropped place may lose
28
+ * before the picture should be remade (40% off the shape crops away about 29% of it). */
29
+ export const TOLERANCE = { same: 0.01, fit: 0.04, crop: 0.4 };
30
+ const RANK = { ok: 0, fixable: 1, remake: 2, missing: 3 };
31
+
32
+ const round = (n) => Math.round(n);
33
+ const pct = (n) => `${Math.round(n * 1000) / 10}%`;
34
+
35
+ /** A shape in words: `16:9`, `square`, `1.91:1`. */
36
+ export function shapeWords(shape) {
37
+ if (!shape || shape === 'any') return 'any shape';
38
+ if (shapeValue(shape) === 1) return 'square';
39
+ const [w, h] = shape.split('/').map(Number);
40
+ if (w > 21 || h > 21) return `${(w / h).toFixed(2).replace(/\.?0+$/, '')}:1`;
41
+ return `${w}:${h}`;
42
+ }
43
+ const sizeWords = ({ width, height }) =>
44
+ width && height ? `${width} × ${height} pixels` : width ? `${width} pixels wide` : `${height} pixels tall`;
45
+
46
+ /** The file's kind, from its first bytes. */
47
+ export function formatOf(bytes) {
48
+ const b = Buffer.from(bytes.subarray(0, 16));
49
+ if (b.length >= 4 && b.readUInt32BE(0) === 0x89504e47) return 'png';
50
+ if (b[0] === 0xff && b[1] === 0xd8) return 'jpeg';
51
+ if (b.toString('ascii', 0, 4) === 'GIF8') return 'gif';
52
+ if (b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') return 'webp';
53
+ if (/<svg\b/i.test(Buffer.from(bytes.subarray(0, 4096)).toString('utf8'))) return 'svg';
54
+ return 'other';
55
+ }
56
+
57
+ /**
58
+ * What a JPEG's EXIF block says that matters here: whether it holds a location (GPS
59
+ * latitude), and its orientation (5 to 8 mean the picture is shown turned a quarter, so its
60
+ * width and height swap). Reads only the first EXIF block; anything else is { gps: false }.
61
+ */
62
+ export function readExif(bytes) {
63
+ const b = Buffer.from(bytes);
64
+ const none = { gps: false, orientation: 1 };
65
+ if (b[0] !== 0xff || b[1] !== 0xd8) return none;
66
+ let i = 2;
67
+ while (i + 4 < b.length && b[i] === 0xff) {
68
+ const marker = b[i + 1];
69
+ const length = b.readUInt16BE(i + 2);
70
+ if (marker === 0xda) break; // the picture itself: no metadata after this
71
+ if (marker === 0xe1 && b.toString('ascii', i + 4, i + 10) === 'Exif\0\0') {
72
+ try {
73
+ const t = i + 10;
74
+ const le = b.toString('ascii', t, t + 2) === 'II';
75
+ const u16 = (o) => (le ? b.readUInt16LE(t + o) : b.readUInt16BE(t + o));
76
+ const u32 = (o) => (le ? b.readUInt32LE(t + o) : b.readUInt32BE(t + o));
77
+ const entries = (ifd) => Array.from({ length: u16(ifd) }, (_, n) => ifd + 2 + n * 12);
78
+ let gps = false;
79
+ let orientation = 1;
80
+ for (const e of entries(u32(4))) {
81
+ const tag = u16(e);
82
+ if (tag === 0x0112) orientation = u16(e + 8);
83
+ if (tag === 0x8825) gps = entries(u32(e + 8)).some((g) => [0x0002, 0x0004].includes(u16(g)));
84
+ }
85
+ return { gps, orientation };
86
+ } catch {
87
+ return none;
88
+ }
89
+ }
90
+ i += 2 + length;
91
+ }
92
+ return none;
93
+ }
94
+
95
+ /**
96
+ * A plain border baked into a picture (a black frame round a poster): found with sharp's trim,
97
+ * which takes the top-left pixel's colour as the border's. Counted only when it runs along two
98
+ * opposite sides, so a plain sky along the top of a photo isn't one. Null when there's none,
99
+ * or no sharp to look with.
100
+ */
101
+ export async function detectMargin(sharp, bytes) {
102
+ if (!sharp) return null;
103
+ try {
104
+ const { width: W, height: H } = await sharp(bytes).metadata();
105
+ const { info } = await sharp(bytes).trim({ threshold: 16 }).toBuffer({ resolveWithObject: true });
106
+ const left = Math.abs(info.trimOffsetLeft ?? 0);
107
+ const top = Math.abs(info.trimOffsetTop ?? 0);
108
+ const right = W - left - info.width;
109
+ const bottom = H - top - info.height;
110
+ const edge = (n, of) => n >= Math.max(2, of * 0.015);
111
+ const across = edge(top, H) && edge(bottom, H);
112
+ const down = edge(left, W) && edge(right, W);
113
+ if (!across && !down) return null;
114
+ return { top, right, bottom, left, width: info.width, height: info.height };
115
+ } catch {
116
+ return null;
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Whether one picture suits one place. `info` is the picture as the site shows it: width,
122
+ * height, format, and its baked-in border if one was found. `shape` is the place's shape here.
123
+ * @returns {{ status: 'ok' | 'fixable' | 'remake', reasons: string[], notes: string[] }}
124
+ */
125
+ export function classify(info, slot, shape) {
126
+ const found = [];
127
+ const notes = [];
128
+ const add = (status, text) => found.push({ status, text });
129
+ const vector = info.format === 'svg';
130
+ let w = info.width;
131
+ let h = info.height;
132
+ if (info.margin) {
133
+ const m = info.margin;
134
+ const sides = m.top && m.bottom && m.left && m.right ? 'all round' : m.top && m.bottom ? 'top and bottom' : 'left and right';
135
+ add('fixable', `It has a plain border baked in (${sides}). Trim it to the picture inside.`);
136
+ w = m.width;
137
+ h = m.height;
138
+ }
139
+ const target = shapeValue(shape);
140
+ const words = shapeWords(shape);
141
+ const version = words === 'square' ? 'a square version' : `a ${words} version`;
142
+ let cropW = w;
143
+ let cropH = h;
144
+ if (target) {
145
+ const a = w / h;
146
+ const off = Math.max(a, target) / Math.min(a, target) - 1;
147
+ const lost = 1 - 1 / (1 + off);
148
+ if (slot.fit === 'contain') {
149
+ if (off > TOLERANCE.fit) add('remake', `It is ${pct(off)} off the ${words} shape this place needs, so it would look uneven next to the others. It needs ${version}.`);
150
+ else if (off > TOLERANCE.same) add('fixable', `It is ${pct(off)} off the ${words} shape: a slight trim makes it fit.`);
151
+ } else {
152
+ if (a > target) cropW = h * target;
153
+ else cropH = w / target;
154
+ const where = a > target ? 'sides' : 'top and bottom';
155
+ if (off > TOLERANCE.crop) add('remake', `It is far from the ${words} shape this place needs: the site would crop away ${pct(lost)} of it. It needs ${version}.`);
156
+ else if (off > TOLERANCE.fit) add('fixable', `The site crops about ${pct(lost)} off its ${where} to fit ${words}. Fine if the subject is in the middle; otherwise crop it around the subject${slot.focus ? ', or set a focus point' : ''}.`);
157
+ }
158
+ }
159
+ if (!vector) {
160
+ const need = sizeFor(slot.min, shape);
161
+ const rec = sizeFor(slot.recommended, shape);
162
+ const cropped = cropW !== w || cropH !== h;
163
+ if ((need.width && cropW < need.width - 0.5) || (need.height && cropH < need.height - 0.5)) {
164
+ add('remake', `It is too small: ${w} × ${h} pixels${cropped ? ` (${round(cropW)} × ${round(cropH)} once cropped)` : ''}, and this place needs at least ${sizeWords(need)}. It needs a larger original.`);
165
+ } else if ((rec.width && cropW < rec.width - 0.5) || (rec.height && cropH < rec.height - 0.5)) {
166
+ notes.push(`Smaller than the recommended ${sizeWords(rec)}, so it may look a little soft on large screens.`);
167
+ }
168
+ if (info.width > MAX_WIDTH) {
169
+ const to = rec.width ?? (rec.height ? round((rec.height * info.width) / info.height) : MAX_WIDTH);
170
+ add('fixable', `It is ${info.width} pixels wide: scale it down to ${Math.min(to, MAX_WIDTH)} wide, so the page loads faster.`);
171
+ }
172
+ }
173
+ if (slot.alpha && info.format === 'jpeg') {
174
+ add('remake', 'This place needs a see-through background, which a JPEG can’t have. It needs a PNG or SVG.');
175
+ }
176
+ const status = found.reduce((s, r) => (RANK[r.status] > RANK[s] ? r.status : s), 'ok');
177
+ return { status, reasons: found.map((r) => r.text), notes };
178
+ }
179
+
180
+ /** A media-friendly file name: lower case, words joined by hyphens (`Poster One.JPG` → `poster-one.jpg`). */
181
+ export function tidyName(name) {
182
+ const ext = extname(name);
183
+ const stem = basename(name, ext)
184
+ .normalize('NFKD')
185
+ .replace(/[̀-ͯ]/g, '')
186
+ .toLowerCase()
187
+ .replace(/[^a-z0-9]+/g, '-')
188
+ .replace(/^-+|-+$/g, '');
189
+ return `${stem || 'picture'}${ext.toLowerCase()}`;
190
+ }
191
+
192
+ /** The media rules a file breaks, in plain words. */
193
+ export function mediaRules(src, info, exif) {
194
+ const rules = [];
195
+ const name = decodeURIComponent(basename(src.split(/[?#]/)[0]));
196
+ if (tidyName(name) !== name) rules.push(`Rename it "${tidyName(name)}": lower case, with words joined by hyphens.`);
197
+ if (info && info.format !== 'svg' && info.width > MAX_WIDTH) rules.push(`It is ${info.width} pixels wide: keep pictures ${MAX_WIDTH} pixels wide or less.`);
198
+ if (exif?.gps) rules.push('It carries location data (where it was taken): remove it before it goes on the site.');
199
+ return rules;
200
+ }
201
+
202
+ // ── Finding the pictures a site uses ──
203
+
204
+ const PAGES = 'src/content/pages';
205
+ const POSTS = 'src/content/posts';
206
+
207
+ function* filesIn(dir, test) {
208
+ if (!existsSync(dir)) return;
209
+ for (const name of readdirSync(dir).sort()) {
210
+ const p = join(dir, name);
211
+ if (statSync(p).isDirectory()) yield* filesIn(p, test);
212
+ else if (test(name)) yield p;
213
+ }
214
+ }
215
+ function readJson(path) {
216
+ try {
217
+ return JSON.parse(readFileSync(path, 'utf8'));
218
+ } catch {
219
+ return null;
220
+ }
221
+ }
222
+ /** A markdown post's frontmatter fields that are plain one-line values. */
223
+ export function frontmatter(text) {
224
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
225
+ const out = {};
226
+ if (!m) return out;
227
+ for (const line of m[1].split(/\r?\n/)) {
228
+ const f = /^([A-Za-z_][\w-]*):\s*(.*?)\s*$/.exec(line);
229
+ if (f && f[2] !== '') out[f[1]] = f[2].replace(/^(['"])(.*)\1$/, '$2');
230
+ }
231
+ return out;
232
+ }
233
+
234
+ /** Each value at a key's path, with the objects it sits in (block first) and its list positions. */
235
+ function* valuesAt(obj, path, ancestors = [obj], positions = []) {
236
+ if (path.length === 0) {
237
+ yield { value: obj, ancestors, positions };
238
+ return;
239
+ }
240
+ const [seg, ...rest] = path;
241
+ const list = seg.endsWith('[]');
242
+ const name = list ? seg.slice(0, -2) : seg;
243
+ const next = obj?.[name];
244
+ if (next == null) return;
245
+ if (list) {
246
+ if (!Array.isArray(next)) return;
247
+ for (let i = 0; i < next.length; i++) yield* valuesAt(next[i], rest, [...ancestors, next[i]], [...positions, { name, index: i }]);
248
+ } else {
249
+ yield* valuesAt(next, rest, [...ancestors, next], positions);
250
+ }
251
+ }
252
+ const singular = (name) => name.replace(/ies$/, 'y').replace(/s$/, '');
253
+
254
+ /** The slot keys by what they belong to: a block type, `page`, `post`, or a settings collection. */
255
+ function keysByOwner() {
256
+ const by = {};
257
+ for (const key of Object.keys(IMAGE_SLOTS)) (by[splitKey(key)[0]] ??= []).push(key);
258
+ return by;
259
+ }
260
+
261
+ /**
262
+ * Every picture the site's content shows in an image slot.
263
+ * @param {string} root the site's folder
264
+ * @returns {{ src: string, key: string, slot: import('../content/imageSlots.mjs').ImageSlot, shape: string, where: string }[]}
265
+ */
266
+ export function findUses(root) {
267
+ const byOwner = keysByOwner();
268
+ const uses = [];
269
+ const collect = (owner, data, where) => {
270
+ for (const key of byOwner[owner] ?? []) {
271
+ const [, path] = splitKey(key);
272
+ for (const { value, ancestors, positions } of valuesAt(data, path)) {
273
+ if (typeof value !== 'string' || value.trim() === '') continue;
274
+ const last = positions[positions.length - 1];
275
+ const item = last ? ancestors[path.findLastIndex((s) => s.endsWith('[]')) + 1] : data;
276
+ const slot = slotModes(key).find((m) => !m.when || m.when({ block: data, item: item ?? data }));
277
+ if (!slot) continue; // the block doesn't show this picture with these settings
278
+ const shape = resolveShape(slot, key, ancestors);
279
+ const at = positions.map((p) => `${singular(p.name)} ${p.index + 1}`).join(', ');
280
+ uses.push({ src: value.trim(), key, slot, shape, where: [where, at].filter(Boolean).join(', ') });
281
+ }
282
+ }
283
+ };
284
+ const walkBlocks = (blocks, where) => {
285
+ (Array.isArray(blocks) ? blocks : []).forEach((block, i) => {
286
+ if (!block || typeof block !== 'object' || block.enabled === false) return;
287
+ const here = `${where} ${i + 1} (${block.type})`;
288
+ collect(block.type, block, here);
289
+ if (Array.isArray(block.blocks)) walkBlocks(block.blocks, `${here}, block`);
290
+ });
291
+ };
292
+
293
+ const pagesDir = join(root, PAGES);
294
+ for (const file of filesIn(pagesDir, (n) => n.endsWith('.json'))) {
295
+ const page = readJson(file);
296
+ if (!page) continue;
297
+ const slug = relative(pagesDir, file).replace(/\\/g, '/').replace(/\.json$/, '');
298
+ const name = `page "${slug}"${page.draft === true ? ' (a draft)' : ''}`;
299
+ collect('page', page, name);
300
+ walkBlocks(page.blocks, `${name}, block`);
301
+ }
302
+ for (const file of filesIn(join(root, POSTS), (n) => /\.mdx?$/.test(n))) {
303
+ const fm = frontmatter(readFileSync(file, 'utf8'));
304
+ const slug = relative(join(root, POSTS), file).replace(/\\/g, '/').replace(/\.mdx?$/, '');
305
+ collect('post', fm, `post "${slug}"${fm.draft === 'true' ? ' (a draft)' : ''}`);
306
+ }
307
+ // Settings: every other owner is a settings collection, a folder of JSON files.
308
+ const blockOwners = new Set(['page', 'post']);
309
+ for (const owner of Object.keys(byOwner)) {
310
+ if (blockOwners.has(owner) || !/Settings$/.test(owner)) continue;
311
+ for (const file of filesIn(join(root, 'src/content', owner), (n) => n.endsWith('.json'))) {
312
+ const data = readJson(file);
313
+ if (data) collect(owner, data, `${owner} (${relative(root, file).replace(/\\/g, '/')})`);
314
+ }
315
+ }
316
+ return uses;
317
+ }
318
+
319
+ const isExternal = (src) => /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(src);
320
+
321
+ /**
322
+ * Check every picture the site uses against its place.
323
+ * @param {string} root the site's folder
324
+ * @param {{ sharp?: any }} [opts] sharp, to find baked-in borders (optional)
325
+ */
326
+ export async function checkSite(root, { sharp } = {}) {
327
+ const files = new Map(); // src → what's known about the file
328
+ const results = [];
329
+ const elsewhere = [];
330
+ for (const use of findUses(root)) {
331
+ if (isExternal(use.src) || !use.src.startsWith('/')) {
332
+ elsewhere.push(use.src);
333
+ continue;
334
+ }
335
+ let file = files.get(use.src);
336
+ if (!file) {
337
+ const path = join(root, 'public', decodeURIComponent(use.src.split(/[?#]/)[0]));
338
+ file = { src: use.src, path, exists: existsSync(path) };
339
+ if (file.exists) {
340
+ const bytes = readFileSync(path);
341
+ const format = formatOf(bytes);
342
+ const exif = readExif(bytes);
343
+ let size = imageSize(bytes);
344
+ if (!size && sharp) {
345
+ try {
346
+ const m = await sharp(bytes).metadata();
347
+ if (m.width && m.height) size = { width: m.width, height: m.height };
348
+ } catch {
349
+ /* not a picture sharp can read either */
350
+ }
351
+ }
352
+ const turned = exif.orientation >= 5 && exif.orientation <= 8;
353
+ if (size && turned) size = { width: size.height, height: size.width };
354
+ file.info = size ? { ...size, format } : null;
355
+ file.exif = exif;
356
+ file.bytes = bytes;
357
+ file.turned = turned;
358
+ }
359
+ file.rules = mediaRules(use.src, file.info, file.exif);
360
+ files.set(use.src, file);
361
+ }
362
+ let verdict;
363
+ if (!file.exists) {
364
+ verdict = { status: 'missing', reasons: [`There's no file at public${decodeURIComponent(use.src)}.`], notes: [] };
365
+ } else if (!file.info) {
366
+ verdict = { status: 'remake', reasons: ['Its size can’t be read. It needs saving as a JPEG, PNG, WebP or SVG.'], notes: [] };
367
+ } else {
368
+ // A border is looked for once per file, and never on a logo or icon (their own space is theirs).
369
+ if (file.margin === undefined) file.margin = file.info.format === 'svg' ? null : await detectMargin(sharp, file.bytes);
370
+ let margin = !use.slot.alpha && file.margin ? file.margin : null;
371
+ if (margin && file.turned) margin = { ...margin, width: margin.height, height: margin.width };
372
+ verdict = classify({ ...file.info, margin }, use.slot, use.shape);
373
+ }
374
+ results.push({
375
+ src: use.src,
376
+ where: use.where,
377
+ slot: use.key,
378
+ place: use.slot.label,
379
+ shape: use.shape,
380
+ size: file.info ? { width: file.info.width, height: file.info.height } : null,
381
+ ...verdict,
382
+ });
383
+ }
384
+ const summary = { ok: 0, fixable: 0, remake: 0, missing: 0 };
385
+ for (const r of results) summary[r.status]++;
386
+ const fileList = [...files.values()].map((f) => ({ src: f.src, rules: f.rules }));
387
+ return { uses: results, files: fileList, summary, elsewhere: [...new Set(elsewhere)] };
388
+ }
389
+
390
+ const HEADINGS = {
391
+ remake: 'Remake: these need a new version from the original',
392
+ missing: 'Missing: these files aren’t in the site',
393
+ fixable: 'Fixable: close, and a small change makes them right',
394
+ ok: 'Ok',
395
+ };
396
+
397
+ /** `ferst-media check` in plain words. */
398
+ export function formatCheck(result) {
399
+ const out = [];
400
+ const { uses, summary } = result;
401
+ if (uses.length === 0 && result.elsewhere.length === 0) {
402
+ out.push('No pictures found in this site’s pages, posts or logo settings.');
403
+ return out.join('\n');
404
+ }
405
+ const fileCount = new Set(uses.map((u) => u.src)).size;
406
+ out.push(`Pictures on this site: ${uses.length} ${uses.length === 1 ? 'use' : 'uses'} of ${fileCount} ${fileCount === 1 ? 'file' : 'files'}.`);
407
+ out.push(
408
+ ` ${summary.ok} ok, ${summary.fixable} fixable, ${summary.remake} to remake${summary.missing ? `, ${summary.missing} missing` : ''}.`,
409
+ );
410
+ for (const status of ['remake', 'missing', 'fixable', 'ok']) {
411
+ const group = uses.filter((u) => u.status === status);
412
+ if (group.length === 0) continue;
413
+ out.push('', HEADINGS[status]);
414
+ for (const u of group) {
415
+ const size = u.size ? `, ${u.size.width} × ${u.size.height}` : '';
416
+ out.push(` ${u.src}${size}`);
417
+ out.push(` ${u.place} (${shapeWords(u.shape)}): ${u.where}`);
418
+ for (const r of u.reasons) out.push(` - ${r}`);
419
+ for (const n of u.notes) out.push(` - ${n}`);
420
+ }
421
+ }
422
+ const broken = result.files.filter((f) => f.rules.length);
423
+ if (broken.length) {
424
+ out.push('', 'Media rules');
425
+ for (const f of broken) {
426
+ out.push(` ${f.src}`);
427
+ for (const r of f.rules) out.push(` - ${r}`);
428
+ }
429
+ }
430
+ if (result.elsewhere.length) {
431
+ out.push('', `Not checked (kept elsewhere): ${result.elsewhere.join(', ')}`);
432
+ }
433
+ out.push('', 'These are suggestions: the site builds either way. `ferst-media brief` lists the size each place needs.');
434
+ return out.join('\n');
435
+ }
436
+
437
+ // ── The asset brief ──
438
+
439
+ /**
440
+ * The places this site shows pictures, each with its shape and sizes, from the pages and
441
+ * settings it has (or, with `all`, every place the engine has).
442
+ */
443
+ export function briefSite(root, { all = false } = {}) {
444
+ const groups = new Map();
445
+ const add = (key, slot, shape, where) => {
446
+ const id = `${key}|${slot.label}|${shape}`;
447
+ const g = groups.get(id) ?? { slot: key, place: slot.label, shape, spec: slot, uses: [] };
448
+ if (where) g.uses.push(where);
449
+ groups.set(id, g);
450
+ };
451
+ if (all) {
452
+ for (const key of Object.keys(IMAGE_SLOTS)) {
453
+ for (const slot of slotModes(key)) {
454
+ if (slot.ratio !== 'any' && shapeValue(slot.ratio) === null) {
455
+ const values = slot.shapes ? Object.values(slot.shapes) : [resolveShape(slot, key, [{}])];
456
+ for (const shape of new Set(values)) add(key, slot, shape);
457
+ } else add(key, slot, slot.ratio);
458
+ }
459
+ }
460
+ } else {
461
+ for (const u of findUses(root)) add(u.key, u.slot, u.shape, u.where);
462
+ }
463
+ return [...groups.values()].map((g) => {
464
+ const s = g.spec;
465
+ return {
466
+ slot: g.slot,
467
+ place: g.place,
468
+ shape: g.shape,
469
+ recommended: sizeFor(s.recommended, g.shape),
470
+ min: sizeFor(s.min, g.shape),
471
+ maxWidth: s.max.width,
472
+ fit: s.fit,
473
+ focus: s.focus,
474
+ safe: s.safe,
475
+ text: s.text,
476
+ textNote: s.textNote,
477
+ alpha: s.alpha,
478
+ uses: g.uses,
479
+ };
480
+ });
481
+ }
482
+
483
+ const shapeLine = (shape) => {
484
+ const r = shapeValue(shape);
485
+ if (!r) return 'Any shape: shown whole, as it is.';
486
+ const kind = r === 1 ? 'square' : r > 1 ? 'landscape' : 'portrait';
487
+ return r === 1 ? 'Square.' : `${shapeWords(shape)}, ${kind}.`;
488
+ };
489
+
490
+ /** `ferst-media brief` in plain words, ready to send to whoever supplies the pictures. */
491
+ export function formatBrief(entries, { siteName } = {}) {
492
+ const out = [];
493
+ out.push(`Pictures for ${siteName || 'this site'}: a brief`, '');
494
+ if (entries.length === 0) {
495
+ out.push('The pages don’t show any pictures yet. Run `ferst-media brief --all` for every place a picture can go.');
496
+ return out.join('\n');
497
+ }
498
+ out.push(
499
+ 'Each place a picture appears, with the shape and size that look best there.',
500
+ 'For every picture:',
501
+ ` - Send it at the recommended size or larger, and no wider than ${MAX_WIDTH} pixels.`,
502
+ ' - Name files in lower case with hyphens, like summer-camp-2026.jpg.',
503
+ ' - Photos as JPEG; logos and icons as SVG or PNG.',
504
+ ' - Remove location data (where a photo was taken) before sending.',
505
+ );
506
+ for (const e of entries) {
507
+ out.push('', e.place);
508
+ if (e.uses.length) {
509
+ const shown = e.uses.slice(0, 3).join('; ');
510
+ out.push(` Used ${e.uses.length === 1 ? 'once' : `${e.uses.length} times`}: ${shown}${e.uses.length > 3 ? '; …' : ''}`);
511
+ }
512
+ out.push(` Shape: ${shapeLine(e.shape)}`);
513
+ out.push(` Size: ${sizeWords(e.recommended)} recommended; at least ${sizeWords(e.min)}.`);
514
+ out.push(
515
+ e.fit === 'cover'
516
+ ? ` Cropped to fill the shape${e.focus ? ', around a focus point if one is set' : ''}.`
517
+ : ' Never cropped: the whole picture shows.',
518
+ );
519
+ out.push(` Where things stay in view: ${e.safe}`);
520
+ out.push(` Words in the picture: ${e.text ? 'fine' : 'best avoided'}.${e.textNote ? ` ${e.textNote}` : ''}`);
521
+ if (e.alpha) out.push(' Background: see-through (an SVG or PNG), so it sits on any colour.');
522
+ }
523
+ return out.join('\n');
524
+ }