@profitstudio/booking-engine 0.0.0-stage → 2.0.0-beta.2

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 (114) hide show
  1. package/CHANGELOG.md +578 -0
  2. package/LICENSE +21 -0
  3. package/README.md +18 -2
  4. package/THIRD_PARTY_NOTICES.md +41 -0
  5. package/bin/booking-engine.mjs +575 -0
  6. package/bin/connect.mjs +408 -0
  7. package/bin/photos.mjs +82 -0
  8. package/dist/admin/BookingAdmin.d.ts +29 -0
  9. package/dist/admin/BookingAdmin.js +338 -0
  10. package/dist/admin/admin.css +1423 -0
  11. package/dist/admin/alerts.d.ts +10 -0
  12. package/dist/admin/alerts.js +11 -0
  13. package/dist/admin/booking-detail.d.ts +47 -0
  14. package/dist/admin/booking-detail.js +159 -0
  15. package/dist/admin/content-inputs.d.ts +15 -0
  16. package/dist/admin/content-inputs.js +105 -0
  17. package/dist/admin/context.d.ts +41 -0
  18. package/dist/admin/context.js +8 -0
  19. package/dist/admin/drawer.d.ts +14 -0
  20. package/dist/admin/drawer.js +56 -0
  21. package/dist/admin/feedback.d.ts +32 -0
  22. package/dist/admin/feedback.js +70 -0
  23. package/dist/admin/fields.d.ts +27 -0
  24. package/dist/admin/fields.js +146 -0
  25. package/dist/admin/fonts/OFL-Geist-Mono.txt +93 -0
  26. package/dist/admin/fonts/OFL-Geist.txt +93 -0
  27. package/dist/admin/fonts/geist-latin-wght-normal.woff2 +0 -0
  28. package/dist/admin/fonts/geist-mono-latin-wght-normal.woff2 +0 -0
  29. package/dist/admin/icons.d.ts +66 -0
  30. package/dist/admin/icons.js +72 -0
  31. package/dist/admin/image-upload.d.ts +58 -0
  32. package/dist/admin/image-upload.js +111 -0
  33. package/dist/admin/index.d.ts +7 -0
  34. package/dist/admin/index.js +6 -0
  35. package/dist/admin/lucide.generated.d.ts +521 -0
  36. package/dist/admin/lucide.generated.js +76 -0
  37. package/dist/admin/sections/BookingsSection.d.ts +1 -0
  38. package/dist/admin/sections/BookingsSection.js +137 -0
  39. package/dist/admin/sections/EmailSection.d.ts +8 -0
  40. package/dist/admin/sections/EmailSection.js +184 -0
  41. package/dist/admin/sections/HoursSection.d.ts +1 -0
  42. package/dist/admin/sections/HoursSection.js +110 -0
  43. package/dist/admin/sections/OverviewSection.d.ts +1 -0
  44. package/dist/admin/sections/OverviewSection.js +427 -0
  45. package/dist/admin/sections/ServicesSection.d.ts +1 -0
  46. package/dist/admin/sections/ServicesSection.js +236 -0
  47. package/dist/admin/sections/SettingsSection.d.ts +10 -0
  48. package/dist/admin/sections/SettingsSection.js +96 -0
  49. package/dist/admin/sections/WebsiteSection.d.ts +1 -0
  50. package/dist/admin/sections/WebsiteSection.js +228 -0
  51. package/dist/admin/sections.d.ts +22 -0
  52. package/dist/admin/sections.js +29 -0
  53. package/dist/admin/setup.d.ts +1 -0
  54. package/dist/admin/setup.js +45 -0
  55. package/dist/admin/today.d.ts +43 -0
  56. package/dist/admin/today.js +115 -0
  57. package/dist/admin/ui.d.ts +134 -0
  58. package/dist/admin/ui.js +220 -0
  59. package/dist/calendar.d.ts +64 -0
  60. package/dist/calendar.js +139 -0
  61. package/dist/client.d.ts +147 -0
  62. package/dist/client.js +507 -0
  63. package/dist/config.d.ts +25 -0
  64. package/dist/config.js +120 -0
  65. package/dist/content/image.d.ts +20 -0
  66. package/dist/content/image.js +90 -0
  67. package/dist/content/resolve.d.ts +12 -0
  68. package/dist/content/resolve.js +73 -0
  69. package/dist/content/schema.d.ts +119 -0
  70. package/dist/content/schema.js +53 -0
  71. package/dist/content/store.d.ts +48 -0
  72. package/dist/content/store.js +123 -0
  73. package/dist/content/validate.d.ts +33 -0
  74. package/dist/content/validate.js +177 -0
  75. package/dist/errors.d.ts +19 -0
  76. package/dist/errors.js +94 -0
  77. package/dist/generated/manifest.d.ts +6 -0
  78. package/dist/generated/manifest.js +7 -0
  79. package/dist/index.d.ts +20 -0
  80. package/dist/index.js +20 -0
  81. package/dist/presets/hair-salon.d.ts +8 -0
  82. package/dist/presets/hair-salon.js +94 -0
  83. package/dist/presets/index.d.ts +5 -0
  84. package/dist/presets/index.js +6 -0
  85. package/dist/preview.d.ts +18 -0
  86. package/dist/preview.js +134 -0
  87. package/dist/semver.d.ts +16 -0
  88. package/dist/semver.js +55 -0
  89. package/dist/time.d.ts +31 -0
  90. package/dist/time.js +138 -0
  91. package/dist/types.d.ts +477 -0
  92. package/dist/types.js +3 -0
  93. package/dist/vite.d.ts +52 -0
  94. package/dist/vite.js +150 -0
  95. package/docs/BUILD-A-SITE.md +203 -0
  96. package/docs/EMAIL-SETUP.md +224 -0
  97. package/docs/INTEGRATION.md +1112 -0
  98. package/engine.manifest.json +90 -0
  99. package/functions/booking-mailer/deno.json +6 -0
  100. package/functions/booking-mailer/index.ts +44 -0
  101. package/functions/booking-mailer/mailer.js +156 -0
  102. package/functions/booking-mailer/providers/index.js +42 -0
  103. package/functions/booking-mailer/providers/resend.js +75 -0
  104. package/functions/booking-mailer/templates.js +345 -0
  105. package/migrations/0001_core.sql +1673 -0
  106. package/migrations/0002_security_hardening.sql +711 -0
  107. package/migrations/0003_private_definers_and_holds.sql +808 -0
  108. package/migrations/0004_verified_requests.sql +1702 -0
  109. package/migrations/0005_scoped_mailer_credential.sql +347 -0
  110. package/migrations/0006_trusted_client_ip.sql +56 -0
  111. package/migrations/0007_site_content.sql +380 -0
  112. package/migrations/0008_service_images_opening_times.sql +328 -0
  113. package/package.json +85 -4
  114. package/templates/BOOKING_ENGINE.md +61 -0
@@ -0,0 +1,1112 @@
1
+ # Booking Engine — Integration Contract
2
+
3
+ `@profitstudio/booking-engine` · engine 2.0.0-beta.2 · database schema 2.0.0-alpha.10
4
+ (booking works from schema alpha.5; website content (§15) needs alpha.7;
5
+ service photos and opening times need alpha.10)
6
+
7
+ This document is the contract between the engine and the website built around
8
+ it. It is written for developers **and for AI coding assistants**. Where a
9
+ prompt and this document disagree on a technical point, this document wins.
10
+
11
+ ---
12
+
13
+ ## 1. Who owns what
14
+
15
+ | The engine owns (do not rebuild, do not edit) | The website owns (design it freely) |
16
+ |---|---|
17
+ | Database tables, security rules, migrations | Every public page, layout, typography, colour, imagery |
18
+ | Availability calculation, time zones, conflict prevention | The booking experience (steps, calendar UI, animations) |
19
+ | Booking requests, email verification, validation, abuse limits | Copy, tone, sections, SEO text |
20
+ | Booking emails (codes, confirmations, owner alerts) and the `booking-mailer` Edge Function | How the code step looks and reads |
21
+ | The admin dashboard (`@profitstudio/booking-engine/admin`) | Navigation, footer, contact and about content |
22
+ | Version checks and upgrades (`booking-engine` CLI) | Styling overrides for the admin via CSS variables (optional) |
23
+ | Storing, validating, publishing and serving the owner's website content and images | Which texts, images and colours the owner may edit (the content schema, §15) and how they look |
24
+
25
+ ## 2. Golden rules
26
+
27
+ 1. All booking data goes through `createBookingEngine()`. Never import
28
+ `@supabase/supabase-js` for booking data, never call `booking_*` RPCs
29
+ yourself, never write SQL for booking tables.
30
+ 2. Never edit `supabase/migrations/*_booking_engine_*.sql`,
31
+ `booking-engine.lock.json` or anything in `node_modules`.
32
+ 3. Only the Supabase **publishable** key (`sb_publishable_…`) may appear in the
33
+ website. Never a secret / `service_role` key, never in a `VITE_` variable.
34
+ The engine throws if given one.
35
+ 4. Booking takes two steps: `requestBooking()` holds the time and emails the
36
+ customer a 6-digit code; `verifyBooking()` with that code makes it a real
37
+ request (or booking). A booking is real only when `verifyBooking()` returns
38
+ `{ ok: true }`. Never show a success screen otherwise, and never skip the code
39
+ step. In preview no email is sent (`delivery: 'preview'`, any 6 digits) and
40
+ `verifyBooking()` returns `PREVIEW_MODE` — show that honestly. Test the real
41
+ flow against a connected backend (§11).
42
+ 5. The server decides availability. Show the slots `getAvailability()` returns;
43
+ never compute or invent times in the browser.
44
+ 6. Show every booking date and time in the **business** time zone
45
+ (`business.timezone`), never the visitor's device zone.
46
+ 7. Every engine call returns a `Result`; handle `ok: false` everywhere.
47
+ 8. Do not rebuild the admin dashboard. Mount the packaged one on its own page.
48
+ 9. The engine sends every booking email. Never send email from the website,
49
+ never add an email service to it, and never put an email provider key
50
+ (Resend `re_…`) in the website, a `VITE_` variable or its `.env` files.
51
+ 10. Whatever the owner should be able to change (headlines, about text, photos,
52
+ logo, brand colours, FAQ…) is declared in a content schema and rendered from
53
+ it (§15) — as text, never as HTML. Services, prices, hours and contact
54
+ details are not content: they come from the engine.
55
+
56
+ ## 3. Install
57
+
58
+ ```bash
59
+ npm install --save-exact @profitstudio/booking-engine@2.0.0-beta.2 # exact version from the guide
60
+ npx booking-engine init # a hair salon may add: --preset hair-salon
61
+ ```
62
+
63
+ `init` adds the engine's SQL migrations to `supabase/migrations/`, the
64
+ `booking-mailer` Edge Function to `supabase/functions/booking-mailer/` (engine
65
+ files — never edit them), and writes `booking-engine.lock.json`,
66
+ `.env.example`, `.gitignore` entries and `BOOKING_ENGINE.md`. It is safe to run
67
+ again. Any kind of appointment business works: the preset only supplies sample
68
+ data (§5).
69
+
70
+ The public API is what the three entry points export: `@profitstudio/booking-engine`,
71
+ `@profitstudio/booking-engine/admin` (plus `admin.css`) and
72
+ `@profitstudio/booking-engine/vite` — declared in `dist/index.d.ts`,
73
+ `dist/admin/index.d.ts` and `dist/vite.d.ts`. Other `.d.ts` files in the package
74
+ describe internals; they cannot be imported and may change in any release.
75
+
76
+ Installing from a tarball the guide provides (before the public release, or
77
+ offline): keep the file in the project, e.g. `vendor/`, install it by path
78
+ (`npm install --save-exact ./vendor/<file>.tgz`) and commit it with
79
+ `package-lock.json` — a build server such as Hostinger's installs from it.
80
+
81
+ ## 4. Project layout (Vite + React + TypeScript)
82
+
83
+ ```
84
+ index.html public website entry
85
+ admin/index.html admin dashboard entry (a real file → works on any static host)
86
+ src/lib/engine.ts the ONE engine instance
87
+ src/main.tsx public site
88
+ src/admin-main.tsx mounts <BookingAdmin>
89
+ src/content/site.ts what the owner may edit (optional, §15)
90
+ vite.config.ts multi-page build (both HTML files)
91
+ ```
92
+
93
+ Keep the public site on one HTML page (sections + an in-page booking flow, or
94
+ hash links). Do not rely on server-side rewrites for client-side routes: static
95
+ hosts differ in how they handle deep links. `admin/index.html` is a real file,
96
+ so `/admin/` always works.
97
+
98
+ `vite.config.ts`:
99
+
100
+ ```ts
101
+ import { defineConfig } from 'vite';
102
+ import react from '@vitejs/plugin-react';
103
+ import { fileURLToPath } from 'node:url';
104
+
105
+ export default defineConfig({
106
+ plugins: [react()],
107
+ build: {
108
+ rolldownOptions: { // Vite 8; on Vite 7 the same object is `rollupOptions`
109
+ input: {
110
+ main: fileURLToPath(new URL('./index.html', import.meta.url)),
111
+ admin: fileURLToPath(new URL('./admin/index.html', import.meta.url)),
112
+ },
113
+ },
114
+ },
115
+ });
116
+ ```
117
+
118
+ ## 5. The engine instance
119
+
120
+ `src/lib/engine.ts`:
121
+
122
+ ```ts
123
+ import { createBookingEngine, hairSalonPreset } from '@profitstudio/booking-engine';
124
+
125
+ export const engine = createBookingEngine({
126
+ supabaseUrl: import.meta.env.VITE_SUPABASE_URL,
127
+ supabaseKey: import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,
128
+ // Preview: fictional data while no backend is connected. Development only.
129
+ allowPreview: import.meta.env.DEV,
130
+ preview: {
131
+ preset: hairSalonPreset,
132
+ business: { name: 'Your Salon Name', timezone: 'America/Los_Angeles' },
133
+ },
134
+ });
135
+ ```
136
+
137
+ In preview the business is the preset's sample: name “Sample Hair Studio”,
138
+ the preset's currency and locale, contact `hello@example.com`, `+1 555 0100`,
139
+ “123 Example Street, Springfield”, and **the developer's computer time zone
140
+ unless you set `business.timezone`** — always set it to the business's zone.
141
+ You may override `name`, `timezone`, `currency`, `locale` and `contact`
142
+ (`{ email, phone, address }`). Once connected, all of these come from the
143
+ owner's dashboard instead.
144
+
145
+ ### Presets: sample data for your kind of business
146
+
147
+ A preset is plain data (type `Preset`): the sample services, opening hours and
148
+ booking policies preview mode shows, the fictional preview business, and the
149
+ words for customers and bookings. The engine ships `hairSalonPreset`. For any
150
+ other appointment business — a nail studio, a physiotherapist, a tattoo
151
+ studio — write one in the site; the engine treats every preset the same way:
152
+
153
+ ```ts
154
+ // src/lib/preset.ts
155
+ import type { Preset } from '@profitstudio/booking-engine';
156
+
157
+ export const nailStudioPreset = {
158
+ id: 'nail-studio',
159
+ label: 'Nail studio',
160
+ terminology: { customer: 'client', customers: 'clients', booking: 'appointment', bookings: 'appointments' },
161
+ previewBusiness: {
162
+ name: 'Sample Nail Studio',
163
+ currency: 'USD',
164
+ locale: 'en-US',
165
+ contact: { email: 'hello@example.com', phone: '+1 555 0100', address: '123 Example Street, Springfield' },
166
+ },
167
+ policies: {
168
+ slotIntervalMinutes: 15, minNoticeMinutes: 120, maxAdvanceDays: 60, autoConfirm: false,
169
+ requirePhone: true, pendingHoldMinutes: 1440, verificationWindowMinutes: 15,
170
+ },
171
+ workingHours: [ // weekday: 1 = Monday … 7 = Sunday
172
+ { weekday: 2, start: '10:00', end: '19:00' },
173
+ { weekday: 6, start: '09:00', end: '16:00' },
174
+ ],
175
+ services: [
176
+ { name: 'Gel Manicure', description: 'Shape, cuticle care and gel colour.', durationMinutes: 60, bufferAfterMinutes: 10, priceCents: 4500 },
177
+ { name: 'Nail Art', durationMinutes: 30, priceCents: 1500, priceFrom: true },
178
+ ],
179
+ } satisfies Preset;
180
+ ```
181
+
182
+ Use it for `preview.preset` (above) and pass it to the dashboard
183
+ (`<BookingAdmin presets={[nailStudioPreset]} …>`, §10), so an owner without
184
+ services is offered your starter set rather than the hair salon's. Values follow
185
+ the dashboard's limits (durations 5–720 minutes, buffers 0–240, a slot interval
186
+ of 5–240 minutes; prices in cents). Every policy is required: when a brief does
187
+ not name one, use the values above (`pendingHoldMinutes: 1440` — a verified
188
+ request holds its time for a day; `verificationWindowMinutes: 15`;
189
+ `autoConfirm: false`). `npx booking-engine init` needs no `--preset` for a
190
+ site's own preset.
191
+
192
+ In preview, `preview.business` overrides the preset's `previewBusiness` field
193
+ by field (`contact` too); the time zone is only in `preview.business` (default:
194
+ the computer's). Preview always reports online booking as switched on, so the
195
+ whole flow can be designed; a connected site starts with it off until the owner
196
+ has a working email and an alerts address (§11).
197
+
198
+ `src/vite-env.d.ts`:
199
+
200
+ ```ts
201
+ /// <reference types="vite/client" />
202
+ interface ImportMetaEnv {
203
+ readonly VITE_SUPABASE_URL?: string;
204
+ readonly VITE_SUPABASE_PUBLISHABLE_KEY?: string;
205
+ }
206
+ interface ImportMeta {
207
+ readonly env: ImportMetaEnv;
208
+ }
209
+ ```
210
+
211
+ ### Modes — `engine.mode`
212
+
213
+ | Mode | When | What to show |
214
+ |---|---|---|
215
+ | `live` | URL and publishable key are set | Real data, real bookings |
216
+ | `preview` | No backend, `allowPreview` true (dev) | A visible banner: “Preview — sample data, bookings are not saved” |
217
+ | `unconfigured` | No backend in a production build | A calm “Online booking is not available yet” message instead of the booking flow |
218
+
219
+ Set both variables or neither. With only one of them the client warns in the
220
+ console, and a build stops (§12): half a connection is never intended.
221
+
222
+ ## 6. Public API
223
+
224
+ All methods are async and return `Result<T> = { ok: true, data: T } | { ok: false, error: EngineError }`.
225
+
226
+ ### `engine.getBusiness(): Result<Business>`
227
+
228
+ ```ts
229
+ { name, timezone /* IANA */, currency /* ISO 4217 */, locale /* BCP 47 */,
230
+ contact: { email, phone, address }, // each string | null
231
+ policies: { slotIntervalMinutes, minNoticeMinutes, maxAdvanceDays, autoConfirm, requirePhone,
232
+ pendingHoldMinutes, onlineBookingEnabled, verificationWindowMinutes },
233
+ openingHours: [{ weekday /* 1=Mon…7=Sun */, start: 'HH:MM', end: 'HH:MM' }] }
234
+ ```
235
+
236
+ Use it for the business name, contact block, opening-hours section and to know
237
+ whether a phone number is required. When `policies.onlineBookingEnabled` is
238
+ `false` (the owner has not switched online booking on yet, or has paused it),
239
+ show the contact details and a calm “Book by phone or email for now” instead
240
+ of the booking flow.
241
+
242
+ ### `engine.listServices(): Result<Service[]>`
243
+
244
+ ```ts
245
+ { id, name, description /* string | null */, durationMinutes,
246
+ priceCents /* number | null = price on request */, priceFrom /* "from …" */, currency,
247
+ image /* { url, path, alt, width, height } | null — the owner's optional photo */ }
248
+ ```
249
+
250
+ Active services only, in the owner's display order. Never hard-code services:
251
+ the owner edits them in the dashboard.
252
+
253
+ **Service photos are optional and the design is yours.** The owner adds,
254
+ replaces and removes a photo per service in the dashboard (Services); `image`
255
+ is `null` until they do (and always on a database older than schema
256
+ 2.0.0-alpha.10). The engine imposes no card or layout:
257
+
258
+ - Show photos in your site's own visual language — or not at all. Never
259
+ require one: a service without a photo must look complete (no empty frame,
260
+ no placeholder picture, no stock photo), and a menu where only some services
261
+ have photos must still read well.
262
+ - Render `image.url` in a fixed-ratio frame with `object-fit: cover` (owners
263
+ upload photos of any shape); use `width`/`height` for the box when known,
264
+ lazy-load below the fold.
265
+ - `image.alt` is the owner's description; when it is `""` the photo only
266
+ illustrates the service named next to it — use `alt=""`. Render names and
267
+ descriptions as text, never as HTML.
268
+ - A replaced photo gets a new URL (files are never overwritten), so long
269
+ caching is safe.
270
+
271
+ ### `engine.getAvailability({ serviceId, from, to? }): Result<Availability>`
272
+
273
+ `from`/`to` are business-local dates `"YYYY-MM-DD"` (inclusive, at most 42 days).
274
+
275
+ ```ts
276
+ { serviceId, timezone, from, to,
277
+ days: [{ date: 'YYYY-MM-DD',
278
+ status: 'available' | 'full' | 'closed' | 'unavailable',
279
+ slots: [{ startsAt /* ISO UTC instant */, endsAt, time /* 'HH:MM' business-local */ }] }] }
280
+ ```
281
+
282
+ - `available` — has bookable times · `full` — open but nothing left ·
283
+ `closed` — not open that day · `unavailable` — past or beyond the booking window.
284
+ - Treat `startsAt` as an opaque id: send it back unchanged to `requestBooking`.
285
+ - On a daylight-saving change two slots can share the same `time` label; keep
286
+ them distinct by `startsAt`.
287
+
288
+ ### `engine.getOpeningTimes({ from, to? }): Result<OpeningTimes>`
289
+
290
+ When the business is actually open on each date: the weekly hours minus
291
+ closures, whole-day and partial-day (`from`/`to` business-local, inclusive, at
292
+ most 42 days; `to` defaults to `from`).
293
+
294
+ ```ts
295
+ { timezone, from, to,
296
+ days: [{ date: 'YYYY-MM-DD', hours: [{ start: 'HH:MM', end: 'HH:MM' /* may be '24:00' */ }] /* [] = closed */ }] }
297
+ ```
298
+
299
+ Use it for “Open now until 6 PM”, “Opens today at 6:30 PM” or “Closed today ·
300
+ opens Tuesday at 9 AM”: compare the ranges of `todayInTimeZone(timezone)` with
301
+ `localTimeLabel(Date.now(), timezone)` (the business-local time now, `'HH:MM'`)
302
+ and format times for people with `formatClockTime`. It is display information only: bookable times come
303
+ from `getAvailability`, never from opening hours. Closure reasons are private
304
+ and never returned. On a database older than schema 2.0.0-alpha.10 it answers
305
+ `SCHEMA_INCOMPATIBLE` — fall back to `getBusiness().openingHours` (the weekly
306
+ pattern). Preview mode answers with the weekly hours.
307
+
308
+ ### `engine.requestBooking(request): Result<PendingVerification>` — step 1
309
+
310
+ ```ts
311
+ const r = await engine.requestBooking({
312
+ serviceId,
313
+ startsAt: slot.startsAt,
314
+ customer: { name, email, phone }, // phone required when business.policies.requirePhone
315
+ notes, // optional, ≤ 1000 chars
316
+ });
317
+ // ok → { requestId, expiresAt /* ISO UTC */, email /* masked: "a***@example.com" */,
318
+ // codeLength: 6, resendAfterSeconds: 60, resendsLeft: 3, delivery: 'email' | 'preview' }
319
+ ```
320
+
321
+ - The time is **held** for this customer until `expiresAt` while a 6-digit
322
+ code is emailed to them. Nobody else — this visitor included — can take the
323
+ time meanwhile, and it disappears from `getAvailability`. `expiresAt` is the
324
+ owner's verification window (5–30 minutes, default 15) **or the appointment
325
+ start if that is sooner**: word the code step from `expiresAt` (“works until
326
+ 4:08 PM”), not from the window.
327
+ - Keep `requestId` in component state only (not in `localStorage`, not in the
328
+ URL). If the page is reloaded the customer simply requests again — a new
329
+ request from the same address replaces the previous one.
330
+ - `codeLength` is always 6 in 2.x.
331
+ - Errors: `INVALID_INPUT` (`field`), `SLOT_UNAVAILABLE`, `SERVICE_UNAVAILABLE`,
332
+ `RATE_LIMITED`, `BOOKING_DISABLED`, `NETWORK` (and the setup codes of §7).
333
+ - Preview (`delivery: 'preview'`): no email is sent and nothing is stored
334
+ outside the page; tell the developer to type any 6 digits. `requestBooking`
335
+ itself never returns `PREVIEW_MODE`.
336
+
337
+ ### `engine.verifyBooking({ requestId, code }): Result<BookingConfirmation>` — step 2
338
+
339
+ ```ts
340
+ const v = await engine.verifyBooking({ requestId, code }); // spaces and dashes in `code` are ignored
341
+ // ok → { reference, status: 'pending' | 'confirmed', startsAt, endsAt, date, time,
342
+ // serviceName, timezone, holdExpiresAt }
343
+ ```
344
+
345
+ - The code proves the customer owns the email address; the time is checked
346
+ again, then the request reaches the owner.
347
+ - `status: 'pending'` — a **request** the owner confirms or declines (the
348
+ customer is emailed either way). The time stays reserved until
349
+ `holdExpiresAt`. Say so honestly, e.g. “Request received — we'll confirm by
350
+ email.” (The wording is yours.)
351
+ - `status: 'confirmed'` — the owner turned on instant confirmation: it is
352
+ booked (“You're booked — a confirmation is on its way.”).
353
+ - Calling it again with the same code returns the same result (safe on retry
354
+ or double click). Show `reference` on the confirmation.
355
+ - Errors: `INVALID_INPUT` (`field`: `code` — not 6 digits, not counted as an
356
+ attempt; or `requestId`), `INVALID_CODE` (`attemptsLeft`), `CODE_EXPIRED`,
357
+ `TOO_MANY_ATTEMPTS`, `SLOT_UNAVAILABLE` (the owner closed the time
358
+ meanwhile), `TOO_MANY_BOOKINGS`, `NETWORK`. After `CODE_EXPIRED`,
359
+ `TOO_MANY_ATTEMPTS`, `SLOT_UNAVAILABLE` and `TOO_MANY_BOOKINGS` the request
360
+ is closed and its time released: entering the code again returns
361
+ `CODE_EXPIRED`.
362
+ - Preview: always `PREVIEW_MODE` (or `CODE_EXPIRED` once the window has passed).
363
+
364
+ ### `engine.resendVerificationCode(requestId): Result<CodeResent>`
365
+
366
+ Emails a new code (the previous one stops working, and the new code gets 5
367
+ fresh attempts). Allowed after `resendAfterSeconds` (60 s), at most 3 times;
368
+ it never extends `expiresAt`. `ok → { expiresAt, resendsLeft,
369
+ resendAfterSeconds, delivery }`.
370
+
371
+ Errors: `RESEND_TOO_SOON` (`retryAfterSeconds`), `RESEND_LIMIT` (no more new
372
+ codes — **the current code still works until `expiresAt`**: keep the code
373
+ step), `CODE_EXPIRED`, `RATE_LIMITED` (the current code still works),
374
+ `CONFLICT` with `field: 'already_verified'` (the code was already accepted —
375
+ call `verifyBooking` with it again to show the confirmation),
376
+ `INVALID_INPUT` (`requestId`), `NETWORK`. Preview: works like live (60 s apart,
377
+ at most 3) but sends nothing.
378
+
379
+ ### `engine.cancelBookingRequest(requestId): Result<{ released: boolean }>`
380
+
381
+ Releases a request that is still waiting for its code: the time is offered
382
+ again at once. Call it when the visitor chooses another time or goes back to
383
+ correct their email address, then reload availability. `released: false`
384
+ means the hold had already ended (expired or replaced) — fine either way; safe
385
+ to call twice. A verified request cannot be withdrawn this way
386
+ (`CONFLICT`, `already_verified`): it belongs to the owner, who confirms or
387
+ declines it.
388
+
389
+ ### `engine.createBooking()` — removed behaviour
390
+
391
+ Deprecated since 2.0.0-alpha.4: it always returns `VERIFICATION_REQUIRED`. Use
392
+ `requestBooking` + `verifyBooking`.
393
+
394
+ ### `engine.getInfo(): Result<EngineInfo>`
395
+
396
+ Package and database schema versions, `mode`, and `compatible`.
397
+
398
+ ## 7. Errors — handle every code
399
+
400
+ `EngineError = { code, message, field?, attemptsLeft?, retryAfterSeconds? }`.
401
+ `message` is safe English text; you may show it or map `code` to your own wording.
402
+
403
+ | Code | Meaning | What the UI should do |
404
+ |---|---|---|
405
+ | `INVALID_INPUT` | A field is wrong (`field`: `customer.name`, `customer.email`, `customer.phone`, `notes`, …) | Mark that field, keep the form filled |
406
+ | `SLOT_UNAVAILABLE` | The time was just taken or is no longer offered | Say so, reload availability, let them pick again |
407
+ | `SERVICE_UNAVAILABLE` | Service no longer bookable | Reload services |
408
+ | `RATE_LIMITED` | A spam or email limit was reached (it never says which) | Suggest calling/emailing the business |
409
+ | `BOOKING_DISABLED` | The owner has not switched online booking on | Show contact details instead of the flow |
410
+ | `INVALID_CODE` | Wrong code (`attemptsLeft` tries remain) | Keep the code step, show how many tries are left |
411
+ | `CODE_EXPIRED` | The code ran out (or a newer request replaced it); the time was released | Back to choosing a time; reload availability |
412
+ | `TOO_MANY_ATTEMPTS` | Five wrong codes; the time was released | Back to choosing a time; reload availability |
413
+ | `TOO_MANY_BOOKINGS` | This (verified) address already has the maximum number of upcoming bookings; the request was closed and its time released | End the code step; suggest contacting the business |
414
+ | `RESEND_TOO_SOON` | A new code can be sent after `retryAfterSeconds` | Allow “Send a new code” after that — a countdown, or a calm “in a minute” where the site's tone rules out timers |
415
+ | `RESEND_LIMIT` | No more new codes for this request; the current code still works until `expiresAt` | Keep the code step; say no more codes can be sent |
416
+ | `PREVIEW_MODE` | No backend (preview) | Show “Preview: nothing was saved” — never a success screen |
417
+ | `VERIFICATION_REQUIRED` | The site still calls the removed `createBooking` | Developer error: switch to `requestBooking` + `verifyBooking` |
418
+ | `NOT_CONFIGURED` | No backend in production | “Online booking is not available yet” |
419
+ | `SCHEMA_MISSING` / `SCHEMA_INCOMPATIBLE` | Database not set up / wrong version | “Online booking is temporarily unavailable” |
420
+ | `NETWORK` | Offline / unreachable | Offer “Try again” |
421
+ | `UNKNOWN` | Anything else | Generic error + “Try again” |
422
+
423
+ `field` values and the rules behind them (checked in the browser first, then
424
+ again on the server):
425
+
426
+ | Field | Rule |
427
+ |---|---|
428
+ | `serviceId` | An active service — treat like `SERVICE_UNAVAILABLE` |
429
+ | `startsAt` | A slot the engine offers right now — treat like `SLOT_UNAVAILABLE` |
430
+ | `customer.name` | 1–120 characters, no control characters |
431
+ | `customer.email` | A valid address (domain ending of 2+ letters), ≤ 254 characters |
432
+ | `customer.phone` | Digits, spaces and `+ ( ) . / -`, at least 5 digits, ≤ 40; required when `business.policies.requirePhone` |
433
+ | `notes` | ≤ 1000 characters |
434
+ | `code` | Exactly 6 digits (spaces and dashes ignored) |
435
+ | `requestId` | The id `requestBooking` returned |
436
+ | `from` / `to` (availability) | `YYYY-MM-DD`, `to ≥ from`, at most 42 days |
437
+
438
+ `RATE_LIMITED` deliberately never says which limit was hit.
439
+ `INVALID_INPUT` with `field: 'requestId'` at the code step means the request
440
+ no longer exists: go back to choosing a time. `BOOKING_DISABLED` can also
441
+ arrive in the middle of a booking (the owner paused online booking): replace
442
+ the flow with the contact details. `CONFLICT` reaches a public site only as
443
+ `already_verified` (above). Admin-only codes — `NOT_AUTHORIZED`, `NOT_FOUND`,
444
+ `INVALID_TRANSITION` — are handled by the dashboard; a public site can treat
445
+ them as `UNKNOWN`.
446
+
447
+ ## 8. The booking flow
448
+
449
+ A good flow (layout and style are yours):
450
+
451
+ 1. **Service** — from `listServices()`: name, duration, price (`formatMoney`, “from” when `priceFrom`).
452
+ 2. **Day** — call `getAvailability` for the visible range (one month: see
453
+ “Recommended: calendar and grouped times” below) and show each day's
454
+ `status`; only `available` days have times to pick.
455
+ 3. **Time** — the day's `slots`, as buttons labelled from `slot.time` (the
456
+ server's business-local `HH:MM`; `formatClockTime(slot.time, locale)` for
457
+ “1:30 PM”). Prefer it to converting `slot.startsAt` in the browser: a device
458
+ with outdated time-zone data can be an hour off around a clock change, the
459
+ server never is. Keep each label on one line (`white-space: nowrap`):
460
+ browsers may put an ordinary space before “AM”. Day and time may share one
461
+ screen.
462
+ 4. **Details** — name, email, phone (required if `policies.requirePhone`), notes.
463
+ Submit → `requestBooking`.
464
+ 5. **Code** — “We sent a 6-digit code to a***@example.com. It works until
465
+ 4:08 PM.” (from `expiresAt`, in the business time zone; some locales end a
466
+ time with a period — en-CA “p.m.” — so don't add another after it). One input:
467
+ `inputmode="numeric"`, `autocomplete="one-time-code"`. Keep only digits
468
+ and at most 6 — on input **and on paste**: a plain `maxlength="6"` cuts a
469
+ pasted “123 456” to “12345” before any handler sees it. Submit →
470
+ `verifyBooking`. Show a “Send a new code” button that becomes active after
471
+ `resendAfterSeconds` (and disappears when `resendsLeft` reaches 0), a way
472
+ back (“Choose another time”) that **awaits** `cancelBookingRequest` and only
473
+ then reloads availability (otherwise the released time may be missing from
474
+ the reload), and remind the customer to check their spam folder. If the
475
+ cancel answers `CONFLICT` / `already_verified`, the code was already
476
+ accepted (an earlier answer was lost): show the confirmation by calling
477
+ `verifyBooking` with the same code instead of going back.
478
+ 6. **Done** — on success a confirmation with service, date (`formatDate`),
479
+ time, reference and the pending/confirmed wording.
480
+
481
+ Requirements: buttons and inputs are keyboard-operable with visible focus;
482
+ inputs have labels; errors are announced (`role="alert"` or `aria-live`); move
483
+ focus to the new step's heading; disable the submit button while sending; show
484
+ “Times shown in {timezone}” when `isDifferentTimeZone(timezone)` is true.
485
+ After `CODE_EXPIRED`, `TOO_MANY_ATTEMPTS`, `SLOT_UNAVAILABLE` or
486
+ `INVALID_INPUT` (`requestId`) at the code step, return to the time step and
487
+ reload availability (keep the details the visitor typed).
488
+
489
+ ### Recommended: calendar and grouped times
490
+
491
+ The interaction the reference site uses, reusable by any site in its own
492
+ style. The helpers of §9 only reshape what `getAvailability` returned: never
493
+ compute or guess free times in the browser.
494
+
495
+ - **A month calendar, one request per visible month.**
496
+ `monthGrid(month, firstDayOfWeek(business.locale))` gives whole weeks and
497
+ `{ from, to }` (at most 42 days): call `getAvailability({ serviceId, from,
498
+ to })` once for the visible month and again when the visitor changes month.
499
+ Start at `monthOf(todayInTimeZone(timezone))`; stop at
500
+ `addDays(today, policies.maxAdvanceDays)`.
501
+ - **Every day status, visibly different.** `available` (a mark), few left
502
+ (`isFewLeft(day)`: 1–3 times — say how many, in the site's own tone: a calm
503
+ “2 left” where the brief rules out scarcity pressure), `full`, `closed` and
504
+ `unavailable` (past or beyond the window; not selectable). Mark today and
505
+ the selected day. Full and closed days may stay selectable so they can
506
+ explain themselves: “Fully booked — next available: Saturday, November 7”
507
+ from `nextAvailableDay(days, date)`, or a move to the next month when the
508
+ loaded data has none. Never show a closure's reason (it is the owner's).
509
+ - **Keyboard.** Arrow keys move by day (Up/Down by week), Page Up/Down by
510
+ month, Home/End to the start/end of the week; days that cannot be chosen
511
+ are skipped. Each day's accessible name carries its date and status.
512
+ - **Phones: a week strip.** `weekDates(date, firstDay)` gives the 7 days of a
513
+ strip; previous/next week, plus a toggle that opens the full month. Every
514
+ week of a month is inside that month's grid, so the strip needs no extra
515
+ request. At 320 px seven 44 px targets do not fit (308 px): use a
516
+ horizontally scrolling day rail there instead — and give a grid that holds
517
+ it `minmax(0, 1fr)` columns, or the rail widens the whole page.
518
+ - **Times grouped by part of the day.** `groupSlotsByPartOfDay(day.slots)`
519
+ returns Morning / Afternoon / Evening (by `slot.time`: before 12:00, before
520
+ 17:00, later) — e.g. a segmented control with counts. The chosen time can
521
+ unfold into “1:30 PM | Continue”; on phones keep the choice and Continue in
522
+ a sticky bottom bar. A “soonest” shortcut may offer
523
+ `nextAvailableDay(days)?.slots[0]` from data already loaded.
524
+ - **The summary stays visible**: service, duration, price, date, time and the
525
+ time zone (`timeZoneLabel(timezone)`), with a way to change the service.
526
+ - **States**: loading (keep the layout), a failed load with “Try again”, a
527
+ time just taken (`SLOT_UNAVAILABLE`: say so, show fresh times), a full or
528
+ closed day, and the code step's own states above.
529
+
530
+ ## 9. Helpers
531
+
532
+ ```ts
533
+ import {
534
+ todayInTimeZone, addDays, weekdayOf, // business-local calendar dates
535
+ formatDate, formatTime, formatDateTime, // Intl formatting in the business zone
536
+ formatClockTime, // "09:00" / "24:00" opening hours → "9:00 AM"
537
+ localTimeLabel, // (Date.now(), timezone) → "14:05", the business-local time now
538
+ timeZoneLabel, // "America/Los_Angeles" → "Pacific Time"
539
+ formatMoney, isDifferentTimeZone, defaultMessage,
540
+ } from '@profitstudio/booking-engine';
541
+ ```
542
+
543
+ Calendar view helpers (pure, framework-free, calendar-date strings only — no
544
+ `Date` time zone pitfalls). They reshape `getAvailability` data for the
545
+ pattern in §8; none of them invents availability.
546
+
547
+ ```ts
548
+ import {
549
+ monthGrid, // ('2026-11', 7) → { month, weeks: string[][], from, to } — the range to request (≤ 42 days)
550
+ monthOf, addMonths, // '2026-11-12' → '2026-11' · ('2026-11', 1) → '2026-12'
551
+ daysInMonth, // '2028-02' → 29
552
+ firstDayOfWeek, // business locale → ISO weekday the week starts on: 'en-US' → 7, 'fr-FR' → 1
553
+ startOfWeek, weekDates, // the week (strip) that contains a date
554
+ partOfDay, // slot.time 'HH:MM' → 'morning' (< 12:00) | 'afternoon' (< 17:00) | 'evening'
555
+ groupSlotsByPartOfDay, // slots → [{ part, slots }] × 3, always in that order
556
+ PARTS_OF_DAY, // ['morning', 'afternoon', 'evening']
557
+ isFewLeft, FEW_LEFT_MAX,// an available day with 1–3 times left
558
+ nextAvailableDay, // (days, after?) → the first day with times in loaded data, or null
559
+ } from '@profitstudio/booking-engine';
560
+ ```
561
+
562
+ ### Project hygiene
563
+
564
+ - `supabase/functions/booking-mailer/` holds engine JavaScript/TypeScript
565
+ that runs on Supabase, not in the website: exclude `supabase/functions/`
566
+ from the site's linter (e.g. `ignorePatterns` in `.oxlintrc.json`, `ignores`
567
+ in an ESLint config) and keep the site's `tsconfig` `include` on `src`.
568
+ - `BOOKING_ENGINE.md` is engine-owned and replaced by `sync`; keep your own
569
+ project rules in `CLAUDE.md`.
570
+ - `npx booking-engine doctor` warns when the code still calls the removed
571
+ `createBooking()`.
572
+
573
+ ### Known limits in 2.0
574
+
575
+ - Emails are in English (dates, times and prices follow the business locale).
576
+ One email provider is built in (Resend); the provider boundary allows others
577
+ in later engine versions.
578
+ - If the owner does not confirm a request before its hold ends, the time
579
+ becomes bookable by others again and the customer is emailed that the request
580
+ expired (the owner can still confirm it while the time is free).
581
+ - `getBusiness().openingHours` is the weekly pattern; closures (holidays,
582
+ partial days) are not in it. For when the business is really open use
583
+ `getOpeningTimes()` (§6); a fully closed date also has status `closed` in
584
+ `getAvailability()`.
585
+ - Services have no categories yet; group them in the site if you need to.
586
+ - One calendar (one chair/person) per business; staff calendars come later.
587
+
588
+ ## 10. Admin dashboard
589
+
590
+ `admin/index.html`:
591
+
592
+ ```html
593
+ <!doctype html>
594
+ <html lang="en">
595
+ <head>
596
+ <meta charset="UTF-8" />
597
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
598
+ <meta name="robots" content="noindex" />
599
+ <link rel="icon" href="/favicon.svg" /> <!-- the site's own icon; without one the browser logs a 404 -->
600
+ <title>Dashboard</title>
601
+ </head>
602
+ <body>
603
+ <div id="admin"></div>
604
+ <script type="module" src="/src/admin-main.tsx"></script>
605
+ </body>
606
+ </html>
607
+ ```
608
+
609
+ `src/admin-main.tsx`:
610
+
611
+ ```tsx
612
+ import { createRoot } from 'react-dom/client';
613
+ import { BookingAdmin } from '@profitstudio/booking-engine/admin';
614
+ import '@profitstudio/booking-engine/admin.css';
615
+ import './admin-theme.css'; // optional: your brand (below)
616
+ import { engine } from './lib/engine';
617
+ import { siteContent } from './content/site'; // optional: what the owner may edit (§15)
618
+
619
+ createRoot(document.getElementById('admin')!).render(
620
+ <BookingAdmin engine={engine} siteUrl="/" content={siteContent} />,
621
+ );
622
+ ```
623
+
624
+ Props: `engine` (the site's one instance), `siteUrl` (default `/`), `content`
625
+ (optional, §15), `presets` (optional: the starter sets offered while the
626
+ owner has no services; default the engine's own — pass the site's preset from
627
+ §5 for any other kind of business) and `emailDelivery` (optional, since
628
+ 2.0.0-beta.2: `'live'` by default; `'none'` only for a public demo or showcase
629
+ that never emails anyone — the dashboard then never says a customer gets an
630
+ email. A real site never sets it).
631
+
632
+ The dashboard handles sign-in, the admin check, a **Today** overview (the
633
+ requests waiting for an answer, with their hold countdown and Confirm /
634
+ Decline; the day and week in numbers; today's schedule; who is in now and
635
+ next; closures ahead; setup progress; email, website and online-booking
636
+ health), **Bookings** (upcoming, needs your answer, past and cancelled views, a
637
+ search over a year back and ahead, and each booking's details with the answers
638
+ valid for it), services, opening hours, closures, email (status, test email,
639
+ the online-booking switch), booking policies (including instant confirmation)
640
+ and business information. In **Services** the owner can add, replace and remove
641
+ an optional photo per service (stored in the media bucket's `services/` folder;
642
+ your site decides whether and how to show it — §6). From 1200 px it has a full sidebar, from 900 px a
643
+ narrower one, and below 900 px a top bar and a bottom tab bar (Today,
644
+ Bookings, Website, Services, More). With `content`, it adds **Website**: the
645
+ owner edits what the site declared, saves a draft, previews it on the real
646
+ site and publishes it (§15). Link to the dashboard discreetly (e.g. a footer
647
+ “Staff login” link to `/admin/`).
648
+
649
+ Its typefaces (Geist and Geist Mono, SIL Open Font Licence) ship inside the
650
+ package in `dist/admin/fonts/` and are declared by `admin.css` with relative
651
+ URLs, so your bundler copies them; nothing is loaded from a font CDN. Its icons
652
+ are Lucide (ISC licence), inlined in the package.
653
+
654
+ ### Theme: light, dark and your brand's accent
655
+
656
+ The dashboard has Light, Dark and System appearances (a switch at the foot of
657
+ its sidebar, under **More** on phones; the choice is kept per browser, System
658
+ follows the device). Its root element carries `data-mode="light"` or
659
+ `data-mode="dark"`.
660
+
661
+ It is one product shared by every business the engine serves: its surfaces,
662
+ text, type and status colours are its own, tuned and contrast-checked for both
663
+ appearances. **A site brands it with one thing: its accent** — two variables,
664
+ set for each appearance. Never fork the component.
665
+
666
+ | Variable | Used for | Contrast to keep |
667
+ |---|---|---|
668
+ | `--pbe-accent` | the business monogram, primary buttons, focus rings, selected rows, the active navigation item, “now” on the schedule, the requests panel's tint | 4.5:1 or more against the dashboard's surfaces in that mode (near-white in Light, near-black in Dark) |
669
+ | `--pbe-accent-text` | text and icons on the accent (buttons, the monogram) | 4.5:1 or more on `--pbe-accent` |
670
+
671
+ Tints, hover states and the focus ring are derived from these two.
672
+
673
+ ```css
674
+ /* src/admin-theme.css — `:root .pbe-admin` outranks the engine's defaults whatever the import order */
675
+ :root .pbe-admin[data-mode='light'] { --pbe-accent: #8a4420; --pbe-accent-text: #ffffff; } /* 7.2:1, 7.2:1 */
676
+ :root .pbe-admin[data-mode='dark'] { --pbe-accent: #de9b66; --pbe-accent-text: #1a1008; } /* 8.1:1, 8.0:1 */
677
+ ```
678
+
679
+ Derive the pair from one brand colour: keep its hue and set the lightness per
680
+ appearance — deep for Light (white text on it), light and a little softer for
681
+ Dark (near-black text on it). Without an `admin-theme.css` the dashboard uses a
682
+ neutral graphite accent. A single `--pbe-accent` for both modes still keeps
683
+ accent-coloured text readable (the dashboard adjusts its lightness where the
684
+ browser supports relative colours), but buttons use the colour as given — so
685
+ set both.
686
+
687
+ When the dashboard is the page (`<div id="admin">` straight in `<body>`), the
688
+ engine removes the browser's default page margin and gives the page the
689
+ dashboard's background and colour scheme; your own `body` rules still win.
690
+
691
+ #### Upgrading a dashboard theme from 2.0.0-alpha.8
692
+
693
+ Until alpha.8 a site could repaint every surface of the dashboard (`--pbe-bg`,
694
+ `--pbe-surface`, `--pbe-surface-hover`, `--pbe-sidebar`, `--pbe-text`,
695
+ `--pbe-muted`, `--pbe-border`, `--pbe-input-*`, the status colours,
696
+ `--pbe-radius`, `--pbe-focus`, `--pbe-shadow`, …). From alpha.9 those variables
697
+ are gone: the dashboard ignores them, so an old `admin-theme.css` keeps
698
+ working, but only its `--pbe-accent` and `--pbe-accent-text` still apply. Delete
699
+ every other line, and give the two a value per mode as above (an accent set
700
+ only once, for both modes, is the most common leftover).
701
+
702
+ ## 11. Connect Supabase
703
+
704
+ What only the owner can do comes first; one command does the rest.
705
+
706
+ 1. **Accounts and values (owner).** Create a Supabase project. Copy its
707
+ **Project URL** and **publishable key** (Project Settings → API Keys) into
708
+ `.env.local` — both are public, so the owner may paste them to an AI assistant;
709
+ never the secret key:
710
+ ```
711
+ VITE_SUPABASE_URL=https://<project-ref>.supabase.co
712
+ VITE_SUPABASE_PUBLISHABLE_KEY=sb_publishable_…
713
+ ```
714
+ Create the owner's login: Authentication → Users → Add user (email, strong
715
+ password, Auto Confirm User). Recommended: turn off public sign-ups.
716
+ 2. **Email (owner)** — required for online booking; walkthrough with DNS records,
717
+ limits and costs in `EMAIL-SETUP.md`: Resend → **Domains → Add domain** (a
718
+ subdomain such as `mail.yourdomain.com`), its DNS records, wait for
719
+ “Verified”; **API Keys → Create** (Sending access, that domain); then Supabase →
720
+ Edge Functions → **Secrets**: `RESEND_API_KEY` = the key, `BOOKING_EMAIL_FROM` =
721
+ `Your Business <bookings@mail.yourdomain.com>`. The key goes there only.
722
+ 3. **Connect (anyone, an AI assistant included):**
723
+ ```bash
724
+ npx supabase@2 login # once per computer: opens the browser
725
+ npx booking-engine connect --admin owner@example.com
726
+ ```
727
+ `connect` works only on the project in `.env.local` and refuses a folder linked
728
+ to another one. In order, it: creates `supabase/config.toml` if needed (with
729
+ the mailer's entry), links the folder (asking for the database password),
730
+ lists the engine migrations and applies them after a yes (`--yes` where nobody
731
+ can answer: an AI agent, CI), makes the user the dashboard owner, deploys
732
+ `booking-mailer` (`--no-verify-jwt --use-api`: no Docker), runs the mailer SQL
733
+ one statement at a time and stores the returned token as the secret
734
+ `BOOKING_MAILER_TOKEN` without showing it, and checks the wiring. Whatever it
735
+ cannot do — a missing login, user, value or the email secrets — stops it with
736
+ the exact action and exit code 2; run it again afterwards. It is safe to run
737
+ any number of times; `--check` only looks and changes nothing. It prints no
738
+ secret and needs none: it never reads the Resend key or any Supabase key.
739
+ A missing owner login does not hold up the email setup. It also adds
740
+ `supabase/.temp/` (this computer's link) to `.gitignore`. Once the website is
741
+ live, `connect --site-url https://yourdomain.com` stores the dashboard address
742
+ as the optional secret `BOOKING_ADMIN_URL`, so owner alerts get an “Open your
743
+ dashboard” button (without it they say to open the dashboard).
744
+ 4. **Dashboard (owner).** Restart `npm run dev`, open `/admin/` and follow
745
+ **Finish setting up**: business name and time zone, services (or the starter
746
+ set) and hours; then in **Email & online booking** choose where
747
+ **new-request alerts** go (“Send new-request alerts to”, or the public business
748
+ email — every new request is emailed there, and without either nobody is
749
+ told), send a test email to that address, switch online booking on (the
750
+ dashboard waits for a working email *and* an alerts address) and make a test
751
+ booking with your own email address.
752
+
753
+ `@2` keeps the Supabase CLI on the line this engine is verified with (2.122).
754
+ Supabase CLI 3 applies the engine's migrations the same way but confirms with a
755
+ default of **No**; its other steps are not verified with the engine yet.
756
+
757
+ ### By hand (what `connect` runs)
758
+
759
+ ```bash
760
+ npx supabase@2 init # only if supabase/config.toml does not exist
761
+ npx booking-engine sync # after `supabase init`: adds the mailer's entry to supabase/config.toml
762
+ npx supabase@2 link --project-ref <project-ref>
763
+ npx supabase@2 db push --dry-run
764
+ npx supabase@2 db push
765
+ npx supabase@2 functions deploy booking-mailer --no-verify-jwt --use-api
766
+ ```
767
+ Then in the SQL Editor: `select booking.add_admin('owner@example.com');` and the
768
+ output of `npx booking-engine mailer-sql`; copy the `booking_mailer_token` it
769
+ returns into Edge Functions → Secrets as `BOOKING_MAILER_TOKEN` (a mailer-only
770
+ token, not a Supabase key).
771
+
772
+ ## 12. Build and deploy
773
+
774
+ `npm run build` produces a static `dist/` (including `dist/admin/index.html`).
775
+ Set the same two `VITE_` variables in the host before building — they are
776
+ compiled into the JavaScript bundle. Email secrets never go to the website
777
+ host: they live in Supabase (Edge Function secrets and the engine's private tables). Run `npx booking-engine doctor --dist dist`
778
+ to confirm no secret key is in the output. Any static host works; Profit
779
+ Studio guides use Hostinger.
780
+
781
+ The engine's Vite plugin (§15) checks the two variables before anything is
782
+ built (`checkBackendEnv`, also exported): half a pair, a misnamed variable
783
+ (`VITE_SUPABASE_ANON_KEY`, names without `VITE_`…), a dashboard address
784
+ instead of the Project URL, an `http://` address, quotes, or a secret or email
785
+ key **stop the build** with one line per problem — so a host never publishes a
786
+ silently unconnected site or a secret key. With neither variable set the build
787
+ succeeds and its log says that online booking will be off. Messages name
788
+ variables, never their values.
789
+
790
+ With website content (§15), the build also bakes the **published** content into
791
+ the page (`@profitstudio/booking-engine/vite`): the title and description search
792
+ engines and link previews read, and a snapshot for the first paint. Changes the
793
+ owner publishes later reach visitors at once; crawlers see them after the next
794
+ build (on Hostinger: push a commit, or start a build in hPanel). If a configured
795
+ backend cannot be reached, the build fails rather than publishing the defaults.
796
+
797
+ ## 13. Upgrading
798
+
799
+ ```bash
800
+ npm install --save-exact @profitstudio/booking-engine@<new exact version>
801
+ npx booking-engine sync # adds the new engine migrations, updates the lock
802
+ npx supabase@2 db push --dry-run # review
803
+ npx supabase@2 db push # after a backup
804
+ npm run build && npx booking-engine doctor --dist dist
805
+ ```
806
+
807
+ PATCH and MINOR versions never break a working site; MAJOR versions come with
808
+ an upgrade guide. A site that does not upgrade keeps working on its version.
809
+ `sync` also updates `supabase/functions/booking-mailer/`; redeploy it with
810
+ `npx supabase@2 functions deploy booking-mailer --no-verify-jwt --use-api`.
811
+
812
+ ### Upgrading from 2.0.0-alpha.13
813
+
814
+ No migration and no website code change: `npm install` + `sync`, rebuild.
815
+ `connect` now finishes the email setup even before the owner's login exists,
816
+ takes `--site-url https://yourdomain.com` (owner alerts get an “Open your
817
+ dashboard” button) and keeps `supabase/.temp/` out of Git (so does `init`). The
818
+ dashboard warns on every page when the daily code-email limit is used up. Sites
819
+ built from an older prompt: check that every Book button reaches the booking
820
+ section while online booking is off (BUILD-A-SITE §4).
821
+
822
+ ### Upgrading from 2.0.0-alpha.12
823
+
824
+ No migration and no website code change. New: `npx booking-engine connect`
825
+ (§11) does the Supabase and email setup that used to take a dozen commands and
826
+ the SQL Editor, and `npx booking-engine photos` prepares a site's photos;
827
+ `docs/BUILD-A-SITE.md` is the short guide for building a site.
828
+
829
+ ### Upgrading from 2.0.0-alpha.11
830
+
831
+ No migration and no website code change: `npm install` + `sync`, rebuild. The
832
+ dashboard now asks where new-request alerts go (setup checklist, Email page)
833
+ and keeps online booking from being switched on without an address; a business
834
+ already online without one sees a warning on every page until it sets one.
835
+
836
+ ### Upgrading from 2.0.0-alpha.10
837
+
838
+ No migration (the database stays at schema 2.0.0-alpha.10) and no website
839
+ code change. `npm install` + `sync` (it updates the lock and `BOOKING_ENGINE.md`). Builds now stop
840
+ on an unusable Supabase connection (§12): if one stops, fix the variable it
841
+ names.
842
+
843
+ ### Upgrading from 2.0.0-alpha.9
844
+
845
+ `sync` adds migration `0008_service_images_opening_times`: an optional `image`
846
+ on services (photos go into the existing `booking-site-media` bucket, under
847
+ `services/`; same policies) and the public opening-times read. It is additive:
848
+ existing services, bookings, prices and availability do not change, and no
849
+ website code has to change. Optionally: render `service.image` in your design
850
+ (§6), and switch “Open now” lines to `getOpeningTimes()` so partial-day
851
+ closures show correctly. Until the migration is applied, photos and opening
852
+ times answer `SCHEMA_INCOMPATIBLE` and everything else works as before.
853
+
854
+ ### Upgrading from 2.0.0-alpha.6
855
+
856
+ `sync` adds migration `0007_site_content` (the content tables and the
857
+ `booking-site-media` image bucket; nothing else changes) and an updated
858
+ `booking-mailer`: run `db push`, then redeploy the function. No website code
859
+ has to change — booking works as before. To let the owner edit the site, add a
860
+ content schema (§15) and pass it to `<BookingAdmin content>`.
861
+
862
+ ### Upgrading from 2.0.0-alpha.3 (alpha releases may change the contract)
863
+
864
+ 1. Install, `sync`, `db push` as above, then do the email setup (§11 step 6).
865
+ After the upgrade **online booking is off** until a test email has been
866
+ delivered and the owner switches it on in the dashboard; existing bookings
867
+ and settings are kept.
868
+ 2. Website code:
869
+ - Replace `createBooking(request)` with `requestBooking(request)` followed by
870
+ a code step that calls `verifyBooking({ requestId, code })` (§6, §8).
871
+ Keep the same request object; the confirmation object is unchanged.
872
+ - Add “Send a new code” (`resendVerificationCode`), “Choose another time”
873
+ (`cancelBookingRequest`) and handle the new error codes (§6, §7).
874
+ - When `business.policies.onlineBookingEnabled` is `false`, show contact
875
+ details instead of the flow.
876
+ - `status: 'confirmed'` now happens when the owner turns on instant
877
+ confirmation: keep handling both statuses.
878
+
879
+ ## 14. Checks
880
+
881
+ ```bash
882
+ npx booking-engine doctor # versions, engine files, env keys, source usage (+ ./dist if present)
883
+ npx booking-engine doctor --dist dist # also scans the build output for secrets
884
+ ```
885
+
886
+ `doctor` checks the Supabase connection in your `.env` files the same way the
887
+ build does (§12) — for `npm run dev` and for a production build — and works
888
+ offline: it never contacts Supabase.
889
+
890
+ ## 15. Website content — what the owner can edit
891
+
892
+ The design stays the website's: the owner changes **values the website
893
+ declares** — headlines, about text, photos, the logo, brand colours, the
894
+ heading style, FAQ, testimonials — never the layout. This is not a page builder
895
+ or a CMS. Each website declares its own fields, so a one-page salon and a
896
+ gallery-first studio get different editors from the same dashboard.
897
+
898
+ ### Declare the fields — `src/content/site.ts`
899
+
900
+ This file is also loaded by `vite.config.ts` (the build plugin), which runs in
901
+ Node: keep it plain data. Import only `@profitstudio/booking-engine` and local
902
+ `.ts` files with their extension; no CSS, image or JSX imports — default image
903
+ `src` values are public-folder URLs (`/photos/hero-1600.webp`).
904
+
905
+ ```ts
906
+ import { defineSiteContent } from '@profitstudio/booking-engine';
907
+
908
+ export const siteContent = defineSiteContent({
909
+ sections: [
910
+ {
911
+ id: 'hero',
912
+ label: 'Hero',
913
+ description: 'The first screen visitors see.',
914
+ fields: [
915
+ { type: 'text', id: 'hero.title', label: 'Headline', default: "The cut you'll still love", maxLength: 70, required: true },
916
+ { type: 'longText', id: 'hero.lede', label: 'Introduction', default: 'Cuts, color and styling…', maxLength: 280, rows: 3 },
917
+ { type: 'image', id: 'hero.photo', label: 'Photo', default: { src: '/hero.jpg', alt: 'The salon floor' }, aspectRatio: 4 / 5 },
918
+ ],
919
+ },
920
+ {
921
+ id: 'brand',
922
+ label: 'Brand',
923
+ fields: [
924
+ { type: 'color', id: 'brand.accent', label: 'Accent', default: '#8a4420', contrastWith: '#fbf6ee', minContrast: 4.5 },
925
+ { type: 'choice', id: 'brand.headings', label: 'Heading style', default: 'serif',
926
+ options: [{ value: 'serif', label: 'Classic serif' }, { value: 'sans', label: 'Modern sans' }] },
927
+ ],
928
+ },
929
+ ],
930
+ });
931
+ ```
932
+
933
+ | Type | Value the site receives | Options |
934
+ |---|---|---|
935
+ | `text` | `string`, one line | `maxLength` (default 160), `required`, `placeholder` |
936
+ | `longText` | `string`; line breaks kept (render with `white-space: pre-line`) | `maxLength` (default 2000), `required`, `rows` |
937
+ | `link` | `string`: `https:`/`http:`, `mailto:`, `tel:`, `#anchor` or `/path` only | `required` |
938
+ | `image` | `{ src, alt, width?, height? }` or `null` (removed) | `aspectRatio` (a hint for the owner) |
939
+ | `color` | `#rrggbb` | `contrastWith` + `minContrast`: refused below that WCAG ratio |
940
+ | `choice` | one of the option values (typed as their union) | `options: [{ value, label, description? }]` |
941
+ | `toggle` | `boolean` | — |
942
+ | `list` | array of items with the listed sub-fields (`text`, `longText`, `link`, `image`, `toggle`) | `fields`, `itemLabel`, `maxItems` (default 12, at most 50), `minItems` |
943
+
944
+ Rules:
945
+
946
+ - **Defaults are the website's own copy**: until the owner publishes, the site
947
+ shows exactly them, and a field without a valid stored value always falls back
948
+ to its default — the page can never render half-empty.
949
+ - Ids look like `section.name` (`/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9_-]+){0,4}$/`,
950
+ unique). The owner's value is stored under the id: **never rename or reuse an
951
+ id on a live site** — add a new one. Removing a field is safe (its stored
952
+ value is ignored).
953
+ - `defineSiteContent` throws at start-up on a duplicate or invalid id, a choice
954
+ default that is not an option, or an image inside a list default.
955
+ - Not content: services, prices, durations, opening hours, the address, phone
956
+ and email — they come from the engine (`getBusiness()`, `listServices()`).
957
+ - **Images in lists** (stylist portraits, gallery items) cannot have a default:
958
+ a list's default items hold text only. Give list images a fallback in the
959
+ site instead — e.g. show the site's own sample photos (labelled “Sample
960
+ photo”) while the owner has not set the list (`ownerFields`), or declare a few
961
+ top-level `image` fields that hold those samples.
962
+ - **Responsive defaults.** An image value is a single `src`. For the site's own
963
+ default photos, keep a small map from each default `src` to its AVIF/WebP
964
+ variants and render a `<picture>` with `srcset`/`sizes`; photos the owner
965
+ uploads arrive already resized (longest side 2400 px, WebP) and render as one
966
+ `<img>`. Always give the frame a fixed `aspect-ratio` and `object-fit: cover`
967
+ so any replacement keeps the layout.
968
+
969
+ ### Render it
970
+
971
+ ```tsx
972
+ // src/lib/content.ts
973
+ import { createSiteContentStore, readSiteContentSnapshot } from '@profitstudio/booking-engine';
974
+ import { siteContent } from '../content/site';
975
+ import { engine } from './engine';
976
+
977
+ export const contentStore = createSiteContentStore(engine, siteContent, { snapshot: readSiteContentSnapshot() });
978
+
979
+ // In a provider component:
980
+ const [content, setContent] = useState(() => contentStore.initial()); // synchronous, for the first paint
981
+ useEffect(() => { void contentStore.load().then(setContent); }, []); // the current published copy
982
+
983
+ // Anywhere:
984
+ <h1>{content.values['hero.title']}</h1>
985
+ {content.values['hero.photo'] && <img src={content.values['hero.photo'].src} alt={content.values['hero.photo'].alt} />}
986
+ ```
987
+
988
+ `values` is fully typed from the schema (a typo in an id is a type error).
989
+ `initial()` uses the newest copy at hand — the snapshot baked into the page at
990
+ build time, or the last published copy this browser saw — else the defaults;
991
+ `load()` then fetches the published copy (one request) and caches it. Offline
992
+ or on an older database the site keeps what it has. `ownerFields` lists the
993
+ fields the owner has set, e.g. to drop a “sample” label once real stylists are
994
+ entered.
995
+
996
+ Brand values are validated (`#rrggbb` colours, known choice values): map them
997
+ onto the design's own CSS variables, e.g.
998
+ `document.documentElement.style.setProperty('--accent', values['brand.accent'])`
999
+ and `document.documentElement.dataset.headings = values['brand.headings']`
1000
+ (in a layout effect, so a returning visitor never sees the old colours flash).
1001
+
1002
+ Never render owner content as HTML (`dangerouslySetInnerHTML`, `innerHTML`),
1003
+ and never build image URLs yourself: images arrive as resolved `src` URLs from
1004
+ the engine's media bucket.
1005
+
1006
+ ### Preview and publish
1007
+
1008
+ Dashboard → **Website**: one tab per section, the website's fields in it.
1009
+ **Save draft** stores a private draft; **Preview** opens the real website with
1010
+ `?preview=draft`, which shows the draft only to a signed-in admin (same browser
1011
+ as the dashboard) — anyone else gets the published site (`previewDenied` is
1012
+ set, so the site can say so).
1013
+ **Publish** makes the draft the public version; visitors get it on their next
1014
+ visit or refresh. **Discard changes** returns to the published version. Two
1015
+ admins cannot overwrite each other: a save based on an old draft is refused
1016
+ and the owner is told someone else saved changes in the meantime.
1017
+
1018
+ Images: JPEG, PNG, WebP or AVIF. Before uploading, the dashboard redraws every
1019
+ camera photo (JPEG) in the browser — keeping only the pixels, so hidden EXIF
1020
+ data such as the GPS position where it was taken is never published — and
1021
+ shrinks anything larger than needed (longest side 2400 px, WebP); the bucket
1022
+ accepts at most 5 MB per file. Every upload is a new file (nothing is overwritten); an
1023
+ image description (alt text) is required before publishing; files no draft or
1024
+ published version uses are deleted on a later publish, after 24 hours.
1025
+
1026
+ ### Search engines and static hosting
1027
+
1028
+ Content is rendered in the browser. The browser tab title can follow at once,
1029
+ but search engines and link previews read the HTML the host serves, which is
1030
+ fixed at build time. Bake the published content into the page during the
1031
+ build with the engine's Vite plugin:
1032
+
1033
+ ```ts
1034
+ // vite.config.ts
1035
+ import { defineConfig, loadEnv } from 'vite';
1036
+ import react from '@vitejs/plugin-react';
1037
+ import { fileURLToPath } from 'node:url';
1038
+ import { publishedSiteContent } from '@profitstudio/booking-engine/vite';
1039
+ import { siteContent } from './src/content/site.ts'; // tsconfig.node.json: "allowImportingTsExtensions": true
1040
+
1041
+ export default defineConfig(({ mode }) => ({
1042
+ plugins: [
1043
+ react(),
1044
+ publishedSiteContent({
1045
+ schema: siteContent,
1046
+ env: loadEnv(mode, process.cwd(), 'VITE_'),
1047
+ meta: (values) => ({ title: values['seo.title'], description: values['seo.description'] }),
1048
+ }),
1049
+ ],
1050
+ build: {
1051
+ rolldownOptions: { // Vite 8; `rollupOptions` on Vite 7
1052
+ input: {
1053
+ main: fileURLToPath(new URL('./index.html', import.meta.url)),
1054
+ admin: fileURLToPath(new URL('./admin/index.html', import.meta.url)),
1055
+ },
1056
+ },
1057
+ },
1058
+ }));
1059
+ ```
1060
+
1061
+ It reads the published content once per build and writes into
1062
+ `index.html` (not `/admin/`): the `<title>`, `<meta name="description">`,
1063
+ `og:title` / `og:description` when present, and a snapshot that
1064
+ `readSiteContentSnapshot()` reads back for the first paint (escaped so content
1065
+ can never close its `<script>` tag). `meta` is optional; declare the search
1066
+ fields you want the owner to control (e.g. `seo.title`, `seo.description`).
1067
+
1068
+ - Write your **default** title and description into `index.html` as plain text
1069
+ (no placeholders): the dev server shows them as they are, the plugin replaces
1070
+ them only in builds, and your site sets `document.title` from the content at
1071
+ run time.
1072
+ - This plugin is the only place that reads `booking_get_site_content` outside
1073
+ the client — never call booking RPCs yourself (§2).
1074
+ - `meta` receives text values only: images resolve to their defaults there, so
1075
+ an owner's photo cannot become an `og:image` yet.
1076
+
1077
+ | Situation at build time | Result |
1078
+ |---|---|
1079
+ | No `VITE_SUPABASE_*` variables (local preview builds) | the site's defaults, and no snapshot tag (nothing is published) |
1080
+ | The database has no website content yet (schema before alpha.7) | the defaults, with a warning — nothing was ever published |
1081
+ | Content loaded | the published title, description and snapshot |
1082
+ | A backend is configured but cannot be read (outage, wrong key, network) — after three attempts | **the build fails**, so the host keeps serving the previous build with its real published text instead of silently replacing it with the defaults |
1083
+ | The same, with `SITE_CONTENT_OPTIONAL=1` in the build environment | the defaults, on purpose (e.g. to ship a code fix during a Supabase outage) |
1084
+
1085
+ Tell the owner the truth in the dashboard field help: *search engines and link
1086
+ previews show new text after the website is next deployed.*
1087
+
1088
+ ### Security
1089
+
1090
+ - The public read (`getSiteContent()`, RPC `booking_get_site_content`) returns
1091
+ only `{ version, publishedAt, values }` of the published document — never the
1092
+ draft, never booking or customer data.
1093
+ - Only admins read or change the draft, publish, upload or delete images
1094
+ (row-level security; the functions check `booking.is_admin()`).
1095
+ - The database refuses malformed documents: keys must look like field ids,
1096
+ strings are plain text (no control characters, at most 5000 characters),
1097
+ images must point into the bucket's `site/` folder, at most 300 fields and
1098
+ 200 KB. The dashboard and `resolveSiteContent` additionally apply the
1099
+ schema's own rules, so an invalid stored value shows the default.
1100
+ - Images live in the public bucket `booking-site-media`: anyone can read a file
1101
+ by its URL; listing, uploading and deleting are admin-only; only image types,
1102
+ 5 MB per file, no overwrites. Website images use its `site/` folder (tidied
1103
+ by the website editor when no content uses them); service photos use
1104
+ `services/` (tidied by the Services editor), and the database accepts a
1105
+ service photo only from that folder. Never put anything private in it.
1106
+
1107
+ ### Limits in alpha.7
1108
+
1109
+ One content document per website, one language, a draft and a published
1110
+ version (no history or scheduled publishing). Images are not cropped or
1111
+ focal-pointed — the site's CSS decides (`object-fit`). The search-facing title
1112
+ and description update on the next build, not on publish.