/** * Days' writes to Google Calendar (CONTRACT §16, 22 Nov 2026): the phone's * core sends one write in plain over its owner's door, this object hands it * to Google with the account's grant, and answers what Google answered. The * object cannot read a sealed event, so the words come from the phone; they * pass through here on their way out as the pull's pass through on their way * in, and nothing of them is kept, logged or said in an error. * * POST /v1/google/events (owner) * { account?, op: "insert" | "patch" | "delete", id?, gcalId?, etag?, * event?: { summary, description?, location?, start, end, recurrence?, * attendees?: [{ email, displayName? }] }, * notify: "all" | "none" } * * WHICH ACCOUNT. The one named, else the first connected that can write. A * named account that cannot write is refused `google_needs_write`; one whose * grant Google stopped honouring is refused `reconnect_required` without * asking Google again (its pass asks nothing either, src/google_calendar.ts). * * AN INSERT made with `id` (the Days row's own id, a UUID) asks Google for * that event id: the UUID's 32 hex digits, which Google's id alphabet * (base32hex) takes. So the pull finds the row by it before the phone has * written Google's id on it (src/google_calendar.ts `rowOf`), and an insert * asked again after its answer was lost is answered as the first, never made * twice and never mailed to its guests twice. * * ANSWERS. 200 with Google's id, etag and guests; 200 `{ account, changed: * true, event }` with Google's copy as `events.get` answers it when the etag * given no longer stands (Google's 412); 200 `{ account, gone: true }` for a * patch or delete of an event Google no longer holds. Both are 2xx because * the phone's transport keeps no refusal's body, and the core needs Google's * copy (coordinator, 22 Nov 2026). Refusals carry `{ code, message }`: 403 * `google_needs_write` for a read-only grant (the account then says so); * 403 `reconnect_required` for a grant Google no longer honours (the account * goes to `reconnect`); 403 `google_refused` when Google refuses this one * event for this account (an event someone else organises); 400 * `google_refused` for an event Google will not take as written; 503 * `google_unavailable` for a rate limit or an outage. */importtype { Env } from"./env.ts";import { googleUrls, readAccounts, saveAccount, typeAccount, typeGoogleHost } from"./google.ts";import { accessToken, Stop } from"./google_calendar.ts";import { json, readJson, refuse } from"./http.ts";typeOp = "insert" | "patch" | "delete";typeBody = Record<string, unknown>;/** A Google event id as Days sends it: Google's own, or one occurrence's `<id>_<stamp>`. */const GCAL_ID = /^[A-Za-z0-9_@.-]{1,1024}$/;const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;/** The Google event id an insert asks for a Days row: its UUID's hex digits. */exportfunction gcalIdOf(rowId: string): string {return rowId.toLowerCase().replace(/-/g, "");}/** The Days row id a Google id made by `gcalIdOf` names, or null for any other id. */exportfunction rowIdOf(gcalId: string): string | null {const m = /^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/.exec(gcalId);return m ? `${m[1]}-${m[2]}-${m[3]}-${m[4]}-${m[5]}` : null;}/** What each refusal says, in words a person may be shown; never the event's words. */const MESSAGES: Record<string, string> = { google_needs_write: "To save changes to Google Calendar, Days needs your permission once more.", reconnect_required: "Google stopped letting Days use this calendar. Connect it again.", google_unavailable: "Google Calendar did not answer. Days tries again later.", google_refused: "Google Calendar did not take this change.", not_connected: "No Google calendar is connected.",};/** A refusal as the contract says it: a code and its message, and never the event's words. */function said(status: number, code: string, extra: Body = {}): Response {return json({ code, message: MESSAGES[code] ?? code, ...extra }, status);}/** Google no longer holds the event: answered done, for the core to bin its row. */function gone(account: Account): Response {return json({ account: account.email, gone: true });}/** `POST /v1/google/events`: one write handed to Google. */exportasyncfunction events(host: GoogleHost, request: Request): Promise<Response> {const body = await readJson(request);const op = body.op === "insert" || body.op === "patch" || body.op === "delete" ? (body.op asOp) : refuse(400, "bad_request", "op: insert, patch or delete");const notify = body.notify === undefined ? "none" : body.notify === "all" || body.notify === "none" ? body.notify : refuse(400, "bad_request", "notify: all or none");let gcalId: string | null = null;if (op === "insert") {if (body.id !== undefined) gcalId = typeof body.id === "string" && UUID.test(body.id) ? gcalIdOf(body.id) : refuse(400, "bad_request", "id: the Days row's id, a UUID"); } else { gcalId = typeof body.gcalId === "string" && GCAL_ID.test(body.gcalId) ? body.gcalId : refuse(400, "bad_request", "gcalId: Google's id for the event"); }const etag = body.etag === undefined || body.etag === null ? null : typeof body.etag === "string" && body.etag.length <= 256 ? body.etag : refuse(400, "bad_request", "etag: Google's etag as the pull kept it");const event = op === "delete" ? null : eventOf(body.event, op);const chosen = choose(host, body.account);if (chosen instanceofResponse) return chosen;const account = chosen;let token: string;try { token = await accessToken(host, account); } catch (error) {return stopped(host, account, error); }const q = new URLSearchParams({ sendUpdates: notify });const base = `${googleUrls(host.env).calendar}/calendars/primary/events`;const headers: Record<string, string> = { authorization: `Bearer ${token}` };if (etag && op !== "insert") headers["if-match"] = etag;let res: Response;try {if (op === "insert") { res = await fetch(`${base}?${q}`, { method: "POST", headers: { ...headers, "content-type": "application/json" }, body: JSON.stringify(gcalId ? { ...event, id: gcalId } : event) }); } elseif (op === "patch") { res = await fetch(`${base}/${encodeURIComponent(gcalId!)}?${q}`, { method: "PATCH", headers: { ...headers, "content-type": "application/json" }, body: JSON.stringify(event) }); } else { res = await fetch(`${base}/${encodeURIComponent(gcalId!)}?${q}`, { method: "DELETE", headers }); } } catch {return said(503, "google_unavailable"); }if (res.ok) {if (op === "delete") return json({ account: account.email, gcalId, deleted: true });return json(done(account, (await res.json().catch(() => ({}))) asBody)); }const why = await reasonOf(res);if (res.status === 412) return changed(host.env, account, token, gcalId!);if (res.status === 404 || res.status === 410) return op === "insert" ? said(400, "google_refused") : gone(account);if (res.status === 409 && op === "insert" && gcalId) {// An insert asked again (its answer was lost): Google holds the event by the id this object gave it, answered as the first.const held = awaitget(host.env, token, gcalId);if (held === "unavailable") return said(503, "google_unavailable");if (held === "gone" || held.status === "cancelled") return gone(account);return json(done(account, held)); }return refused(host, account, res.status, why);}/** The account a write goes through, or the refusal that says why none can take it. */function choose(host: GoogleHost, named: unknown): Account | Response {const accounts = readAccounts(host.store);if (named !== undefined && named !== null) {const email = typeof named === "string" ? named.trim().toLowerCase() : refuse(400, "bad_request", "account: the Google address");const account = accounts.find((a) => a.email === email);if (!account) return said(404, "not_connected");if (account.phase === "reconnect") return said(403, "reconnect_required");if (account.can_write !== true) return said(403, "google_needs_write");return account; }const writable = accounts.filter((a) => a.can_write === true);const live = writable.find((a) => a.phase !== "reconnect");if (live) return live;if (writable.length) return said(403, "reconnect_required");if (accounts.length) return said(403, "google_needs_write");return said(404, "not_connected");}/** The event's fields Google takes from Days, and nothing else; each checked for its shape, never for its words. */function eventOf(raw: unknown, op: Op): Body {if (!raw || typeof raw !== "object" || Array.isArray(raw)) refuse(400, "bad_request", "event: the event as Google takes it");const e = raw asBody;const out: Body = {};for (const k of ["summary", "description", "location"] asconst) {if (e[k] === undefined) continue;if (e[k] !== null && typeof e[k] !== "string") refuse(400, "bad_request", `event.${k}: words`); out[k] = e[k]; }for (const k of ["start", "end"] asconst) {if (e[k] === undefined) continue; out[k] = momentOf(e[k], k); }if (op === "insert" && (!out.start || !out.end)) refuse(400, "bad_request", "event.start and event.end: an insert names both");if (e.recurrence !== undefined) {if (!Array.isArray(e.recurrence) || e.recurrence.length > 50 || !e.recurrence.every((l) => typeof l === "string" && /^(RRULE|EXRULE|RDATE|EXDATE)[:;]/.test(l))) refuse(400, "bad_request", "event.recurrence: RRULE, RDATE and EXDATE lines"); out.recurrence = e.recurrence; }if (e.attendees !== undefined) {if (!Array.isArray(e.attendees) || e.attendees.length > 200) refuse(400, "bad_request", "event.attendees: at most 200 guests"); out.attendees = (e.attendees as unknown[]).map((a) => {const g = a asBody;if (!g || typeof g.email !== "string" || !/^[^\s@]+@[^\s@]+$/.test(g.email.trim())) refuse(400, "bad_request", "event.attendees: each { email, displayName? }");return { email: g.email.trim(), ...(typeof g.displayName === "string" && g.displayName.trim() ? { displayName: g.displayName.trim() } : {}) }; }); }return out;}function momentOf(raw: unknown, what: string): Body {const m = raw asBody;if (m && typeof m === "object" && typeof m.date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(m.date)) return { date: m.date };if (m && typeof m === "object" && typeof m.dateTime === "string" && !Number.isNaN(Date.parse(m.dateTime))) {if (m.timeZone !== undefined && (typeof m.timeZone !== "string" || !/^[A-Za-z_]+(\/[A-Za-z0-9_+-]+)*$/.test(m.timeZone))) refuse(400, "bad_request", `event.${what}.timeZone: an IANA zone`);return { dateTime: m.dateTime, ...(m.timeZone ? { timeZone: m.timeZone } : {}) }; } refuse(400, "bad_request", `event.${what}: { dateTime, timeZone } or { date }`);}/** What a write that landed answers: Google's id, its new etag and its guests as Google holds them. */function done(account: Account, r: Body): Body {return { account: account.email, gcalId: r.id, etag: r.etag ?? null, attendees: guestsOf(r.attendees) };}/** Google's guests, the fields Days reads. */exportfunction guestsOf(raw: unknown): Body[] {if (!Array.isArray(raw)) return [];return (raw asBody[]).flatMap((a) => a && typeof a.email === "string" ? [{ email: a.email, ...(typeof a.displayName === "string" ? { displayName: a.displayName } : {}), responseStatus: typeof a.responseStatus === "string" ? a.responseStatus : "needsAction", ...(a.self === true ? { self: true } : {}), ...(a.organizer === true ? { organizer: true } : {}) }] : [], );}/** Google's copy of one event, as `events.get` answers it. */asyncfunctionget(env: Env, token: string, gcalId: string): Promise<Body | "gone" | "unavailable"> {try {const res = await fetch(`${googleUrls(env).calendar}/calendars/primary/events/${encodeURIComponent(gcalId)}`, { headers: { authorization: `Bearer ${token}` } });if (res.ok) return (await res.json()) asBody;if (res.status === 404 || res.status === 410) return"gone";return"unavailable"; } catch {return"unavailable"; }}/** Google changed the event after the etag Days holds: its copy, for the core to keep (Google's wins), or gone. */asyncfunction changed(env: Env, account: Account, token: string, gcalId: string): Promise<Response> {const held = awaitget(env, token, gcalId);if (held === "unavailable") return said(503, "google_unavailable");if (held === "gone" || held.status === "cancelled") return gone(account);return json({ account: account.email, changed: true, event: held });}/** Google's reason for a refusal (`error.errors[0].reason`), never its message: a message may quote the event. */asyncfunction reasonOf(res: Response): Promise<string> {const body = (await res.json().catch(() => ({}))) as { error?: { errors?: { reason?: string }[] } };return body.error?.errors?.[0]?.reason ?? "";}/** A refusal from Google other than a conflict or a gone event. */function refused(host: GoogleHost, account: Account, status: number, reason: string): Response {if (status === 401) return stopped(host, account, newStop("reconnect_required", `Google Calendar answered ${status}: connect Google again`, true));if (status === 429 || status >= 500 || reason === "rateLimitExceeded" || reason === "userRateLimitExceeded" || reason === "quotaExceeded") return said(503, "google_unavailable");if (status === 403 && (reason === "insufficientPermissions" || reason === "ACCESS_TOKEN_SCOPE_INSUFFICIENT")) {// Google says the grant cannot write: the account says so from now on, until the person connects again. host.write(() => {const now = readAccounts(host.store).find((a) => a.email === account.email);if (now) saveAccount(host.store, { ...now, can_write: false }); });return said(403, "google_needs_write"); }if (status === 403) return said(403, "google_refused", { reason });return said(400, "google_refused", { reason });}/** A grant that would not open or that Google no longer honours: the account to `reconnect`, said once. */function stopped(host: GoogleHost, account: Account, error: unknown): Response {if (!(error instanceofStop) || !error.reconnect) return said(503, "google_unavailable");const at = newDate().toISOString(); host.write(() => {const now = readAccounts(host.store).find((a) => a.email === account.email);if (now) saveAccount(host.store, { ...now, phase: "reconnect", last_error: { code: error.code, message: error.message, at } }); });return said(403, "reconnect_required");}