# Design ## Stack - Cloudflare Workers runtime for the server; Node.js 20 or later only to install, build and test. TypeScript throughout, ES modules. - Server: one Worker (`src/worker/index.ts`, `export default { fetch }`), a small hand-written router or Hono (either is fine), Cloudflare D1 through the `DB` binding with `prepare().bind()` and `batch()`, `luxon` for every time-zone sum. No ORM. No Node.js built-ins, no `nodejs_compat`. Web Crypto for passwords and tokens. - Tooling: `wrangler` 4 (dev dependency) for `wrangler dev`, D1 migrations, `wrangler types` (writes `worker-configuration.d.ts` with the `Env` type; use `--strict-vars=false` so vars type as `string`) and deploy. Keep the Worker's tsconfig separate from the client's (Worker: `types: []` plus `worker-configuration.d.ts`; client: DOM libs). - Client: React 18 or 19, React Router, Vite. Plain CSS with custom properties (one stylesheet, or CSS modules). No UI kit. - Tests: Vitest for units, Playwright (Chromium) for end-to-end. - Use React Router's data router (`createBrowserRouter` and `RouterProvider`): the editor's "Discard changes?" guard needs `useBlocker`, which the plain `BrowserRouter` does not support. - The client asks `GET /api/now` before its first render. Do it with a promise, not a top-level `await`, which Vite's default build target refuses. - Public pages (profile, booker, booking page) do not ask for the session. - Static assets: Workers static assets serve `dist/`, with `not_found_handling: "single-page-application"` so every app path gets `index.html`, and `run_worker_first: ["/api/*"]` so only API calls run the Worker. Unknown `/api/...` paths answer JSON 404. - The Worker checks that a `POST`, `PATCH` or `DELETE` carrying an `Origin` header comes from the same origin (403 otherwise), refuses bodies over 200 KB (413), and turns any unexpected error into a JSON 500 with a plain message, logging the detail with `console.error`. ## Cloudflare config `wrangler.jsonc`: ```jsonc { "$schema": "node_modules/wrangler/config-schema.json", "name": "scheduler", "main": "src/worker/index.ts", "compatibility_date": "", "assets": { "directory": "./dist", "binding": "ASSETS", "not_found_handling": "single-page-application", "run_worker_first": ["/api/*"] }, "d1_databases": [ { "binding": "DB", "database_name": "scheduler", // Local dev works with this placeholder; replace it before deploying. "database_id": "00000000-0000-0000-0000-000000000000", "migrations_dir": "migrations" } ], // ALLOWED_EMAILS / ALLOW_SIGNUP: see R2 (owner-only deployments). "vars": { "NOW": "", "TEST_CLOCK": "0", "ALLOWED_EMAILS": "", "ALLOW_SIGNUP": "1" }, "observability": { "enabled": true, "traces": { "enabled": true } } } ``` `package.json` scripts: - `build`: `vite build` - `db:migrate:local`: `wrangler d1 migrations apply DB --local` - `dev`: `npm run build && npm run db:migrate:local && wrangler dev` - `test`: `vitest run` - `e2e`: `playwright test` - `deploy`: `npm run build && wrangler deploy` - `types`: `wrangler types --strict-vars=false` The clock helper reads, in order: the `test_now` cookie when `TEST_CLOCK` is `"1"`, then `NOW` when not empty, then the real time. It is used for every "now" on the server (sessions, notice, tabs, today's overrides). ## Deploy Written into the README. Needs the user's own Cloudflare account; never done by tests. 1. `npx wrangler login` (or set `CLOUDFLARE_API_TOKEN` to a token that can edit Workers and D1). 2. `npx wrangler d1 create scheduler` and paste the printed `database_id` into `wrangler.jsonc`. 3. `npx wrangler d1 migrations apply DB --remote`. 4. `npm run deploy`. The app is on `https://scheduler..workers.dev`. The demo user is created on the first API request when `seed_demo` is on; turn `seed_demo` off for a real deployment. 5. Logs: `npx wrangler tail`, or the Workers dashboard (observability is on). Leave `NOW` empty and `TEST_CLOCK` `"0"` in production. For a personal deployment set `ALLOWED_EMAILS` to the owner's email, create the account, then set `ALLOW_SIGNUP` to `"0"` (dashboard: Workers & Pages > the Worker > Settings > Variables and Secrets, or edit `wrangler.jsonc` and deploy). Keep `workers_dev` on only if you want the `workers.dev` address. Field maxima and colour swatches are defined in R4 of `spec.md`; apply the same limits on forms and API validation. Account names and booker names also use the 80-character name limit. ## Data model D1 (SQLite) tables, created only by `migrations/0001_init.sql` (later changes go in new numbered files). `id` columns are `INTEGER PRIMARY KEY`. Foreign keys use `ON DELETE CASCADE` from users, schedules and their rows; `event_types.schedule_id` uses `ON DELETE SET NULL`. Times marked UTC are ISO strings like `2026-11-16T14:00:00.000Z`. Booleans are 0 or 1. **users**: `id`, `email` (unique, stored lower case), `password_hash` (`pbkdf2-sha256$100000$$`, Web Crypto PBKDF2-SHA256, 100000 iterations, 16-byte salt, 32-byte key), `name`, `username` (unique), `bio`, `time_zone` (IANA), `time_format` (12 or 24, default 12), `week_start` (`monday` or `sunday`, default `monday`), `created_at` UTC. The session cookie is named `session`. **sessions**: `token` (32 random bytes, hex, primary key), `user_id`, `expires_at` UTC. **schedules**: `id`, `user_id`, `name`, `time_zone`, `is_default`. Each user has exactly one default schedule; setting another as default clears the old first in the same batch. Add `CREATE UNIQUE INDEX s_one_default ON schedules(user_id) WHERE is_default=1`. The default cannot be deleted or unset without a replacement. A duplicate appends " (copy)" to the name and is not the default. **schedule_hours**: `id`, `schedule_id`, `weekday` (0 = Sunday ... 6 = Saturday), `start_min`, `end_min`. Minutes from local midnight, `0 <= start_min < end_min <= 1440`, multiples of 15. Several rows per weekday allowed, not overlapping. **date_overrides**: `id`, `schedule_id`, `date` (`YYYY-MM-DD`), `start_min`, `end_min`. A row with both null means unavailable all day. Several rows per date allowed (ranges); a date has either one null row or ranges, never both. **event_types**: `id`, `user_id`, `title`, `slug` (unique per user, `a-z0-9-`, 1 to 60), `description`, `duration_min`, `position` (order on lists, lower first), `hidden`, `location_kind` (`video`, `phone`, `in_person`, `custom`), `location_value`, `schedule_id` (null = the user's default schedule), `min_notice_min` (default 120), `buffer_before_min`, `buffer_after_min`, `slot_step_min` (null = use the duration), `max_per_day` (null = no limit), `future_days` (null = no limit), `requires_approval`, `hide_guests`, `color` (`#rrggbb`), `created_at` UTC. **bookings**: `id`, `uid` (unique), `event_type_id` (kept even if the event type is deleted: delete sets a `deleted_at` on the event type instead of removing the row), `host_id`, `title` (event title at booking time), `start_utc`, `end_utc`, `start_ms`, `end_ms` (the same instants as integer epoch milliseconds, for the guard), `buffer_before_min`, `buffer_after_min` (the event type's buffers copied at booking time, so later edits to the event do not move existing bookings' guard zones), `status` (`accepted`, `pending`, `cancelled`, `rejected`), `booker_name`, `booker_email`, `booker_phone`, `booker_tz`, `notes`, `guests` (JSON array of emails), `location`, `cancel_reason`, `cancelled_by` (`host` or `guest`), `rescheduled` (1 when it was cancelled by being moved), `from_uid` (the booking it was moved from), `reschedule_reason`, `created_at` UTC. Indexes: bookings by `(host_id, start_ms)`, unique by `uid`; event types by `(user_id, slug)`. No unique index on the active host/start pair: same-start rescheduling relies on the conditional insert, which excludes the old uid, then cancels the old row in the same batch. Reserved usernames: `api`, `login`, `signup`, `logout`, `event-types`, `bookings`, `booking`, `availability`, `settings`, `reschedule`, `assets`, `static`, `admin`, `app`, `new`. ## API JSON in and out. Errors: status 400 (bad input, with `fields`), 401 (no session), 403, 404, 409 (slot taken or state conflict). Times in and out are UTC ISO. Public, no session: - `GET /api/now` -> `{ now }`. - `GET /api/public/users/:username` -> `{ user: {name, username, bio, weekStart, timeFormat}, eventTypes: [{title, slug, description, durationMin, locationKind}] }` (visible, not deleted, by position). - `GET /api/public/users/:username/events/:slug` -> the event type's public fields, `requiresApproval`, `hideGuests`, and the host's public fields. Hidden event types are returned; deleted ones are 404. - `GET /api/public/slots?username=&slug=&start=&end=&tz=&reschedule=` -> `{ slots: { "YYYY-MM-DD": ["", ...] } }`. `start` and `end` are UTC ISO and at most 45 days apart; keys are dates in `tz`. The client asks for the whole visible month in the visitor's zone. - `POST /api/public/bookings` `{ username, slug, start, name, email, phone?, notes?, guests?, timeZone, reschedule?, rescheduleReason? }` -> 201 `{ uid }`. With `asHost: true` (host reschedule, R11) only `username`, `slug`, `start`, `reschedule` and `rescheduleReason` are read: the signed-in user must be the old booking's host (401 / 404), the guest's details are copied from the old booking, the new booking is `accepted`, and the old one gets `cancelled_by = host`. When `reschedule` is a uid, it must be a booking of this host and event with status `accepted` or `pending` that has not started; the new booking copies the status rule of the event (approval again if needed), and the old one is set to `cancelled`, `rescheduled = 1`, `cancelled_by = guest`, in the same D1 `batch()` (one transaction) as the insert; see "Double-booking guard". - `GET /api/public/bookings/:uid` -> the booking with event title, duration, location, host name, email and username, event slug, `fromUid`, and whether a newer booking was moved from it (`movedToUid`). - `POST /api/public/bookings/:uid/cancel` `{ reason? }` -> the booking. 409 if already cancelled or rejected, or if it has started. - `GET /api/public/bookings/:uid/ics` -> `text/calendar` with one `VEVENT` (PRODID `-////EN`, UID `{uid}@scheduler`, DTSTART and DTEND in UTC, SUMMARY, LOCATION, DESCRIPTION with the notes), `METHOD:PUBLISH`. Session needed: - `POST /api/auth/signup`, `POST /api/auth/login`, `POST /api/auth/logout`, `GET /api/me`, `PATCH /api/me`. - `GET/POST /api/event-types`, `GET/PATCH/DELETE /api/event-types/:id`, `POST /api/event-types/:id/duplicate`, `POST /api/event-types/:id/move` `{ direction: "up" | "down" }`. - `GET/POST /api/schedules`, `GET/PATCH/DELETE /api/schedules/:id` (PATCH takes the whole schedule: name, timeZone, isDefault, hours[], overrides[], and replaces the rows in one D1 `batch()`), `POST /api/schedules/:id/duplicate`. - `GET /api/bookings?status=upcoming|unconfirmed|past|cancelled&cursor=` -> `{ items, nextCursor, counts: {upcoming, unconfirmed, past, cancelled} }`. Each item also carries its event type's slug and colour, so the row can link to `/{username}/{slug}?reschedule={uid}` and draw its colour bar. - `POST /api/bookings/:uid/accept`, `/decline` `{reason?}`, `/cancel` `{reason?}` (sets `cancelled_by = host`). Tab definitions, with `now` the server clock: - **upcoming**: status `accepted`, `end_utc > now`. - **unconfirmed**: status `pending`, `end_utc > now`. - **past**: status `accepted` or `pending`, `end_utc <= now`. - **cancelled**: status `cancelled` or `rejected`, any time. ## Slot maths One pure module, `src/shared/slots.ts`, with no database or clock access: ```ts computeSlots(input: { now: string; // UTC ISO rangeStart: string; // UTC ISO, inclusive rangeEnd: string; // UTC ISO, exclusive schedule: { timeZone: string; hours: {weekday:number; startMin:number; endMin:number}[]; overrides: {date:string; startMin:number|null; endMin:number|null}[] }; event: { durationMin:number; stepMin:number|null; minNoticeMin:number; bufferBeforeMin:number; bufferAfterMin:number; maxPerDay:number|null; futureDays:number|null }; busy: { start:string; end:string; bufferBeforeMin:number; bufferAfterMin:number; sameEvent:boolean }[]; // the host's accepted + pending bookings near the range }): string[] // free slot starts, UTC ISO, sorted ``` Steps: 1. **Windows.** For each local date `d` in the schedule's zone from the day before `rangeStart` to the day after `rangeEnd`: if any override has `date = d`, use the override rows (none if the row is all-day unavailable); otherwise use the `hours` rows whose weekday is `d`'s weekday. Each row becomes a window from `d` at `startMin` to `d` at `endMin`, built with Luxon as wall-clock time in the zone (`DateTime.fromObject({year, month, day}, {zone}).plus({minutes})` is wrong on DST days; build the hour and minute directly with `DateTime.fromObject({year, month, day, hour, minute}, {zone})`, and `endMin = 1440` means the next date at 00:00). A wall time that does not exist (the spring-forward gap) moves forward to the first real time, which Luxon does by default. Sort windows and merge any that overlap or touch, so 23:00-24:00 and the next day's 00:00-01:00 make one window. 2. **Candidates.** `step = stepMin ?? durationMin`. In each window, the candidates are `window.start + k * step` for k = 0, 1, 2, ... while `start + durationMin <= window.end`. Counting from the window start (not from the hour) keeps slots the same for every visitor whatever their zone. 3. **Notice and horizon.** Drop a candidate whose start is before `now + minNoticeMin`. If `futureDays` is set, drop a candidate that starts on or after the start of the local date (schedule zone) that is `futureDays` days after today's local date. Drop candidates outside `[rangeStart, rangeEnd)`. 4. **Conflicts.** A candidate `[s, e)` clashes with busy booking `b` when `s - event.bufferBeforeMin - b.bufferAfterMin < b.end` and `e + event.bufferAfterMin + b.bufferBeforeMin > b.start`. That is, the gap between them must fit both events' buffers on that side. Drop clashes. 5. **Per-day limit.** If `maxPerDay` is set, count busy bookings with `sameEvent` for each local date (schedule zone) of their start; drop every candidate on a date whose count is at least `maxPerDay`. The server builds `busy` from the host's bookings with status `accepted` or `pending` whose times fall within the range widened by 1 day each side, leaving out the booking being rescheduled. Each busy entry's buffers are the buffers stored on that booking. The booking endpoint calls `computeSlots` from 12 hours before to 12 hours after the asked start and checks that the exact start string is in the answer (409 if not), then writes through the guard below. ### Double-booking guard D1 has no interactive transactions (no `BEGIN` across awaits), but runs each statement, and each `batch()`, atomically and one at a time. So the check that matters is inside the write. With numbered parameters: ```sql INSERT INTO bookings (uid, event_type_id, host_id, title, start_utc, end_utc, start_ms, end_ms, buffer_before_min, buffer_after_min, status, booker_name, booker_email, booker_phone, booker_tz, notes, guests, location, from_uid, reschedule_reason, created_at) SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21 WHERE NOT EXISTS ( SELECT 1 FROM bookings x WHERE x.host_id = ?3 AND x.status IN ('accepted','pending') AND x.uid IS NOT ?19 AND ?7 - ?9*60000 - x.buffer_after_min*60000 < x.end_ms AND ?8 + ?10*60000 + x.buffer_before_min*60000 > x.start_ms) AND (?22 IS NULL OR ( SELECT COUNT(*) FROM bookings y WHERE y.event_type_id = ?2 AND y.status IN ('accepted','pending') AND y.uid IS NOT ?19 AND y.start_ms >= ?23 AND y.start_ms < ?24) < ?22) AND (?19 IS NULL OR EXISTS ( SELECT 1 FROM bookings z WHERE z.uid = ?19 AND z.status IN ('accepted','pending'))); ``` `?7`/`?8` are the new start and end in ms, `?9`/`?10` the event's buffers, `?19` the uid being rescheduled (or null), `?22` `max_per_day` (or null), `?23`/`?24` the start and end in ms of the start's local day in the schedule's zone (worked out with luxon, as SQL cannot do zones). The overlap test is the same rule as step 4 of the slot maths. For a reschedule, send the insert and `UPDATE bookings SET status='cancelled', rescheduled=1, cancelled_by='guest', cancel_reason=? WHERE uid=?old AND EXISTS (SELECT 1 FROM bookings WHERE uid=?new)` together in one `batch()`. If the insert's `meta.changes` is 0, answer 409 "Someone just took this time. Pick another." Durable Objects and KV are not needed. Other multi-row writes (sign-up with its schedule, hours and two event types; the demo seed; saving a schedule; reordering event types) are one `batch()` each, so they land whole or not at all. Rows that need an id made earlier in the same batch find it with a subquery such as `(SELECT id FROM users WHERE username = ?)`. Grouping for the API: each slot goes under its date in the visitor's zone. ### Slot tests Vitest cases for `computeSlots`. Each uses a fixed `now`. 1. Basic: zone `America/New_York`, Mon-Fri 09:00-17:00, 30-minute event, no notice, `now` a Sunday. Monday 2026-11-16 has 16 slots, the first at `2026-11-16T14:00:00.000Z`, the last at `2026-11-16T21:30:00.000Z`. 2. Step: same with a 60-minute event and step 30: 15 slots, last at 16:00 local. 3. Fit: 45-minute event in 09:00-10:00: one slot at 09:00. 4. Notice: `now` = Monday 10:10 local, notice 60 minutes: first slot Monday 11:30 local (11:10 is not a slot start; slots are 30 minutes from 09:00). 5. DST forward: zone `America/New_York`, Sun 2027-03-14 is the change day with Sunday hours 01:00-04:00, 60-minute event: slots at 01:00 (06:00Z) and 03:00 (07:00Z) local; 02:00 does not exist and 01:00-02:00 runs into 03:00, so the window is two hours long, 01:00 EST to 04:00 EDT. Monday 2027-03-15 09:00 local is `13:00Z`, while Friday 2027-03-12 09:00 local is `14:00Z`. 6. DST back: Sun 2026-11-01 hours 00:00-03:00, 60-minute event: four slots (00:00, 01:00 EDT, 01:00 EST, 02:00), because the day has 25 hours. 7. Half-hour zone: schedule in `Asia/Kolkata` 09:00-10:00, 30-minute event: slots at `03:30Z` and `04:00Z`. 8. Midnight: hours 22:00-24:00 on Monday and 00:00-02:00 on Tuesday in `Europe/London` with a 120-minute event and step 60, on Monday 2026-11-16: slots at 22:00, 23:00 and 00:00 (`2026-11-16T22:00:00.000Z`, `2026-11-16T23:00:00.000Z`, `2026-11-17T00:00:00.000Z`); the 23:00 slot runs past midnight because the two windows were merged. 9. Override replaces: Monday override 13:00-14:00 gives only 13:00 and 13:30 that day; an all-day unavailable override gives none; other Mondays are unchanged. 10. Busy: a booking 10:00-10:30 removes only the 10:00 slot. 11. Buffers: this event has 15 after; the busy booking at 10:00-10:30 has 10 before. The 09:30 slot ends at 10:00, plus 15 + 10 = 10:25 > 10:00, so it is dropped; 09:00 stays. With both buffers 0 it stays. 12. Per day: `maxPerDay` 1 and one same-event booking on Monday: no Monday slots; Tuesday unaffected. A booking of another event does not count. 13. Horizon: `futureDays` 7 with `now` Sunday 2026-11-15: slots on Friday 2026-11-20, none on or after Sunday 2026-11-22. 14. Visitor zone does not change slots: grouping the basic case's slots by date in `Pacific/Kiritimati` (UTC+14) puts every one of Monday's slots under `2026-11-17`, and the slot instants are identical to case 1. ## Screens Widths are desktop (1280 px) unless said. ### Look - Background `#f9fafb` for the app, white panels with a 1 px `#e5e7eb` border and 8 px radius. Text `#111827`, secondary `#6b7280`. System font stack (`ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif`), 14 px body, 600 weight headings (page title 20 px). - Primary button: `brand_color` background, white text, 6 px radius, 36 px high. Secondary: white with border. Ghost icon buttons for row actions. Destructive: red text, and red fill inside a confirm dialog. - Switches: 36 x 20 px pill, `brand_color` when on. - Badges: 12 px text on a light grey (or light colour) pill. - Toasts in the bottom centre, dark, 3 seconds. - Dialogs: centred, 480 px wide, dimmed backdrop, title, body, and buttons on the right of the footer. ### Login and sign-up A centred 400 px card with `app_name`, the fields, a primary full-width button, and a link to the other page. Sign-up shows the public link preview `{origin}/{username}` under the username field as it is typed. ### Event types (`/event-types`) Header "Event types", subtitle "Kinds of meeting people can book with you.", button "New". One white panel holding the rows, separated by borders. Empty state: "No event types yet" / "Make one so people can book you.". ### Event type editor (`/event-types/{id}`) Header with a back arrow to the list, the title in 20 px, the hidden switch labelled "Hidden", and "Save". Tabs as a horizontal row under the header on desktop (Setup, Availability, Limits, Advanced). Each tab is a white panel of labelled fields, label above field, help text in grey under it. Leaving with unsaved changes asks "Discard changes?". ### Availability (`/availability` and `/availability/{id}`) List header "Availability", subtitle "When people can book you.", button "New". Rows show the schedule name, the "Default" badge, the summary and the zone with a small globe icon. Editor: header with back arrow, editable name, "Set as default" switch and "Save". Two columns: left (about two thirds) the panel of day rows, then the "Date overrides" panel; right a narrow panel "Time zone" with the select. A day row: switch, day name (100 px), then the ranges stacked, each `[start] - [end]` with the bin icon; "+" and the copy icon on the first range's line. An off day shows "Unavailable" in grey. Summary text: consecutive days with identical ranges are joined (`Mon - Fri`), others listed with commas (`Mon, Wed`), then the ranges (`9:00am - 5:00pm`, several joined with `, `). A schedule with no hours says "No hours set". ### Bookings (`/bookings/{status}`) Header "Bookings", subtitle "Meetings people have booked with you." Tabs "Upcoming", "Unconfirmed", "Past", "Cancelled", each with its count in a small badge. Day headings in 12 px uppercase grey. Rows in a white panel: left column 180 px with the time range and a 4 px colour bar in the event colour, middle the title, people, location and notes, right the action buttons. Empty states: "Nothing coming up", "Nothing waiting for you", "No past bookings", "No cancelled bookings", each with a short grey line (R14); the upcoming one adds an "Open your booking page" button. Upcoming and unconfirmed rows both have "Reschedule" (host mode, `&host=1`). ### Settings (`/settings/profile`, `/settings/general`) A 200 px sub-menu on the left ("Profile", "General"), the form panel on the right, "Save" under the form. ### The booker (`/{username}/{slug}`) Grey page background. One white panel, centred, with a 1 px border and 12 px radius, 1060 px wide at most, three columns: details (280 px), calendar (flexible, about 460 px), times (280 px, scrolls on its own, as tall as the calendar). Thin borders between columns. Under the panel in small grey text: "Booked with **`app_name`**" as plain text (no link: `/` sends a guest to the host sign-in page). - Details: 40 px initials avatar, host name in grey, event title 20 px bold, description, then lines with small icons: clock + duration (`30m`), place icon + location kind, check icon + "Needs approval" when needed, globe + the time zone select (plain text with a chevron until opened). - Calendar: month and year at the top left (`November 2026`, month in bold), arrows top right. Weekday headings in 12 px uppercase grey. Day tiles are square, 6 px radius, about 56 px. Free days: `#f3f4f6` tile, dark bold number, hover border. Selected: `brand_color` tile, white number. Unavailable: no tile, grey number. Days of other months are not shown (empty cells). - Times: day heading `Mon 16` (weekday bold), the 12h/24h toggle as a small two-part pill, then the time buttons: full width, 40 px high, white with border, centred text, `brand_color` border on hover. If the day has no slots, "No times left on this day". - Form view: the calendar and times columns are replaced by one form column. The details column adds a calendar icon with the day and time range. In reschedule mode it also shows a light blue note ("Rescheduling your booking" or "Moving {booker}'s booking", bold, then the instruction) and "Current time: " with the old time struck through. - Step headings: 14 px semibold "Select a date" over the calendar, "Select a time" over the times, "Enter your details" / "Confirm your new time" / "Confirm the new time" over the form, each with the grey line from R14. - Under 1024 px: one column, details, then the calendar, then the times below it; the form takes the full width. ### Booking page (`/booking/{uid}`) A white panel 600 px wide, centred. A 48 px green circle with a white check (or a grey circle with a clock for pending, a red circle with a cross for cancelled), the heading, one grey line, then a two-column grid of the rows (label 100 px, bold). Then the grey "What's next" box (R10) with "Copy link to this page" and "Add to calendar" buttons, then a border and the "Need a change?" line. ## Integrations (optional, R15-R18) None of this is needed for R1-R14. Build it behind checks so the app works with every integration unset. ### Config | Name | Kind | Used by | Notes | |---|---|---|---| | `EMAIL_PROVIDER` | var | R15 | `""` (log only), `cloudflare` or `resend` | | `EMAIL_FROM` | var | R15 | `"Name" ` on a verified domain | | `EMAIL` | `send_email` binding | R15 | `"send_email": [{ "name": "EMAIL" }]`; only with `cloudflare` | | `RESEND_API_KEY` | secret | R15 | only with `resend` | | `ENCRYPTION_KEY` | secret | R17, R18 | 32 random bytes, base64; `openssl rand -base64 32` | | `ICAL_POLL_MINUTES` | var | R17 | 5-15, default 10 | | `SITE_URL` | var | R15-R17 | public origin for links in emails and invites sent from cron (no request to read it from) | | `GOOGLE_CLIENT_ID` | var | R18 | | | `GOOGLE_CLIENT_SECRET` | secret | R18 | | `"triggers": { "crons": ["*/5 * * * *"] }` in `wrangler.jsonc`, handled by `scheduled(controller, env, ctx)`. Each run: send due reminders and retry failed emails (R15), poll iCal feeds that are due (R17), refresh Google free/busy and retry failed calendar writes (R18). Every step is wrapped so one failure does not stop the others, and each run takes a lease row in `cron_runs` (`INSERT ... WHERE NOT EXISTS` a lease younger than 4 minutes) so overlapping runs do nothing. ### Data (migration `0002_integrations.sql`, additive only) - `ALTER TABLE event_types ADD COLUMN reminder_offsets TEXT NOT NULL DEFAULT '[1440,60]'` - `ALTER TABLE bookings ADD COLUMN ics_sequence INTEGER NOT NULL DEFAULT 0`, `ADD COLUMN ics_uid TEXT` (the chain's first uid), `ADD COLUMN google_event_id TEXT`. - `email_log` (`id`, `booking_uid`, `kind` (`confirmed`, `requested`, `accepted`, `declined`, `moved`, `cancelled`, `reminder`), `offset_min` (0 except reminders), `recipient`, `status` (`sending`, `sent`, `failed`), `attempts`, `error`, `created_at`, `sent_at`), `UNIQUE (booking_uid, kind, offset_min, recipient)`. A sender first inserts the row with `INSERT OR IGNORE`; it sends only if that insert changed a row, or if the row is `failed` with fewer than 3 attempts (claimed with a conditional `UPDATE`). - `calendar_feeds` (`id`, `user_id` unique, `url_enc`, `url_hint`, `etag`, `last_modified`, `last_sync_at`, `last_ok_at` (last successful fetch), `last_error`, `fail_count`). - `busy_blocks` (`id`, `user_id`, `source` (`ical`, `google`), `start_ms`, `end_ms`), index `(user_id, start_ms)`. - `google_accounts` (`user_id` unique, `email`, `refresh_token_enc`, `connected_at`, `last_error`), `oauth_states` (`state`, `user_id`, `verifier`, `expires_at`). - `cron_runs` (`name` primary key, `started_at`). Encryption: `src/worker/crypto.ts` with `encrypt(text)` / `decrypt(blob)` using WebCrypto AES-GCM, the key imported from `ENCRYPTION_KEY`, a random 12-byte IV per value, stored as `v1..`. Saving a feed or Google token without `ENCRYPTION_KEY` set is refused with "Set ENCRYPTION_KEY first". ### API - `GET /api/integrations` -> status of each integration: `{ email: { provider, from, state, lastError }, ical: { hint, lastSyncAt, lastError, state }, google: { connected, email, state, lastError }, configured: {...} }`. Never returns a URL, key or token. - `PUT /api/integrations/ical` `{ url }` (must be `https://`, fetched once to check it parses), `DELETE /api/integrations/ical`, `POST /api/integrations/ical/sync` (sync now). - `GET /oauth/google/start` -> 302 to Google; `GET /oauth/google/callback` checks `state`, swaps the code, stores the refresh token, -> 302 `/settings/calendars`. `DELETE /api/integrations/google` revokes and deletes. - Booking, reschedule, cancel, accept and decline call `notify(kind, booking)` through `ctx.waitUntil` after the D1 write. ### Files - `src/worker/email.ts`: the `Sender` interface, `cloudflareSender`, `resendSender`, `logSender`, templates (text + HTML) per kind. - `src/shared/ics.ts`: `buildInvite` (R16) and `foldLine` / `escapeText`. - `src/shared/ical-parse.ts`: the iCal reader and recurrence expansion (R17), pure, with fixtures in `tests/fixtures/*.ics`. - `src/worker/google.ts`: OAuth, events insert/patch/delete, `freeBusy.query`. - `src/worker/cron.ts`: the scheduled handler. - Screens: `/settings/integrations` (status list) and `/settings/calendars` (iCal field with the Google Calendar instructions, Google connect and the setup walkthrough), as two more entries in the settings sub-menu. ### Tests - Unit: `tests/ics.test.ts` (R16 checks with a small parser), `tests/mime.test.ts` (R16 MIME structure with a small MIME parser), `tests/ical.test.ts` (R17 fixtures), `tests/email.test.ts` (templates, masking, dedupe with an in-memory D1 stand-in), `tests/crypto.test.ts` (round trip, wrong key fails). - E2E: `wrangler dev` with `EMAIL_PROVIDER` set to `test`, which records emails in a `test_outbox` table (recipient, reply_to, subject, text, html, ics, mime, created_at) readable at `GET /api/test/outbox` only when `TEST_CLOCK` is `"1"`; the iCal feed served from `GET /api/test/feed.ics` (also test-only); the scheduled handler triggered with `POST /api/test/scheduled?now=...` (test-only, runs the cron work at a given time); Google replaced by a fake under `/api/test/google/*` selected by `GOOGLE_API_BASE`. ## Demo data When `seed_demo` is true and the database is empty, the Worker creates this in one `batch()` on the first API request (a request that loses the race to seed sees the unique-email error and carries on): - User "Alex Rivera", email `alex@example.com`, password `demo-pass-123`, username `alex`, zone `America/New_York`, 12-hour, week starts Monday, bio "Product designer. Happy to talk shop." - Default schedule "Working hours", Mon-Fri 09:00-12:00 and 13:00-17:00, in `America/New_York`. - Event types: "Intro call" (`intro`, 30 minutes, video link `https://meet.example.com/alex`), "Deep dive" (`deep-dive`, 60 minutes, 10 minutes buffer after, needs approval), "Coffee" (`coffee`, 45 minutes, in person "Corner cafe, 5th Ave", hidden). Descriptions: Intro call: "A short first call to see how we can work together."; Deep dive: "An hour on one problem. I'll confirm the request."; Coffee: "Coffee and an open chat, in person." Colours respectively `#1d4ed8`, `#047857`, `#b45309` from the R4 swatches. - No bookings. The README lists these logins.