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
package/lib/book.ts CHANGED
@@ -1,378 +1,416 @@
1
- /**
2
- * A "Book" block lets visitors book a time for one of the organisation's offers (the Ferst Events
3
- * and bookings module). The block names the offer; its name, length and who gives it are the
4
- * organisation's, read from the platform at build time, and its free times are read in the browser
5
- * (they change by the minute). A picked time is held by the platform for the visitor while they
6
- * give their details; the page never decides what's free.
7
- *
8
- * A booking is always the site's own, so the site must say who it is (`siteId` in
9
- * ferst-site.json). An offer that isn't booked online, or a platform that can't be reached, fails
10
- * the build: better the last good deploy stays live than a Book button that can't book.
11
- *
12
- * One block, shaped by the offer (0.13.0; myai4-webdev docs/EVENTS.md slice 6c): the platform says
13
- * how it's booked (`mode`): `times`, a time of its length (a haircut); `chosen`, a start and an end
14
- * (hall hire), its price worked out as the visitor chooses; `places`, places at one of its coming
15
- * dates (a class, a concert). The page names the offer, and may name one event of it.
16
- *
17
- * Or a person or a place (0.14.0; the maintainer 2026-11-24: "we need both and its up to the person
18
- * configuring the module to pick what is suitable"): `resource` alone books everything they provide
19
- * online, the visitor choosing which in the block; with `service`, that offer with them only.
20
- */
21
- export type BookMode = 'times' | 'chosen' | 'places';
22
- export interface BookResource { id: string; name: string; kind: 'place' | 'person' | null }
23
- export interface BookService {
24
- id: string;
25
- name: string;
26
- description: string;
27
- minutes: number;
28
- /** How it's booked; what it costs, as the owner put it ("£25 an hour", "Free"). */
29
- mode: BookMode;
30
- price: string;
31
- /** A fixed length, or chosen when booking (from `minutes`, in steps of `step`). */
32
- lasts: 'fixed' | 'chosen';
33
- step: number;
34
- /** One event of the offer the block books (a class's or concert's), or null for all its dates. */
35
- event: string | null;
36
- /** The person or place the block books it with (then `resources` is just them), or null for anyone who gives it. */
37
- resource: string | null;
38
- /** Who or what gives it (a visitor may choose, or take anyone available); a place is "at", a person "with". */
39
- resources: BookResource[];
40
- /** Where the browser reads free times (`?from&to`) and holds a time (`/hold`). */
41
- definition: string;
42
- /** Where the browser books a held time (`/:hold`) or lets it go. */
43
- holds: string;
44
- }
45
-
46
- type FetchFn = (input: string, init?: RequestInit) => Promise<Response>;
47
-
48
- /** Today's date in London ('YYYY-MM-DD'). */
49
- export const londonDay = (d = new Date()): string => d.toLocaleDateString('en-CA', { timeZone: 'Europe/London' });
50
- /** A date some days on ('YYYY-MM-DD'). */
51
- export function addDays(day: string, n: number): string {
52
- const [y, m, d] = day.split('-').map(Number);
53
- return new Date(Date.UTC(y, m - 1, d + n)).toISOString().slice(0, 10);
54
- }
55
-
56
- /** 30 minutes, 1 hour, 1 hour 30 minutes. */
57
- export function lengthText(minutes: number): string {
58
- const h = Math.floor(minutes / 60);
59
- const rest = minutes % 60;
60
- return [h ? `${h} hour${h === 1 ? '' : 's'}` : '', rest ? `${rest} minutes` : ''].filter(Boolean).join(' ');
61
- }
62
-
63
- const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
64
- const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
65
- const WEEKDAYS_LONG = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
66
- const MONTHS_LONG = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
67
-
68
- /** A day, short enough for a row of days: { weekday: 'Mon', date: '4 Jan' }. */
69
- export function dayChip(day: string): { weekday: string; date: string } {
70
- const [y, m, d] = day.split('-').map(Number);
71
- return { weekday: WEEKDAYS[new Date(Date.UTC(y, m - 1, d)).getUTCDay()], date: `${d} ${MONTHS[m - 1]}` };
72
- }
73
-
74
- /** 'Monday 4 January at 10:00', from a London time ('YYYY-MM-DDTHH:MM'). */
75
- export function whenText(local: string): string {
76
- const [y, m, d] = local.slice(0, 10).split('-').map(Number);
77
- return `${WEEKDAYS_LONG[new Date(Date.UTC(y, m - 1, d)).getUTCDay()]} ${d} ${MONTHS_LONG[m - 1]} at ${local.slice(11, 16)}`;
78
- }
79
-
80
- /** What to tell the visitor when the platform says no. */
81
- export function bookingMessage(code: string): string {
82
- switch (code) {
83
- case 'time_taken': return 'That time has just been taken. Please choose another.';
84
- case 'hold_expired': return 'We kept that time for 10 minutes and it has gone. Please choose a time again.';
85
- case 'too_many_holds': return 'You’re already holding a few times. Book one, or let one go, first.';
86
- case 'rate_limited': return 'Too many tries in a short time. Please wait a minute and try again.';
87
- case 'name_required': return 'Please give your name.';
88
- case 'invalid_email': return 'Please give an email address we can send your booking to.';
89
- case 'bookings_not_open': return 'This website isn’t taking bookings just now.';
90
- case 'not_enough_places': return 'There aren’t that many places left. Please choose fewer, or another date.';
91
- case 'invalid_date': return 'That date isn’t on offer any more. Please choose another.';
92
- case 'invalid_length': case 'invalid_end': return 'Please choose when it ends again.';
93
- case 'one_day': return 'Online, a booking starts and ends on the same day. For longer, please ask us.';
94
- default: return 'The booking couldn’t be made just now. Please try again.';
95
- }
96
- }
97
-
98
- /** One coming date of a class or a concert: its places left and its price. */
99
- export interface EventDate {
100
- event_id: string; title: string; description?: string; start: string; end: string; places: number; left: number; price: string;
101
- /** For search engines (0.15.0, slice 6d): a place's price in pence (0 free; null when not priced by the place), its place and who leads it. */
102
- amount?: number | null; where?: { name: string } | null; with?: string[];
103
- }
104
-
105
- // ── For search engines (0.15.0; myai4-webdev docs/EVENTS.md slice 6d) ──────────────────────────────
106
- // Each coming date of a class or an event is a schema.org Event, written into the page at build and
107
- // brought up to date (its places left) as the page loads. Only what's booked by places: a haircut or a
108
- // hire becomes one date only once it's booked, so it's nothing to search for.
109
-
110
- /** One of the site's places (siteSettings.places), whose address an event there is given. */
111
- export interface SitePlace { name?: string; streetAddress?: string; locality?: string; postalCode?: string; country?: string }
112
- /** What the page knows that the platform doesn't: its own address, the organisation, and its places. */
113
- export interface EventsContext { url: string; organisation: { name?: string; url: string }; places: SitePlace[] }
114
-
115
- /** '2026-12-19T19:30:00+00:00': a London time with its offset, as schema.org wants it. */
116
- export function londonWithOffset(local: string): string {
117
- const [y, m, d] = local.slice(0, 10).split('-').map(Number);
118
- const guess = new Date(Date.UTC(y, m - 1, d, Number(local.slice(11, 13)), Number(local.slice(14, 16))));
119
- const name = new Intl.DateTimeFormat('en-GB', { timeZone: 'Europe/London', timeZoneName: 'longOffset' })
120
- .formatToParts(guess).find((p) => p.type === 'timeZoneName')?.value ?? 'GMT';
121
- const off = name.replace('GMT', '') || '+00:00';
122
- return `${local.slice(0, 16)}:00${off}`;
123
- }
124
-
125
- const postal = (p: SitePlace) => {
126
- const a: Record<string, string> = { '@type': 'PostalAddress' };
127
- if (p.streetAddress) a.streetAddress = p.streetAddress;
128
- if (p.locality) a.addressLocality = p.locality;
129
- if (p.postalCode) a.postalCode = p.postalCode;
130
- a.addressCountry = p.country || 'GB';
131
- return a;
132
- };
133
- const filled = (p: SitePlace) => !!(p && (p.name || p.streetAddress || p.postalCode));
134
-
135
- /** Where a date is, with its address when it's one of the site's places (or the site has only one). */
136
- function locationOf(where: { name: string } | null | undefined, places: SitePlace[]): Record<string, unknown> | undefined {
137
- const known = places.filter(filled);
138
- const same = where ? known.find((p) => p.name?.trim().toLowerCase() === where.name.trim().toLowerCase()) : undefined;
139
- const only = known.length === 1 ? known[0] : undefined;
140
- const at = same ?? (where ? undefined : only);
141
- if (where && !same && only && !only.name) return { '@type': 'Place', name: where.name, address: postal(only) };
142
- if (!where && !at) return undefined;
143
- const place: Record<string, unknown> = { '@type': 'Place', name: where?.name ?? at?.name };
144
- if (at && (at.streetAddress || at.postalCode || at.locality)) place.address = postal(at);
145
- return place;
146
- }
147
-
148
- /** The schema.org Events for a class's or an event's coming dates, or null when there are none. */
149
- export function eventsData(dates: EventDate[], ctx: EventsContext): { '@context': string; '@graph': Array<Record<string, unknown>> } | null {
150
- if (!dates.length) return null;
151
- const graph = dates.slice(0, 50).map((d) => {
152
- const e: Record<string, unknown> = { '@type': 'Event', name: d.title };
153
- if (d.description) e.description = d.description;
154
- e.startDate = londonWithOffset(d.start);
155
- e.endDate = londonWithOffset(d.end);
156
- e.eventStatus = 'https://schema.org/EventScheduled';
157
- e.eventAttendanceMode = 'https://schema.org/OfflineEventAttendanceMode';
158
- const location = locationOf(d.where, ctx.places);
159
- if (location) e.location = location;
160
- e.organizer = { '@type': 'Organization', ...(ctx.organisation.name ? { name: ctx.organisation.name } : {}), url: ctx.organisation.url };
161
- if (d.with?.length) e.performer = d.with.map((name) => ({ '@type': 'Person', name }));
162
- e.maximumAttendeeCapacity = d.places;
163
- e.remainingAttendeeCapacity = d.left;
164
- if (typeof d.amount === 'number') {
165
- e.offers = { '@type': 'Offer', price: (d.amount / 100).toFixed(2), priceCurrency: 'GBP', availability: `https://schema.org/${d.left > 0 ? 'InStock' : 'SoldOut'}`, url: ctx.url };
166
- }
167
- e.url = ctx.url;
168
- return e;
169
- });
170
- return { '@context': 'https://schema.org', '@graph': graph };
171
- }
172
-
173
- /** The JSON for a page's script tag: `<` escaped so it can't close the tag. */
174
- export const ldJson = (data: unknown) => JSON.stringify(data).replace(/</g, '\\u003c');
175
-
176
- /**
177
- * A class's or an event's dates for the coming month, read at build for search engines. Never fails the
178
- * build: the block still works (it reads its dates as the page loads), search engines just aren't told.
179
- */
180
- export async function loadEventDates(definition: string, opts: { event?: string | null; resource?: string | null; now?: Date; fetch?: FetchFn } = {}): Promise<EventDate[]> {
181
- const doFetch = opts.fetch ?? ((u: string, i?: RequestInit) => fetch(u, i));
182
- const from = londonDay(opts.now);
183
- const q = `from=${from}&to=${addDays(from, 30)}${opts.event ? `&event=${encodeURIComponent(opts.event)}` : ''}${opts.resource ? `&resource=${encodeURIComponent(opts.resource)}` : ''}`;
184
- try {
185
- const res = await doFetch(`${definition}?${q}`, { headers: { Accept: 'application/json' } });
186
- if (!res.ok) return [];
187
- const body = (await res.json()) as { events?: EventDate[] };
188
- return Array.isArray(body.events) ? body.events : [];
189
- } catch {
190
- return [];
191
- }
192
- }
193
-
194
- /** The platform's answer for an offer's free times (or, booked by places, its coming dates), as the block reads it. */
195
- export interface TimesAnswer {
196
- service: { id: string; name: string; description?: string; minutes: number; mode?: BookMode; lasts?: 'fixed' | 'chosen'; step_minutes?: number; price?: string };
197
- resources: Array<{ id: string; name: string; kind?: 'place' | 'person' }>;
198
- days: Array<{ day: string; times: Array<{ time: string; start: string; resources: string[] }> }>;
199
- events?: EventDate[];
200
- }
201
-
202
- const join = (names: string[]) => (names.length <= 1 ? names.join('') : `${names.slice(0, -1).join(', ')} or ${names[names.length - 1]}`);
203
- /** "with Sam or Alex", "at the Hall": a place is somewhere to be, a person someone to see. */
204
- export function whereText(resources: BookResource[]): string {
205
- const places = resources.filter((r) => r.kind === 'place').map((r) => r.name);
206
- const people = resources.filter((r) => r.kind !== 'place').map((r) => r.name);
207
- return [people.length ? `with ${join(people)}` : '', places.length ? `at ${join(places)}` : ''].filter(Boolean).join(', ');
208
- }
209
-
210
- /**
211
- * Which of several places are free at a time, for a calendar of hire across them with "Anywhere free"
212
- * (2026-11-24): "All free", or their names. Null when it isn't said: one place, or people.
213
- */
214
- export function whichFree(free: string[], places: Array<{ id: string; name: string; kind?: string | null }>): string | null {
215
- if (places.length < 2 || !places.every((r) => r.kind === 'place')) return null;
216
- const names = places.filter((r) => free.includes(r.id)).map((r) => r.name);
217
- return names.length === places.length ? 'All free' : names.join(', ');
218
- }
219
-
220
- /** The block's line under its name: "30 minutes · with Sam or Alex · £18 a booking", "From 1 hour · at the Hall · £25 an hour". */
221
- export function metaLine(d: Pick<BookService, 'mode' | 'minutes' | 'price' | 'resources'>): string {
222
- const length = d.mode === 'chosen' ? `From ${lengthText(d.minutes)}` : lengthText(d.minutes);
223
- return [length, whereText(d.resources), d.price].filter(Boolean).join(' · ');
224
- }
225
-
226
- const mins = (hhmm: string) => Number(hhmm.slice(0, 2)) * 60 + Number(hhmm.slice(3, 5));
227
- const hhmm = (m: number) => `${String(Math.floor(m / 60)).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`;
228
- /**
229
- * The ends a hall hire starting at `start` can have: at least `minutes`, in steps of `step`, while
230
- * the time stays free. `free` is the day's free starts for its shortest length (the platform's
231
- * answer); a longer booking is free while every start under it is. The platform checks again on hold.
232
- */
233
- export function endChoices(free: string[], start: string, minutes: number, step: number): string[] {
234
- const at = free.map(mins).sort((a, b) => a - b);
235
- const set = new Set(at);
236
- const s = mins(start);
237
- if (!set.has(s)) return [];
238
- const gaps = at.slice(1).map((m, i) => m - at[i]).filter((g) => g > 0);
239
- const grid = gaps.length ? Math.min(...gaps) : step;
240
- const out: string[] = [];
241
- for (let end = s + minutes; end <= 24 * 60; end += step) {
242
- let ok = true;
243
- for (let t = s; t <= end - minutes; t += grid) if (!set.has(t)) { ok = false; break; }
244
- if (!ok) break;
245
- out.push(end === 24 * 60 ? '24:00' : hhmm(end));
246
- }
247
- return out;
248
- }
249
-
250
- /** A booking, for "Add to calendar": its title, UTC times, where, and its id. */
251
- export interface Booked { title: string; starts_at: string; ends_at: string; location?: string | null; uid?: string }
252
- const utcBasic = (iso: string) => new Date(iso).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
253
- /** Add to Google Calendar. */
254
- export function googleCalendarLink(b: Booked): string {
255
- const q = [`action=TEMPLATE`, `text=${encodeURIComponent(b.title)}`, `dates=${encodeURIComponent(`${utcBasic(b.starts_at)}/${utcBasic(b.ends_at)}`)}`];
256
- if (b.location) q.push(`location=${encodeURIComponent(b.location)}`);
257
- return `https://calendar.google.com/calendar/render?${q.join('&')}`;
258
- }
259
- const icsText = (t: string) => t.replace(/\\/g, '\\\\').replace(/;/g, '\\;').replace(/,/g, '\\,').replace(/\r?\n/g, '\\n');
260
- /** A calendar file for Apple Calendar, Outlook and the rest. */
261
- export function calendarFile(b: Booked, stamp = new Date()): string {
262
- return [
263
- 'BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//Ferst//Book//EN', 'METHOD:PUBLISH', 'BEGIN:VEVENT',
264
- `UID:${b.uid ?? `${utcBasic(b.starts_at)}`}@ferst.co.uk`, `DTSTAMP:${utcBasic(stamp.toISOString())}`,
265
- `DTSTART:${utcBasic(b.starts_at)}`, `DTEND:${utcBasic(b.ends_at)}`, `SUMMARY:${icsText(b.title)}`,
266
- ...(b.location ? [`LOCATION:${icsText(b.location)}`] : []),
267
- 'END:VEVENT', 'END:VCALENDAR', '',
268
- ].join('\r\n');
269
- }
270
-
271
- /** What a block names: an offer, a person or place, or both. Naming neither fails the build. */
272
- export function bookTarget(props: { service?: string | null; resource?: string | null }): { service: string | null; resource: string | null } {
273
- const service = props.service || null;
274
- const resource = props.resource || null;
275
- if (!service && !resource) {
276
- throw new Error('Book block: name an offer ("service": "<id>"), a person or place ("resource": "<id>"), or both. Run `npx ferst-modules` to list what this site takes bookings for.');
277
- }
278
- return { service, resource };
279
- }
280
-
281
- /** A person or a place, as a block naming them shows them. */
282
- export interface BookWho extends BookResource { description: string }
283
-
284
- const cache = new Map<string, Promise<BookService>>();
285
-
286
- export function loadBookService(service: string, opts: { base: string; siteId?: string | null; fetch?: FetchFn; now?: Date; event?: string | null; resource?: string | null }): Promise<BookService> {
287
- const key = `${opts.base}|${opts.siteId ?? ''}|${service}|${opts.event ?? ''}|${opts.resource ?? ''}`;
288
- let hit = cache.get(key);
289
- if (!hit) {
290
- hit = fetchService(service, opts.base, opts.siteId ?? null, opts.fetch ?? fetch, opts.now ?? new Date(), opts.event ?? null, opts.resource ?? null);
291
- cache.set(key, hit);
292
- hit.catch(() => cache.delete(key)); // a failure is retried by the next caller
293
- }
294
- return hit;
295
- }
296
-
297
- const noSiteId = () => new Error(`Book block: this site doesn't say who it is, so it can't take bookings. Add "siteId" to ferst-site.json (or set FERST_SITE_ID).`);
298
-
299
- async function fetchService(service: string, base: string, siteId: string | null, fetchFn: FetchFn, now: Date, event: string | null, resource: string | null): Promise<BookService> {
300
- if (!siteId) throw noSiteId();
301
- const definition = `${base}/sites/${encodeURIComponent(siteId)}/book/${encodeURIComponent(service)}`;
302
- const today = londonDay(now);
303
- const url = `${definition}?from=${today}&to=${addDays(today, 1)}${event ? `&event=${encodeURIComponent(event)}` : ''}${resource ? `&resource=${encodeURIComponent(resource)}` : ''}`;
304
- let res: Response;
305
- try {
306
- res = await fetchFn(url, { headers: { Accept: 'application/json' } });
307
- } catch (e) {
308
- throw new Error(`Book block: couldn’t reach the Ferst platform for offer "${service}" (${url}): ${e instanceof Error ? e.message : String(e)}`);
309
- }
310
- if (res.status === 404) {
311
- throw new Error(`Book block: "${service}" isn’t booked online on this site. Check it in the portal (Events and bookings: the offer, "Book online", and opening hours for who gives it), or run \`npx ferst-modules\` to list what this site takes bookings for.`);
312
- }
313
- if (res.status === 403) {
314
- throw new Error(`Book block: this site isn’t taking bookings (offer "${service}"). Check Events and bookings is switched on for the site, and that the organisation takes bookings.`);
315
- }
316
- if (!res.ok) throw new Error(`Book block: the Ferst platform answered ${res.status} for offer "${service}" (${url}).`);
317
- const d = (await res.json()) as TimesAnswer;
318
- const resources = d.resources.map((r) => ({ id: r.id, name: r.name, kind: r.kind ?? null })).filter((r) => !resource || r.id === resource);
319
- if (resource && !resources.length) {
320
- throw new Error(`Book block: "${resource}" doesn’t provide "${service}" online. Check who provides it in the portal (Events and bookings), or run \`npx ferst-modules\` to list who provides what.`);
321
- }
322
- return {
323
- id: d.service.id, name: d.service.name, description: d.service.description ?? '', minutes: d.service.minutes,
324
- // A platform from before slice 6c says no mode: it books times, at no price it says.
325
- mode: d.service.mode ?? 'times', price: d.service.price ?? 'Free', lasts: d.service.lasts ?? 'fixed', step: d.service.step_minutes ?? 30, event, resource,
326
- resources, definition, holds: `${base}/sites/${encodeURIComponent(siteId)}/book/holds`,
327
- };
328
- }
329
-
330
- /** The platform's answer for a person or a place: who they are, and each offer they provide online. */
331
- interface WithAnswer {
332
- resource: { id: string; name: string; kind?: 'place' | 'person'; description?: string };
333
- offers: Array<{ id: string; name: string; description?: string; minutes: number; lasts?: 'fixed' | 'chosen'; step_minutes?: number; mode: BookMode; price?: string; resources?: Array<{ id: string; name: string; kind?: 'place' | 'person' }> }>;
334
- }
335
-
336
- const whoCache = new Map<string, Promise<{ resource: BookWho; services: BookService[] }>>();
337
-
338
- /** A person or a place, and everything they provide online, each booked with them only (a block naming `resource` alone). */
339
- export function loadBookResource(resource: string, opts: { base: string; siteId?: string | null; fetch?: FetchFn }): Promise<{ resource: BookWho; services: BookService[] }> {
340
- const key = `${opts.base}|${opts.siteId ?? ''}|${resource}`;
341
- let hit = whoCache.get(key);
342
- if (!hit) {
343
- hit = fetchResource(resource, opts.base, opts.siteId ?? null, opts.fetch ?? fetch);
344
- whoCache.set(key, hit);
345
- hit.catch(() => whoCache.delete(key));
346
- }
347
- return hit;
348
- }
349
-
350
- async function fetchResource(resource: string, base: string, siteId: string | null, fetchFn: FetchFn): Promise<{ resource: BookWho; services: BookService[] }> {
351
- if (!siteId) throw noSiteId();
352
- const site = `${base}/sites/${encodeURIComponent(siteId)}/book`;
353
- const url = `${site}/with/${encodeURIComponent(resource)}`;
354
- let res: Response;
355
- try {
356
- res = await fetchFn(url, { headers: { Accept: 'application/json' } });
357
- } catch (e) {
358
- throw new Error(`Book block: couldn’t reach the Ferst platform for "${resource}" (${url}): ${e instanceof Error ? e.message : String(e)}`);
359
- }
360
- if (res.status === 404) {
361
- throw new Error(`Book block: "${resource}" provides nothing booked online on this site. Check it in the portal (Events and bookings: what they provide, and "Book online"), or run \`npx ferst-modules\` to list who takes bookings.`);
362
- }
363
- if (res.status === 403) {
364
- throw new Error(`Book block: this site isn’t taking bookings ("${resource}"). Check Events and bookings is switched on for the site, and that the organisation takes bookings.`);
365
- }
366
- if (!res.ok) throw new Error(`Book block: the Ferst platform answered ${res.status} for "${resource}" (${url}).`);
367
- const d = (await res.json()) as WithAnswer;
368
- const who: BookWho = { id: d.resource.id, name: d.resource.name, kind: d.resource.kind ?? null, description: d.resource.description ?? '' };
369
- return {
370
- resource: who,
371
- services: d.offers.map((o) => ({
372
- id: o.id, name: o.name, description: o.description ?? '', minutes: o.minutes, mode: o.mode, price: o.price ?? 'Free',
373
- lasts: o.lasts ?? 'fixed', step: o.step_minutes ?? 30, event: null, resource: who.id,
374
- resources: [{ id: who.id, name: who.name, kind: who.kind }],
375
- definition: `${site}/${encodeURIComponent(o.id)}`, holds: `${site}/holds`,
376
- })),
377
- };
378
- }
1
+ /**
2
+ * A "Book" block lets visitors book a time for one of the organisation's offers (the Ferst Events
3
+ * and bookings module). The block names the offer; its name, length and who gives it are the
4
+ * organisation's, read from the platform at build time, and its free times are read in the browser
5
+ * (they change by the minute). A picked time is held by the platform for the visitor while they
6
+ * give their details; the page never decides what's free.
7
+ *
8
+ * A booking is always the site's own, so the site must say who it is (`siteId` in
9
+ * ferst-site.json). An offer that isn't booked online, or a platform that can't be reached, fails
10
+ * the build: better the last good deploy stays live than a Book button that can't book.
11
+ *
12
+ * One block, shaped by the offer (0.13.0; myai4-webdev docs/EVENTS.md slice 6c): the platform says
13
+ * how it's booked (`mode`): `times`, a time of its length (a haircut); `chosen`, a start and an end
14
+ * (hall hire), its price worked out as the visitor chooses; `places`, places at one of its coming
15
+ * dates (a class, a concert). The page names the offer, and may name one event of it.
16
+ *
17
+ * Or a person or a place (0.14.0; the maintainer 2026-11-24: "we need both and its up to the person
18
+ * configuring the module to pick what is suitable"): `resource` alone books everything they provide
19
+ * online, the visitor choosing which in the block; with `service`, that offer with them only.
20
+ */
21
+ export type BookMode = 'times' | 'chosen' | 'places';
22
+ export interface BookResource { id: string; name: string; kind: 'place' | 'person' | null }
23
+ export interface BookService {
24
+ id: string;
25
+ name: string;
26
+ description: string;
27
+ minutes: number;
28
+ /** How it's booked; what it costs, as the owner put it ("£25 an hour", "Free"). */
29
+ mode: BookMode;
30
+ price: string;
31
+ /** A fixed length, or chosen when booking (from `minutes`, in steps of `step`). */
32
+ lasts: 'fixed' | 'chosen';
33
+ step: number;
34
+ /** One event of the offer the block books (a class's or concert's), or null for all its dates. */
35
+ event: string | null;
36
+ /** The person or place the block books it with (then `resources` is just them), or null for anyone who gives it. */
37
+ resource: string | null;
38
+ /** Who or what gives it (a visitor may choose, or take anyone available); a place is "at", a person "with". */
39
+ resources: BookResource[];
40
+ /** Where the browser reads free times (`?from&to`) and holds a time (`/hold`). */
41
+ definition: string;
42
+ /** Where the browser books a held time (`/:hold`) or lets it go. */
43
+ holds: string;
44
+ }
45
+
46
+ type FetchFn = (input: string, init?: RequestInit) => Promise<Response>;
47
+
48
+ /** Today's date in London ('YYYY-MM-DD'). */
49
+ export const londonDay = (d = new Date()): string => d.toLocaleDateString('en-CA', { timeZone: 'Europe/London' });
50
+ /** A date some days on ('YYYY-MM-DD'). */
51
+ export function addDays(day: string, n: number): string {
52
+ const [y, m, d] = day.split('-').map(Number);
53
+ return new Date(Date.UTC(y, m - 1, d + n)).toISOString().slice(0, 10);
54
+ }
55
+
56
+ /** 30 minutes, 1 hour, 1 hour 30 minutes. */
57
+ export function lengthText(minutes: number): string {
58
+ const h = Math.floor(minutes / 60);
59
+ const rest = minutes % 60;
60
+ return [h ? `${h} hour${h === 1 ? '' : 's'}` : '', rest ? `${rest} minutes` : ''].filter(Boolean).join(' ');
61
+ }
62
+
63
+ const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
64
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
65
+ const WEEKDAYS_LONG = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
66
+ const MONTHS_LONG = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
67
+
68
+ /** A day, short enough for a row of days: { weekday: 'Mon', date: '4 Jan' }. */
69
+ export function dayChip(day: string): { weekday: string; date: string } {
70
+ const [y, m, d] = day.split('-').map(Number);
71
+ return { weekday: WEEKDAYS[new Date(Date.UTC(y, m - 1, d)).getUTCDay()], date: `${d} ${MONTHS[m - 1]}` };
72
+ }
73
+
74
+ /** 'Monday 4 January at 10:00', from a London time ('YYYY-MM-DDTHH:MM'). */
75
+ export function whenText(local: string): string {
76
+ const [y, m, d] = local.slice(0, 10).split('-').map(Number);
77
+ return `${WEEKDAYS_LONG[new Date(Date.UTC(y, m - 1, d)).getUTCDay()]} ${d} ${MONTHS_LONG[m - 1]} at ${local.slice(11, 16)}`;
78
+ }
79
+
80
+ // ── The month (look: 'calendar'; myai4-webdev issue #239) ──────────────────────────────────────────
81
+ // Booking as people book everywhere: a month with the days that have free times marked, and that
82
+ // day's times beside it. Days are London days ('YYYY-MM-DD') and months 'YYYY-MM', worked out as
83
+ // calendar dates (UTC arithmetic), so a clock change never moves a day.
84
+
85
+ /** The month a day is in ('YYYY-MM'). */
86
+ export const monthOf = (day: string): string => day.slice(0, 7);
87
+ /** A month some months on ('YYYY-MM'). */
88
+ export function shiftMonth(month: string, n: number): string {
89
+ const [y, m] = month.split('-').map(Number);
90
+ return new Date(Date.UTC(y, m - 1 + n, 1)).toISOString().slice(0, 7);
91
+ }
92
+ /** The days of a month that can be booked, as the platform is asked for them (`from`, and `to` the
93
+ * day after): from today (or the 1st) to the month's end, or the last day bookings are taken
94
+ * (`ahead` days on). Null when none of it can be booked. Never more than 31 days, the platform's most. */
95
+ export function monthWindow(month: string, today: string, ahead: number): { from: string; to: string } | null {
96
+ const first = `${month}-01`;
97
+ const next = `${shiftMonth(month, 1)}-01`;
98
+ const last = addDays(today, ahead + 1);
99
+ const from = first > today ? first : today;
100
+ const to = next < last ? next : last;
101
+ return from < to ? { from, to } : null;
102
+ }
103
+ /** The days with a free time (with one person or place, when `who` names them). */
104
+ export function freeDays(days: TimesAnswer['days'], who = ''): string[] {
105
+ return days.filter((d) => d.times.some((t) => !who || t.resources.includes(who))).map((d) => d.day);
106
+ }
107
+ /** 'Tuesday 1 December', over a day's times. */
108
+ export function dayTitle(day: string): string {
109
+ const [y, m, d] = day.split('-').map(Number);
110
+ return `${WEEKDAYS_LONG[new Date(Date.UTC(y, m - 1, d)).getUTCDay()]} ${d} ${MONTHS_LONG[m - 1]}`;
111
+ }
112
+ /** 'December 2026'. */
113
+ export function monthTitle(month: string): string {
114
+ const [y, m] = month.split('-').map(Number);
115
+ return `${MONTHS_LONG[m - 1]} ${y}`;
116
+ }
117
+
118
+ /** What to tell the visitor when the platform says no. */
119
+ export function bookingMessage(code: string): string {
120
+ switch (code) {
121
+ case 'time_taken': return 'That time has just been taken. Please choose another.';
122
+ case 'hold_expired': return 'We kept that time for 10 minutes and it has gone. Please choose a time again.';
123
+ case 'too_many_holds': return 'You’re already holding a few times. Book one, or let one go, first.';
124
+ case 'rate_limited': return 'Too many tries in a short time. Please wait a minute and try again.';
125
+ case 'name_required': return 'Please give your name.';
126
+ case 'invalid_email': return 'Please give an email address we can send your booking to.';
127
+ case 'bookings_not_open': return 'This website isn’t taking bookings just now.';
128
+ case 'not_enough_places': return 'There aren’t that many places left. Please choose fewer, or another date.';
129
+ case 'invalid_date': return 'That date isn’t on offer any more. Please choose another.';
130
+ case 'invalid_length': case 'invalid_end': return 'Please choose when it ends again.';
131
+ case 'one_day': return 'Online, a booking starts and ends on the same day. For longer, please ask us.';
132
+ default: return 'The booking couldn’t be made just now. Please try again.';
133
+ }
134
+ }
135
+
136
+ /** One coming date of a class or a concert: its places left and its price. */
137
+ export interface EventDate {
138
+ event_id: string; title: string; description?: string; start: string; end: string; places: number; left: number; price: string;
139
+ /** For search engines (0.15.0, slice 6d): a place's price in pence (0 free; null when not priced by the place), its place and who leads it. */
140
+ amount?: number | null; where?: { name: string } | null; with?: string[];
141
+ }
142
+
143
+ // ── For search engines (0.15.0; myai4-webdev docs/EVENTS.md slice 6d) ──────────────────────────────
144
+ // Each coming date of a class or an event is a schema.org Event, written into the page at build and
145
+ // brought up to date (its places left) as the page loads. Only what's booked by places: a haircut or a
146
+ // hire becomes one date only once it's booked, so it's nothing to search for.
147
+
148
+ /** One of the site's places (siteSettings.places), whose address an event there is given. */
149
+ export interface SitePlace { name?: string; streetAddress?: string; locality?: string; postalCode?: string; country?: string }
150
+ /** What the page knows that the platform doesn't: its own address, the organisation, and its places. */
151
+ export interface EventsContext { url: string; organisation: { name?: string; url: string }; places: SitePlace[] }
152
+
153
+ /** '2026-12-19T19:30:00+00:00': a London time with its offset, as schema.org wants it. */
154
+ export function londonWithOffset(local: string): string {
155
+ const [y, m, d] = local.slice(0, 10).split('-').map(Number);
156
+ const guess = new Date(Date.UTC(y, m - 1, d, Number(local.slice(11, 13)), Number(local.slice(14, 16))));
157
+ const name = new Intl.DateTimeFormat('en-GB', { timeZone: 'Europe/London', timeZoneName: 'longOffset' })
158
+ .formatToParts(guess).find((p) => p.type === 'timeZoneName')?.value ?? 'GMT';
159
+ const off = name.replace('GMT', '') || '+00:00';
160
+ return `${local.slice(0, 16)}:00${off}`;
161
+ }
162
+
163
+ const postal = (p: SitePlace) => {
164
+ const a: Record<string, string> = { '@type': 'PostalAddress' };
165
+ if (p.streetAddress) a.streetAddress = p.streetAddress;
166
+ if (p.locality) a.addressLocality = p.locality;
167
+ if (p.postalCode) a.postalCode = p.postalCode;
168
+ a.addressCountry = p.country || 'GB';
169
+ return a;
170
+ };
171
+ const filled = (p: SitePlace) => !!(p && (p.name || p.streetAddress || p.postalCode));
172
+
173
+ /** Where a date is, with its address when it's one of the site's places (or the site has only one). */
174
+ function locationOf(where: { name: string } | null | undefined, places: SitePlace[]): Record<string, unknown> | undefined {
175
+ const known = places.filter(filled);
176
+ const same = where ? known.find((p) => p.name?.trim().toLowerCase() === where.name.trim().toLowerCase()) : undefined;
177
+ const only = known.length === 1 ? known[0] : undefined;
178
+ const at = same ?? (where ? undefined : only);
179
+ if (where && !same && only && !only.name) return { '@type': 'Place', name: where.name, address: postal(only) };
180
+ if (!where && !at) return undefined;
181
+ const place: Record<string, unknown> = { '@type': 'Place', name: where?.name ?? at?.name };
182
+ if (at && (at.streetAddress || at.postalCode || at.locality)) place.address = postal(at);
183
+ return place;
184
+ }
185
+
186
+ /** The schema.org Events for a class's or an event's coming dates, or null when there are none. */
187
+ export function eventsData(dates: EventDate[], ctx: EventsContext): { '@context': string; '@graph': Array<Record<string, unknown>> } | null {
188
+ if (!dates.length) return null;
189
+ const graph = dates.slice(0, 50).map((d) => {
190
+ const e: Record<string, unknown> = { '@type': 'Event', name: d.title };
191
+ if (d.description) e.description = d.description;
192
+ e.startDate = londonWithOffset(d.start);
193
+ e.endDate = londonWithOffset(d.end);
194
+ e.eventStatus = 'https://schema.org/EventScheduled';
195
+ e.eventAttendanceMode = 'https://schema.org/OfflineEventAttendanceMode';
196
+ const location = locationOf(d.where, ctx.places);
197
+ if (location) e.location = location;
198
+ e.organizer = { '@type': 'Organization', ...(ctx.organisation.name ? { name: ctx.organisation.name } : {}), url: ctx.organisation.url };
199
+ if (d.with?.length) e.performer = d.with.map((name) => ({ '@type': 'Person', name }));
200
+ e.maximumAttendeeCapacity = d.places;
201
+ e.remainingAttendeeCapacity = d.left;
202
+ if (typeof d.amount === 'number') {
203
+ e.offers = { '@type': 'Offer', price: (d.amount / 100).toFixed(2), priceCurrency: 'GBP', availability: `https://schema.org/${d.left > 0 ? 'InStock' : 'SoldOut'}`, url: ctx.url };
204
+ }
205
+ e.url = ctx.url;
206
+ return e;
207
+ });
208
+ return { '@context': 'https://schema.org', '@graph': graph };
209
+ }
210
+
211
+ /** The JSON for a page's script tag: `<` escaped so it can't close the tag. */
212
+ export const ldJson = (data: unknown) => JSON.stringify(data).replace(/</g, '\\u003c');
213
+
214
+ /**
215
+ * A class's or an event's dates for the coming month, read at build for search engines. Never fails the
216
+ * build: the block still works (it reads its dates as the page loads), search engines just aren't told.
217
+ */
218
+ export async function loadEventDates(definition: string, opts: { event?: string | null; resource?: string | null; now?: Date; fetch?: FetchFn } = {}): Promise<EventDate[]> {
219
+ const doFetch = opts.fetch ?? ((u: string, i?: RequestInit) => fetch(u, i));
220
+ const from = londonDay(opts.now);
221
+ const q = `from=${from}&to=${addDays(from, 30)}${opts.event ? `&event=${encodeURIComponent(opts.event)}` : ''}${opts.resource ? `&resource=${encodeURIComponent(opts.resource)}` : ''}`;
222
+ try {
223
+ const res = await doFetch(`${definition}?${q}`, { headers: { Accept: 'application/json' } });
224
+ if (!res.ok) return [];
225
+ const body = (await res.json()) as { events?: EventDate[] };
226
+ return Array.isArray(body.events) ? body.events : [];
227
+ } catch {
228
+ return [];
229
+ }
230
+ }
231
+
232
+ /** The platform's answer for an offer's free times (or, booked by places, its coming dates), as the block reads it. */
233
+ export interface TimesAnswer {
234
+ service: { id: string; name: string; description?: string; minutes: number; mode?: BookMode; lasts?: 'fixed' | 'chosen'; step_minutes?: number; price?: string };
235
+ resources: Array<{ id: string; name: string; kind?: 'place' | 'person' }>;
236
+ days: Array<{ day: string; times: Array<{ time: string; start: string; resources: string[] }> }>;
237
+ events?: EventDate[];
238
+ }
239
+
240
+ const join = (names: string[]) => (names.length <= 1 ? names.join('') : `${names.slice(0, -1).join(', ')} or ${names[names.length - 1]}`);
241
+ /** "with Sam or Alex", "at the Hall": a place is somewhere to be, a person someone to see. */
242
+ export function whereText(resources: BookResource[]): string {
243
+ const places = resources.filter((r) => r.kind === 'place').map((r) => r.name);
244
+ const people = resources.filter((r) => r.kind !== 'place').map((r) => r.name);
245
+ return [people.length ? `with ${join(people)}` : '', places.length ? `at ${join(places)}` : ''].filter(Boolean).join(', ');
246
+ }
247
+
248
+ /**
249
+ * Which of several places are free at a time, for a calendar of hire across them with "Anywhere free"
250
+ * (2026-11-24): "All free", or their names. Null when it isn't said: one place, or people.
251
+ */
252
+ export function whichFree(free: string[], places: Array<{ id: string; name: string; kind?: string | null }>): string | null {
253
+ if (places.length < 2 || !places.every((r) => r.kind === 'place')) return null;
254
+ const names = places.filter((r) => free.includes(r.id)).map((r) => r.name);
255
+ return names.length === places.length ? 'All free' : names.join(', ');
256
+ }
257
+
258
+ /** The block's line under its name: "30 minutes · with Sam or Alex · £18 a booking", "From 1 hour · at the Hall · £25 an hour". */
259
+ export function metaLine(d: Pick<BookService, 'mode' | 'minutes' | 'price' | 'resources'>): string {
260
+ const length = d.mode === 'chosen' ? `From ${lengthText(d.minutes)}` : lengthText(d.minutes);
261
+ return [length, whereText(d.resources), d.price].filter(Boolean).join(' · ');
262
+ }
263
+
264
+ const mins = (hhmm: string) => Number(hhmm.slice(0, 2)) * 60 + Number(hhmm.slice(3, 5));
265
+ const hhmm = (m: number) => `${String(Math.floor(m / 60)).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`;
266
+ /**
267
+ * The ends a hall hire starting at `start` can have: at least `minutes`, in steps of `step`, while
268
+ * the time stays free. `free` is the day's free starts for its shortest length (the platform's
269
+ * answer); a longer booking is free while every start under it is. The platform checks again on hold.
270
+ */
271
+ export function endChoices(free: string[], start: string, minutes: number, step: number): string[] {
272
+ const at = free.map(mins).sort((a, b) => a - b);
273
+ const set = new Set(at);
274
+ const s = mins(start);
275
+ if (!set.has(s)) return [];
276
+ const gaps = at.slice(1).map((m, i) => m - at[i]).filter((g) => g > 0);
277
+ const grid = gaps.length ? Math.min(...gaps) : step;
278
+ const out: string[] = [];
279
+ for (let end = s + minutes; end <= 24 * 60; end += step) {
280
+ let ok = true;
281
+ for (let t = s; t <= end - minutes; t += grid) if (!set.has(t)) { ok = false; break; }
282
+ if (!ok) break;
283
+ out.push(end === 24 * 60 ? '24:00' : hhmm(end));
284
+ }
285
+ return out;
286
+ }
287
+
288
+ /** A booking, for "Add to calendar": its title, UTC times, where, and its id. */
289
+ export interface Booked { title: string; starts_at: string; ends_at: string; location?: string | null; uid?: string }
290
+ const utcBasic = (iso: string) => new Date(iso).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
291
+ /** Add to Google Calendar. */
292
+ export function googleCalendarLink(b: Booked): string {
293
+ const q = [`action=TEMPLATE`, `text=${encodeURIComponent(b.title)}`, `dates=${encodeURIComponent(`${utcBasic(b.starts_at)}/${utcBasic(b.ends_at)}`)}`];
294
+ if (b.location) q.push(`location=${encodeURIComponent(b.location)}`);
295
+ return `https://calendar.google.com/calendar/render?${q.join('&')}`;
296
+ }
297
+ const icsText = (t: string) => t.replace(/\\/g, '\\\\').replace(/;/g, '\\;').replace(/,/g, '\\,').replace(/\r?\n/g, '\\n');
298
+ /** A calendar file for Apple Calendar, Outlook and the rest. */
299
+ export function calendarFile(b: Booked, stamp = new Date()): string {
300
+ return [
301
+ 'BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//Ferst//Book//EN', 'METHOD:PUBLISH', 'BEGIN:VEVENT',
302
+ `UID:${b.uid ?? `${utcBasic(b.starts_at)}`}@ferst.co.uk`, `DTSTAMP:${utcBasic(stamp.toISOString())}`,
303
+ `DTSTART:${utcBasic(b.starts_at)}`, `DTEND:${utcBasic(b.ends_at)}`, `SUMMARY:${icsText(b.title)}`,
304
+ ...(b.location ? [`LOCATION:${icsText(b.location)}`] : []),
305
+ 'END:VEVENT', 'END:VCALENDAR', '',
306
+ ].join('\r\n');
307
+ }
308
+
309
+ /** What a block names: an offer, a person or place, or both. Naming neither fails the build. */
310
+ export function bookTarget(props: { service?: string | null; resource?: string | null }): { service: string | null; resource: string | null } {
311
+ const service = props.service || null;
312
+ const resource = props.resource || null;
313
+ if (!service && !resource) {
314
+ throw new Error('Book block: name an offer ("service": "<id>"), a person or place ("resource": "<id>"), or both. Run `npx ferst-modules` to list what this site takes bookings for.');
315
+ }
316
+ return { service, resource };
317
+ }
318
+
319
+ /** A person or a place, as a block naming them shows them. */
320
+ export interface BookWho extends BookResource { description: string }
321
+
322
+ const cache = new Map<string, Promise<BookService>>();
323
+
324
+ export function loadBookService(service: string, opts: { base: string; siteId?: string | null; fetch?: FetchFn; now?: Date; event?: string | null; resource?: string | null }): Promise<BookService> {
325
+ const key = `${opts.base}|${opts.siteId ?? ''}|${service}|${opts.event ?? ''}|${opts.resource ?? ''}`;
326
+ let hit = cache.get(key);
327
+ if (!hit) {
328
+ hit = fetchService(service, opts.base, opts.siteId ?? null, opts.fetch ?? fetch, opts.now ?? new Date(), opts.event ?? null, opts.resource ?? null);
329
+ cache.set(key, hit);
330
+ hit.catch(() => cache.delete(key)); // a failure is retried by the next caller
331
+ }
332
+ return hit;
333
+ }
334
+
335
+ const noSiteId = () => new Error(`Book block: this site doesn't say who it is, so it can't take bookings. Add "siteId" to ferst-site.json (or set FERST_SITE_ID).`);
336
+
337
+ async function fetchService(service: string, base: string, siteId: string | null, fetchFn: FetchFn, now: Date, event: string | null, resource: string | null): Promise<BookService> {
338
+ if (!siteId) throw noSiteId();
339
+ const definition = `${base}/sites/${encodeURIComponent(siteId)}/book/${encodeURIComponent(service)}`;
340
+ const today = londonDay(now);
341
+ const url = `${definition}?from=${today}&to=${addDays(today, 1)}${event ? `&event=${encodeURIComponent(event)}` : ''}${resource ? `&resource=${encodeURIComponent(resource)}` : ''}`;
342
+ let res: Response;
343
+ try {
344
+ res = await fetchFn(url, { headers: { Accept: 'application/json' } });
345
+ } catch (e) {
346
+ throw new Error(`Book block: couldn’t reach the Ferst platform for offer "${service}" (${url}): ${e instanceof Error ? e.message : String(e)}`);
347
+ }
348
+ if (res.status === 404) {
349
+ throw new Error(`Book block: "${service}" isn’t booked online on this site. Check it in the portal (Events and bookings: the offer, "Book online", and opening hours for who gives it), or run \`npx ferst-modules\` to list what this site takes bookings for.`);
350
+ }
351
+ if (res.status === 403) {
352
+ throw new Error(`Book block: this site isn’t taking bookings (offer "${service}"). Check Events and bookings is switched on for the site, and that the organisation takes bookings.`);
353
+ }
354
+ if (!res.ok) throw new Error(`Book block: the Ferst platform answered ${res.status} for offer "${service}" (${url}).`);
355
+ const d = (await res.json()) as TimesAnswer;
356
+ const resources = d.resources.map((r) => ({ id: r.id, name: r.name, kind: r.kind ?? null })).filter((r) => !resource || r.id === resource);
357
+ if (resource && !resources.length) {
358
+ throw new Error(`Book block: "${resource}" doesn’t provide "${service}" online. Check who provides it in the portal (Events and bookings), or run \`npx ferst-modules\` to list who provides what.`);
359
+ }
360
+ return {
361
+ id: d.service.id, name: d.service.name, description: d.service.description ?? '', minutes: d.service.minutes,
362
+ // A platform from before slice 6c says no mode: it books times, at no price it says.
363
+ mode: d.service.mode ?? 'times', price: d.service.price ?? 'Free', lasts: d.service.lasts ?? 'fixed', step: d.service.step_minutes ?? 30, event, resource,
364
+ resources, definition, holds: `${base}/sites/${encodeURIComponent(siteId)}/book/holds`,
365
+ };
366
+ }
367
+
368
+ /** The platform's answer for a person or a place: who they are, and each offer they provide online. */
369
+ interface WithAnswer {
370
+ resource: { id: string; name: string; kind?: 'place' | 'person'; description?: string };
371
+ offers: Array<{ id: string; name: string; description?: string; minutes: number; lasts?: 'fixed' | 'chosen'; step_minutes?: number; mode: BookMode; price?: string; resources?: Array<{ id: string; name: string; kind?: 'place' | 'person' }> }>;
372
+ }
373
+
374
+ const whoCache = new Map<string, Promise<{ resource: BookWho; services: BookService[] }>>();
375
+
376
+ /** A person or a place, and everything they provide online, each booked with them only (a block naming `resource` alone). */
377
+ export function loadBookResource(resource: string, opts: { base: string; siteId?: string | null; fetch?: FetchFn }): Promise<{ resource: BookWho; services: BookService[] }> {
378
+ const key = `${opts.base}|${opts.siteId ?? ''}|${resource}`;
379
+ let hit = whoCache.get(key);
380
+ if (!hit) {
381
+ hit = fetchResource(resource, opts.base, opts.siteId ?? null, opts.fetch ?? fetch);
382
+ whoCache.set(key, hit);
383
+ hit.catch(() => whoCache.delete(key));
384
+ }
385
+ return hit;
386
+ }
387
+
388
+ async function fetchResource(resource: string, base: string, siteId: string | null, fetchFn: FetchFn): Promise<{ resource: BookWho; services: BookService[] }> {
389
+ if (!siteId) throw noSiteId();
390
+ const site = `${base}/sites/${encodeURIComponent(siteId)}/book`;
391
+ const url = `${site}/with/${encodeURIComponent(resource)}`;
392
+ let res: Response;
393
+ try {
394
+ res = await fetchFn(url, { headers: { Accept: 'application/json' } });
395
+ } catch (e) {
396
+ throw new Error(`Book block: couldn’t reach the Ferst platform for "${resource}" (${url}): ${e instanceof Error ? e.message : String(e)}`);
397
+ }
398
+ if (res.status === 404) {
399
+ throw new Error(`Book block: "${resource}" provides nothing booked online on this site. Check it in the portal (Events and bookings: what they provide, and "Book online"), or run \`npx ferst-modules\` to list who takes bookings.`);
400
+ }
401
+ if (res.status === 403) {
402
+ throw new Error(`Book block: this site isn’t taking bookings ("${resource}"). Check Events and bookings is switched on for the site, and that the organisation takes bookings.`);
403
+ }
404
+ if (!res.ok) throw new Error(`Book block: the Ferst platform answered ${res.status} for "${resource}" (${url}).`);
405
+ const d = (await res.json()) as WithAnswer;
406
+ const who: BookWho = { id: d.resource.id, name: d.resource.name, kind: d.resource.kind ?? null, description: d.resource.description ?? '' };
407
+ return {
408
+ resource: who,
409
+ services: d.offers.map((o) => ({
410
+ id: o.id, name: o.name, description: o.description ?? '', minutes: o.minutes, mode: o.mode, price: o.price ?? 'Free',
411
+ lasts: o.lasts ?? 'fixed', step: o.step_minutes ?? 30, event: null, resource: who.id,
412
+ resources: [{ id: who.id, name: who.name, kind: who.kind }],
413
+ definition: `${site}/${encodeURIComponent(o.id)}`, holds: `${site}/holds`,
414
+ })),
415
+ };
416
+ }