@davidwoods/skylight-mcp 1.22.0 → 1.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,625 @@
1
+ /**
2
+ * Event writes for the library entry (experimental). Stage 1: create a one-off event.
3
+ *
4
+ * Every write is two functions with identical arguments: a preview that changes nothing and a
5
+ * commit. Both call the same plan function, so the checks cannot drift: the commit re-runs
6
+ * every check against fresh reads (the calendar can change between the two calls), then writes,
7
+ * then reads back.
8
+ *
9
+ * Errors for input and for the write itself are plain Errors with `name` "SkylightWriteError"
10
+ * and a stable `code`. Their messages are the library's own wording: Skylight's response text is
11
+ * never included (the HTTP client puts it in its own error messages, so every write error is
12
+ * mapped here). Sign-in errors pass through unchanged (`AuthenticationError`).
13
+ *
14
+ * Nothing here returns a calendar address, an account id or an email: the Google calendar is
15
+ * chosen by its `calendar.sources()` id and resolved inside the call.
16
+ */
17
+ import { getClient } from "./api/client.js";
18
+ import { getCalendarEvents, createCalendarEvent, deleteCalendarEvent, updateCalendarEvent } from "./api/endpoints/calendar.js";
19
+ import { getCategories } from "./api/endpoints/categories.js";
20
+ import { isoWithOffset } from "./api/endpoints/messages.js";
21
+ import { readBackUntil } from "./api/endpoints/source-calendars.js";
22
+ import { addDays, dateInZone, toLocalParts, zonedToEpoch } from "./utils/schedule.js";
23
+ import { planSeries, SeriesError } from "./utils/series.js";
24
+ export function writeError(code, message, extra = {}) {
25
+ const e = new Error(message);
26
+ e.name = "SkylightWriteError";
27
+ e.code = code;
28
+ if (extra.status !== undefined)
29
+ e.status = extra.status;
30
+ if (extra.eventId !== undefined)
31
+ e.eventId = extra.eventId;
32
+ if (extra.ids !== undefined)
33
+ e.ids = extra.ids;
34
+ return e;
35
+ }
36
+ const CREATE_KEYS = new Set(["title", "start", "end", "allDay", "location", "notes", "profileIds", "labelIds", "calendar", "repeat"]);
37
+ const TITLE_MAX = 200;
38
+ const LOCATION_MAX = 500;
39
+ const NOTES_MAX = 5000;
40
+ const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
41
+ const LOCAL_TIME = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2})$/;
42
+ const ID = /^\d+$/;
43
+ // Control characters other than tab and newline (notes may have line breaks; a title may not).
44
+ // eslint-disable-next-line no-control-regex -- matching control characters is the point
45
+ const CONTROL = /[\u0000-\u0008\u000B-\u001F\u007F]/;
46
+ const EMAIL = /[^\s@<>()"',;:]+@[^\s@<>()"',;:]+\.[^\s@<>()"',;:]+/;
47
+ function realDate(value) {
48
+ const m = DATE.exec(value);
49
+ if (!m)
50
+ return false;
51
+ const t = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
52
+ return new Date(t).toISOString().slice(0, 10) === value;
53
+ }
54
+ /** Epoch ms for a wall-clock time, refusing a time the zone skips (a clock change). */
55
+ function localToEpoch(value, timeZone, field) {
56
+ const m = LOCAL_TIME.exec(value);
57
+ if (!m || !realDate(m[1]) || Number(m[2]) > 23 || Number(m[3]) > 59) {
58
+ throw writeError("invalid_time", `${field} must be a local time YYYY-MM-DDTHH:MM, with no offset or Z.`);
59
+ }
60
+ const epoch = zonedToEpoch(m[1], `${m[2]}:${m[3]}`, timeZone);
61
+ const p = toLocalParts(epoch, timeZone);
62
+ if (dateInZone(epoch, timeZone) !== m[1] || p.hour !== Number(m[2]) || p.minute !== Number(m[3])) {
63
+ throw writeError("invalid_time", `${field} does not exist in ${timeZone} (the clocks change at that time).`);
64
+ }
65
+ return epoch;
66
+ }
67
+ function optionalText(value, field, max) {
68
+ if (value === undefined)
69
+ return null;
70
+ if (typeof value !== "string")
71
+ throw writeError("bad_input", `${field} must be text.`);
72
+ if (CONTROL.test(value))
73
+ throw writeError("bad_input", `${field} contains control characters.`);
74
+ if (value.length > max)
75
+ throw writeError("bad_input", `${field} is longer than ${max} characters.`);
76
+ return value.trim() === "" ? null : value;
77
+ }
78
+ function idList(value, field) {
79
+ if (value === undefined)
80
+ return [];
81
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string" && ID.test(v))) {
82
+ throw writeError("bad_input", `${field} must be a list of ids (digits), from the library's lists.`);
83
+ }
84
+ if (new Set(value).size !== value.length)
85
+ throw writeError("bad_input", `${field} lists an id twice.`);
86
+ return [...value];
87
+ }
88
+ /** Source calendars with their account link. The included account records hold an email and are never read here. */
89
+ async function sourcesWithAccounts() {
90
+ const response = await getClient().get("/api/frames/{frameId}/source_calendars", { include: "calendar_account" });
91
+ return response.data ?? [];
92
+ }
93
+ /** True when the library can create on this source: a Google calendar this account can write to. */
94
+ export function sourceWritable(cal) {
95
+ const a = cal.attributes;
96
+ return a.kind === "gmail" && a.editable !== false && a.role !== "reader";
97
+ }
98
+ /** The one check behind previewCreate and create. Reads categories and calendars fresh every time. */
99
+ export async function planCreate(input, timeZone) {
100
+ if (!input || typeof input !== "object" || Array.isArray(input))
101
+ throw writeError("bad_input", "create needs an object of event fields.");
102
+ const raw = input;
103
+ for (const key of Object.keys(raw)) {
104
+ if (!CREATE_KEYS.has(key))
105
+ throw writeError("bad_input", `Unknown field "${key}".`);
106
+ }
107
+ if (typeof raw.title !== "string" || raw.title.trim() === "")
108
+ throw writeError("invalid_title", "title must be non-empty text.");
109
+ const title = raw.title.trim();
110
+ if (title.length > TITLE_MAX)
111
+ throw writeError("invalid_title", `title is longer than ${TITLE_MAX} characters.`);
112
+ if (/[\r\n]/.test(title) || CONTROL.test(title))
113
+ throw writeError("invalid_title", "title must be one line with no control characters.");
114
+ if (raw.allDay !== undefined && typeof raw.allDay !== "boolean")
115
+ throw writeError("bad_input", "allDay must be true or false.");
116
+ const allDay = raw.allDay === true;
117
+ if (typeof raw.start !== "string")
118
+ throw writeError("invalid_time", "start is required.");
119
+ if (raw.end !== undefined && typeof raw.end !== "string")
120
+ throw writeError("invalid_time", "end must be text.");
121
+ let startSent;
122
+ let endSent;
123
+ let startDate;
124
+ let endDate;
125
+ let startMs;
126
+ let endMs;
127
+ if (allDay) {
128
+ if (!realDate(raw.start))
129
+ throw writeError("invalid_time", "For an all-day event start must be a date, YYYY-MM-DD.");
130
+ if (raw.end !== undefined && !realDate(raw.end))
131
+ throw writeError("invalid_time", "For an all-day event end must be a date, YYYY-MM-DD, or left out.");
132
+ if (raw.end !== undefined && raw.end < raw.start)
133
+ throw writeError("end_before_start", "end is before start.");
134
+ if (raw.end !== undefined && raw.end !== raw.start) {
135
+ throw writeError("unsupported", "An all-day event covers one day: leave end out or give the same date. Multi-day all-day events are not supported yet.");
136
+ }
137
+ startDate = raw.start;
138
+ endDate = raw.start;
139
+ startSent = raw.start;
140
+ endSent = addDays(raw.start, 1); // Skylight's all-day end is the next day (exclusive), as the app sends it
141
+ startMs = zonedToEpoch(startDate, "00:00", timeZone);
142
+ endMs = zonedToEpoch(endSent, "00:00", timeZone);
143
+ }
144
+ else {
145
+ if (raw.end === undefined)
146
+ throw writeError("invalid_time", "end is required for a timed event.");
147
+ startMs = localToEpoch(raw.start, timeZone, "start");
148
+ endMs = localToEpoch(raw.end, timeZone, "end");
149
+ if (endMs <= startMs)
150
+ throw writeError("end_before_start", "end must be after start.");
151
+ startSent = isoWithOffset(startMs, timeZone);
152
+ endSent = isoWithOffset(endMs, timeZone);
153
+ startDate = dateInZone(startMs, timeZone);
154
+ endDate = dateInZone(endMs - 1, timeZone);
155
+ }
156
+ const location = optionalText(raw.location, "location", LOCATION_MAX);
157
+ const notes = optionalText(raw.notes, "notes", NOTES_MAX);
158
+ const profileIds = idList(raw.profileIds, "profileIds");
159
+ const labelIds = idList(raw.labelIds, "labelIds");
160
+ let series = null;
161
+ if (raw.repeat !== undefined) {
162
+ const startTime = allDay ? "00:00" : `${String(toLocalParts(startMs, timeZone).hour).padStart(2, "0")}:${String(toLocalParts(startMs, timeZone).minute).padStart(2, "0")}`;
163
+ try {
164
+ series = planSeries(raw.repeat, startDate, startTime, timeZone);
165
+ }
166
+ catch (error) {
167
+ if (error instanceof SeriesError)
168
+ throw writeError("invalid_repeat", error.message);
169
+ throw error;
170
+ }
171
+ }
172
+ if (typeof raw.calendar !== "string" || (raw.calendar !== "skylight" && !ID.test(raw.calendar))) {
173
+ throw writeError("bad_input", 'calendar is required: "skylight", or the id of a Google calendar from calendar.sources().');
174
+ }
175
+ // Fresh reads: a profile, label or calendar removed a minute ago must not be written to.
176
+ const categories = await getCategories(false);
177
+ const byId = new Map(categories.map((c) => [String(c.id), c]));
178
+ const name = (c) => {
179
+ const label = typeof c.attributes.label === "string" ? c.attributes.label : "";
180
+ return EMAIL.test(label) ? "Calendar" : label;
181
+ };
182
+ const badProfiles = profileIds.filter((id) => byId.get(id)?.attributes.linked_to_profile !== true);
183
+ if (badProfiles.length)
184
+ throw writeError("unknown_profile", "Not a profile on this frame: see profiles.list().", { ids: badProfiles });
185
+ const unknownLabels = labelIds.filter((id) => {
186
+ const c = byId.get(id);
187
+ return !c || c.attributes.linked_to_profile === true;
188
+ });
189
+ if (unknownLabels.length)
190
+ throw writeError("unknown_label", "Not a label on this frame: see labels.list().", { ids: unknownLabels });
191
+ const fedLabels = labelIds.filter((id) => (byId.get(id)?.relationships?.source_calendars?.data ?? []).length > 0);
192
+ if (fedLabels.length) {
193
+ throw writeError("label_not_assignable", "A synced calendar writes to this label; Skylight assigns it to that calendar's events itself.", { ids: fedLabels });
194
+ }
195
+ let target = null;
196
+ if (raw.calendar !== "skylight") {
197
+ const cal = (await sourcesWithAccounts()).find((c) => String(c.id) === raw.calendar);
198
+ if (!cal)
199
+ throw writeError("unknown_calendar", "No synced calendar with that id: see calendar.sources().");
200
+ const a = cal.attributes;
201
+ if (!sourceWritable(cal))
202
+ throw writeError("calendar_not_writable", "That calendar is not a Google calendar this account can write to.");
203
+ const sourceId = typeof a.source_id === "string" ? a.source_id : "";
204
+ const account = cal.relationships?.calendar_account?.data?.id;
205
+ if (!sourceId || !((typeof account === "string" && account !== "") || typeof account === "number")) {
206
+ throw writeError("calendar_not_writable", "Skylight did not report that calendar's account, so it cannot be written to.");
207
+ }
208
+ const label = typeof a.label === "string" && !EMAIL.test(a.label) ? a.label : "Google calendar";
209
+ target = { calendarId: sourceId, accountId: account, label, id: String(cal.id) };
210
+ }
211
+ const categoryIds = [...profileIds, ...labelIds];
212
+ const body = {
213
+ summary: title,
214
+ kind: "standard",
215
+ starts_at: startSent,
216
+ ends_at: endSent,
217
+ all_day: allDay,
218
+ timezone: timeZone,
219
+ description: notes ?? "",
220
+ location: location ?? "",
221
+ category_ids: categoryIds,
222
+ ...(series ? { rrule: [series.rrule] } : {}),
223
+ ...(target ? { calendar_id: target.calendarId, calendar_account_id: target.accountId } : {}),
224
+ };
225
+ const preview = {
226
+ action: "create",
227
+ title,
228
+ start: startSent,
229
+ end: endSent,
230
+ allDay,
231
+ location,
232
+ notes,
233
+ profileIds,
234
+ profiles: profileIds.map((id) => name(byId.get(id))),
235
+ labelIds,
236
+ labels: labelIds.map((id) => name(byId.get(id))),
237
+ calendar: target ? { id: target.id, label: target.label, kind: "google" } : { id: "skylight", label: "Skylight", kind: "skylight" },
238
+ timezone: timeZone,
239
+ repeat: series ? { rule: series.rule, first: series.first, skipped: series.skipped, last: series.last } : null,
240
+ warnings: series ? [...series.warnings] : [],
241
+ };
242
+ const freq = series ? /FREQ=([A-Z]+)/.exec(series.rrule)[1] : null;
243
+ return { preview, body, startDate, endDate, startMs, endMs, categoryIds, source: target ? "google" : "skylight", freq };
244
+ }
245
+ /** Map anything the write itself threw to the library's own error, never Skylight's text. Sign-in errors pass through. */
246
+ function mapWriteFailure(error) {
247
+ const e = error;
248
+ if (e && (e.name === "AuthenticationError" || e.name === "CredentialSaveError"))
249
+ return error;
250
+ const status = typeof e?.statusCode === "number" ? e.statusCode : undefined;
251
+ if (status !== undefined && status >= 400 && status < 500) {
252
+ return writeError("skylight_refused", `Skylight refused the write (HTTP ${status}). Nothing was written.`, { status });
253
+ }
254
+ return writeError("outcome_unknown", "The write was sent but no answer came back (a network error or a Skylight server error). It may or may not have been written: read the calendar before trying again.");
255
+ }
256
+ function sameText(stored, wanted) {
257
+ const s = typeof stored === "string" ? stored : "";
258
+ return s.trim() === (wanted ?? "").trim();
259
+ }
260
+ /** Did Skylight store what was asked? Profiles and labels asked for must all be there; Skylight may add the calendar's own label. */
261
+ function matchesPlan(event, plan, categoryIdsOf) {
262
+ const a = event.attributes;
263
+ if (a.summary !== plan.preview.title)
264
+ return false;
265
+ if ((a.all_day === true) !== plan.preview.allDay)
266
+ return false;
267
+ if (Date.parse(String(a.starts_at)) !== plan.startMs || Date.parse(String(a.ends_at)) !== plan.endMs) {
268
+ // All-day records come back as local midnights with an offset; timed ones as instants. Both are compared as instants.
269
+ return false;
270
+ }
271
+ if (!sameText(a.location, plan.preview.location) || !sameText(a.description, plan.preview.notes))
272
+ return false;
273
+ if (a.source !== plan.source)
274
+ return false;
275
+ if (plan.freq !== null) {
276
+ const rule = Array.isArray(a.rrule) ? a.rrule.join(";") : "";
277
+ if (a.recurring !== true || !rule.includes(`FREQ=${plan.freq}`))
278
+ return false;
279
+ }
280
+ else if (a.recurring === true)
281
+ return false;
282
+ const stored = new Set(categoryIdsOf(event));
283
+ return plan.categoryIds.every((id) => stored.has(id));
284
+ }
285
+ /**
286
+ * Create, then read back. Returns the stored record only when the read-back shows every field as
287
+ * asked; otherwise throws `not_confirmed` with the id Skylight gave (the event may still appear:
288
+ * Skylight's list can lag a write).
289
+ */
290
+ export async function commitCreate(input, timeZone, categoryIdsOf) {
291
+ const plan = await planCreate(input, timeZone);
292
+ let created;
293
+ try {
294
+ created = await createCalendarEvent(plan.body);
295
+ }
296
+ catch (error) {
297
+ throw mapWriteFailure(error);
298
+ }
299
+ const id = created?.id !== undefined && created?.id !== null ? String(created.id) : "";
300
+ if (!id)
301
+ throw writeError("outcome_unknown", "Skylight accepted the write but did not say which event it created. Read the calendar before trying again.");
302
+ const back = await readBackUntil(() => getCalendarEvents({ dateMin: plan.startDate, dateMax: plan.endDate, timezone: timeZone }), (list) => list.some((e) => String(e.id) === id && matchesPlan(e, plan, categoryIdsOf)));
303
+ const stored = back.value.find((e) => String(e.id) === id);
304
+ if (!back.ok || !stored) {
305
+ throw writeError("not_confirmed", stored
306
+ ? "Skylight created the event but reading it back shows different fields from those asked. Read it before changing it."
307
+ : "Skylight accepted the write but the event did not show on reading it back. It may still appear: read the calendar before trying again.", { eventId: id });
308
+ }
309
+ return stored;
310
+ }
311
+ // ---------------------------------------------------------------------------------------------
312
+ // Stage 2: update and delete. An event is named by what a read returned: its id, the date it was
313
+ // read on, and its version (a fingerprint of the fields shown). The commit reads the event again
314
+ // and refuses if the version moved, so an edit made from an old screen is refused, not applied.
315
+ // Skylight has no conditional write, so a change landing between that re-read and the write is
316
+ // not caught.
317
+ // ---------------------------------------------------------------------------------------------
318
+ /** FNV-1a, twice with different seeds: a stable 16-hex fingerprint with no crypto (runs in Workers). */
319
+ function fnv(text, seed) {
320
+ let h = seed >>> 0;
321
+ for (let i = 0; i < text.length; i++) {
322
+ h ^= text.charCodeAt(i);
323
+ h = Math.imul(h, 0x01000193) >>> 0;
324
+ }
325
+ return h.toString(16).padStart(8, "0");
326
+ }
327
+ /** The version of an event as read: changes when its title, times, all-day, location, notes, people, labels or rule change. */
328
+ export function eventVersion(event, categoryIdsOf) {
329
+ const a = event.attributes;
330
+ const text = JSON.stringify([
331
+ String(event.id),
332
+ typeof a.summary === "string" ? a.summary : "",
333
+ Date.parse(String(a.starts_at)),
334
+ Date.parse(String(a.ends_at)),
335
+ a.all_day === true,
336
+ typeof a.location === "string" ? a.location.trim() : "",
337
+ typeof a.description === "string" ? a.description.trim() : "",
338
+ [...categoryIdsOf(event)].sort(),
339
+ Array.isArray(a.rrule) ? a.rrule.join("|") : "",
340
+ a.master_event_id == null ? "" : String(a.master_event_id),
341
+ ]);
342
+ return fnv(text, 0x811c9dc5) + fnv(text, 0x9747b28c);
343
+ }
344
+ const REF_KEYS = ["id", "date", "version"];
345
+ const UPDATE_KEYS = new Set([...REF_KEYS, "scope", "changes"]);
346
+ const DELETE_KEYS = new Set([...REF_KEYS, "scope"]);
347
+ const CHANGE_KEYS = new Set(["title", "start", "end", "allDay", "location", "notes", "profileIds", "labelIds"]);
348
+ const EVENT_ID = /^\d+(-\d+)?$/;
349
+ /** Read the event fresh and check it is the one the caller saw and that Skylight can change it. */
350
+ async function findForWrite(raw, keys, timeZone, categoryIdsOf, verb) {
351
+ for (const key of Object.keys(raw))
352
+ if (!keys.has(key))
353
+ throw writeError("bad_input", `Unknown field "${key}".`);
354
+ if (typeof raw.id !== "string" || !EVENT_ID.test(raw.id))
355
+ throw writeError("bad_input", "id must be an event id from calendar.events().");
356
+ if (typeof raw.date !== "string" || !realDate(raw.date))
357
+ throw writeError("bad_input", "date must be the event's date, YYYY-MM-DD, as read.");
358
+ if (typeof raw.version !== "string" || raw.version === "")
359
+ throw writeError("bad_input", "version is required: pass the event's version from calendar.events().");
360
+ const list = await getCalendarEvents({ dateMin: raw.date, dateMax: raw.date, timezone: timeZone });
361
+ const event = list.find((e) => String(e.id) === raw.id);
362
+ if (!event)
363
+ throw writeError("not_found", `No event with that id on ${raw.date}: it may have moved or been deleted. Read the calendar again.`);
364
+ if (eventVersion(event, categoryIdsOf) !== raw.version) {
365
+ throw writeError("stale", `The event changed since it was read. Nothing was ${verb}: read it again and show the new version before asking again.`);
366
+ }
367
+ const a = event.attributes;
368
+ if (a.source !== "skylight" && a.source !== "google")
369
+ throw writeError("not_editable", "That event comes from a subscribed calendar, which is read-only.");
370
+ if (a.editable === false)
371
+ throw writeError("not_editable", "Skylight marks that event as not editable.");
372
+ const detached = a.master_event_id != null && a.master_event_id !== "";
373
+ const series = !detached && (a.recurring === true || a.recurring_config === true);
374
+ return { event, kind: detached ? "detached" : series ? "series" : "one-off", google: a.source === "google" };
375
+ }
376
+ function seriesKeyOf(event) {
377
+ const a = event.attributes;
378
+ return { uid: typeof a.uid === "string" ? a.uid : "", number: String(event.id).split("-")[0] };
379
+ }
380
+ /** The one check behind previewUpdate and update. */
381
+ export async function planUpdate(input, timeZone, categoryIdsOf) {
382
+ if (!input || typeof input !== "object" || Array.isArray(input))
383
+ throw writeError("bad_input", "update needs an object: id, date, version, changes.");
384
+ const raw = input;
385
+ const changesRaw = raw.changes;
386
+ if (!changesRaw || typeof changesRaw !== "object" || Array.isArray(changesRaw))
387
+ throw writeError("bad_input", "changes must be an object of the fields to change.");
388
+ const c = changesRaw;
389
+ for (const key of Object.keys(c))
390
+ if (!CHANGE_KEYS.has(key))
391
+ throw writeError("bad_input", `Unknown change "${key}".`);
392
+ if (Object.keys(c).length === 0)
393
+ throw writeError("bad_input", "Nothing to change.");
394
+ if (raw.scope !== undefined && raw.scope !== "one" && raw.scope !== "all") {
395
+ throw writeError("scope_not_allowed", raw.scope === "future" ? 'Skylight refuses "this and following" for an edit: use "one" or "all".' : 'scope must be "one" or "all".');
396
+ }
397
+ const found = await findForWrite(raw, UPDATE_KEYS, timeZone, categoryIdsOf, "changed");
398
+ const a = found.event.attributes;
399
+ const scope = raw.scope ?? null;
400
+ if (found.kind === "series" && scope === null)
401
+ throw writeError("scope_required", 'That is an occurrence of a repeating event: say scope "one" (only this one) or "all" (the whole series).');
402
+ if (found.kind !== "series" && scope !== null)
403
+ throw writeError("scope_not_allowed", "scope applies to an occurrence of a repeating event only.");
404
+ if (found.kind === "series") {
405
+ const bad = ["allDay", "location", "notes"].filter((k) => c[k] !== undefined);
406
+ if (bad.length)
407
+ throw writeError("unsupported", `On a repeating event only the title, people, labels and time of day can be changed here (${bad.join(", ")} on a series is not verified).`);
408
+ if ((c.start === undefined) !== (c.end === undefined))
409
+ throw writeError("invalid_time", "To change a repeating event's time give both start and end.");
410
+ }
411
+ const changes = {};
412
+ const body = {};
413
+ const expect = { categoryIds: [], readDates: [raw.date] };
414
+ if (c.title !== undefined) {
415
+ if (typeof c.title !== "string" || c.title.trim() === "")
416
+ throw writeError("invalid_title", "title must be non-empty text.");
417
+ const title = c.title.trim();
418
+ if (title.length > TITLE_MAX)
419
+ throw writeError("invalid_title", `title is longer than ${TITLE_MAX} characters.`);
420
+ if (/[\r\n]/.test(title) || CONTROL.test(title))
421
+ throw writeError("invalid_title", "title must be one line with no control characters.");
422
+ changes.title = title;
423
+ body.summary = title;
424
+ expect.title = title;
425
+ }
426
+ const wasAllDay = a.all_day === true;
427
+ if (c.allDay !== undefined && typeof c.allDay !== "boolean")
428
+ throw writeError("bad_input", "allDay must be true or false.");
429
+ const allDay = c.allDay === undefined ? wasAllDay : c.allDay;
430
+ if (c.allDay !== undefined && c.allDay !== wasAllDay && (c.start === undefined)) {
431
+ throw writeError("invalid_time", "Changing all-day needs a new start (and end for a timed event).");
432
+ }
433
+ if (c.start !== undefined || c.end !== undefined) {
434
+ if (c.start !== undefined && typeof c.start !== "string")
435
+ throw writeError("invalid_time", "start must be text.");
436
+ if (c.end !== undefined && typeof c.end !== "string")
437
+ throw writeError("invalid_time", "end must be text.");
438
+ let startMs;
439
+ let endMs;
440
+ if (allDay) {
441
+ const day = c.start ?? dateInZone(Date.parse(String(a.starts_at)), timeZone);
442
+ if (!realDate(day))
443
+ throw writeError("invalid_time", "For an all-day event start must be a date, YYYY-MM-DD.");
444
+ if (c.end !== undefined && c.end !== day)
445
+ throw writeError("unsupported", "An all-day event covers one day: leave end out or give the same date.");
446
+ startMs = zonedToEpoch(day, "00:00", timeZone);
447
+ endMs = zonedToEpoch(addDays(day, 1), "00:00", timeZone);
448
+ body.starts_at = day;
449
+ body.ends_at = addDays(day, 1);
450
+ changes.start = day;
451
+ changes.end = addDays(day, 1);
452
+ expect.readDates.push(day);
453
+ }
454
+ else {
455
+ startMs = c.start !== undefined ? localToEpoch(c.start, timeZone, "start") : Date.parse(String(a.starts_at));
456
+ endMs = c.end !== undefined ? localToEpoch(c.end, timeZone, "end") : Date.parse(String(a.ends_at));
457
+ if (endMs <= startMs)
458
+ throw writeError("end_before_start", "end must be after start.");
459
+ if (found.kind === "series" && (dateInZone(startMs, timeZone) !== raw.date || dateInZone(endMs - 1, timeZone) !== raw.date)) {
460
+ throw writeError("unsupported", `A time change on a repeating event keeps its date (${raw.date}): only the time of day changes.`);
461
+ }
462
+ body.starts_at = isoWithOffset(startMs, timeZone);
463
+ body.ends_at = isoWithOffset(endMs, timeZone);
464
+ changes.start = body.starts_at;
465
+ changes.end = body.ends_at;
466
+ expect.readDates.push(dateInZone(startMs, timeZone));
467
+ }
468
+ if (found.kind === "series")
469
+ body.timezone = timeZone;
470
+ expect.startMs = startMs;
471
+ expect.endMs = endMs;
472
+ }
473
+ if (c.allDay !== undefined) {
474
+ body.all_day = allDay;
475
+ changes.allDay = allDay;
476
+ expect.allDay = allDay;
477
+ }
478
+ if (c.location !== undefined) {
479
+ const v = optionalText(c.location, "location", LOCATION_MAX);
480
+ body.location = v ?? "";
481
+ changes.location = v;
482
+ expect.location = v;
483
+ }
484
+ if (c.notes !== undefined) {
485
+ const v = optionalText(c.notes, "notes", NOTES_MAX);
486
+ body.description = v ?? "";
487
+ changes.notes = v;
488
+ expect.notes = v;
489
+ }
490
+ // People and labels: the app re-sends the whole set with every edit. Keep what is not being changed,
491
+ // including the label Skylight puts on a Google calendar's events.
492
+ const categories = await getCategories(false);
493
+ const byId = new Map(categories.map((x) => [String(x.id), x]));
494
+ const current = categoryIdsOf(found.event);
495
+ const currentProfiles = current.filter((id) => byId.get(id)?.attributes.linked_to_profile === true);
496
+ const currentLabels = current.filter((id) => byId.get(id)?.attributes.linked_to_profile !== true);
497
+ let profiles = currentProfiles;
498
+ let labels = currentLabels;
499
+ if (c.profileIds !== undefined) {
500
+ profiles = idList(c.profileIds, "profileIds");
501
+ const bad = profiles.filter((id) => byId.get(id)?.attributes.linked_to_profile !== true);
502
+ if (bad.length)
503
+ throw writeError("unknown_profile", "Not a profile on this frame: see profiles.list().", { ids: bad });
504
+ changes.profileIds = profiles;
505
+ }
506
+ if (c.labelIds !== undefined) {
507
+ labels = idList(c.labelIds, "labelIds");
508
+ const unknown = labels.filter((id) => {
509
+ const x = byId.get(id);
510
+ return !x || x.attributes.linked_to_profile === true;
511
+ });
512
+ if (unknown.length)
513
+ throw writeError("unknown_label", "Not a label on this frame: see labels.list().", { ids: unknown });
514
+ const fed = labels.filter((id) => !currentLabels.includes(id) && (byId.get(id)?.relationships?.source_calendars?.data ?? []).length > 0);
515
+ if (fed.length)
516
+ throw writeError("label_not_assignable", "A synced calendar writes to this label; Skylight assigns it itself.", { ids: fed });
517
+ changes.labelIds = labels;
518
+ }
519
+ body.category_ids = [...profiles, ...labels];
520
+ expect.categoryIds = [...profiles, ...labels];
521
+ const title = typeof a.summary === "string" ? a.summary : "this event";
522
+ const effect = found.kind === "series"
523
+ ? scope === "one"
524
+ ? `only the occurrence on ${raw.date}; it becomes its own event with a new id`
525
+ : `the whole series "${title}", every occurrence, including ones edited on their own`
526
+ : found.kind === "detached"
527
+ ? `this occurrence of "${title}", which was already edited on its own`
528
+ : `"${title}"`;
529
+ return { found, scope, body, changes, effect, expect };
530
+ }
531
+ function matchesExpect(event, expect, categoryIdsOf) {
532
+ const a = event.attributes;
533
+ if (expect.title !== undefined && a.summary !== expect.title)
534
+ return false;
535
+ if (expect.startMs !== undefined && Date.parse(String(a.starts_at)) !== expect.startMs)
536
+ return false;
537
+ if (expect.endMs !== undefined && Date.parse(String(a.ends_at)) !== expect.endMs)
538
+ return false;
539
+ if (expect.allDay !== undefined && (a.all_day === true) !== expect.allDay)
540
+ return false;
541
+ if (expect.location !== undefined && !sameText(a.location, expect.location))
542
+ return false;
543
+ if (expect.notes !== undefined && !sameText(a.description, expect.notes))
544
+ return false;
545
+ const stored = new Set(categoryIdsOf(event));
546
+ return expect.categoryIds.every((id) => stored.has(id));
547
+ }
548
+ /**
549
+ * Update, then read back. Resolves with the event as stored, under its id after the change: an edit
550
+ * of one occurrence makes a new event, and a time edit of a series changes every occurrence's id.
551
+ */
552
+ export async function commitUpdate(input, timeZone, categoryIdsOf) {
553
+ const plan = await planUpdate(input, timeZone, categoryIdsOf);
554
+ const id = String(plan.found.event.id);
555
+ try {
556
+ await updateCalendarEvent(id, plan.body, plan.scope ?? undefined);
557
+ }
558
+ catch (error) {
559
+ throw mapWriteFailure(error);
560
+ }
561
+ const key = seriesKeyOf(plan.found.event);
562
+ const dates = [...new Set(plan.expect.readDates)].sort();
563
+ const pick = (list) => {
564
+ const fits = (e) => matchesExpect(e, plan.expect, categoryIdsOf);
565
+ if (plan.found.kind !== "series")
566
+ return list.find((e) => String(e.id) === id && fits(e));
567
+ if (plan.scope === "one") {
568
+ // The split-off occurrence: a plain id, pointing back at the series.
569
+ return list.find((e) => {
570
+ const m = e.attributes.master_event_id;
571
+ return m != null && (String(m) === key.uid || String(m) === key.number) && fits(e);
572
+ });
573
+ }
574
+ // Whole series: the occurrence on this date, same series.
575
+ return list.find((e) => String(e.id).split("-")[0] === key.number && fits(e));
576
+ };
577
+ const back = await readBackUntil(() => getCalendarEvents({ dateMin: dates[0], dateMax: dates[dates.length - 1], timezone: timeZone }), (list) => pick(list) !== undefined);
578
+ const stored = pick(back.value);
579
+ if (!back.ok || !stored) {
580
+ throw writeError("not_confirmed", "Skylight accepted the change but reading it back did not show it as asked. Read the calendar before trying again.", { eventId: id });
581
+ }
582
+ return stored;
583
+ }
584
+ /** The one check behind previewDelete and delete. */
585
+ export async function planDelete(input, timeZone, categoryIdsOf) {
586
+ if (!input || typeof input !== "object" || Array.isArray(input))
587
+ throw writeError("bad_input", "delete needs an object: id, date, version.");
588
+ const raw = input;
589
+ if (raw.scope !== undefined && raw.scope !== "one" && raw.scope !== "future" && raw.scope !== "all") {
590
+ throw writeError("bad_input", 'scope must be "one", "future" or "all".');
591
+ }
592
+ const found = await findForWrite(raw, DELETE_KEYS, timeZone, categoryIdsOf, "deleted");
593
+ const scope = raw.scope ?? null;
594
+ if (found.kind === "series" && scope === null) {
595
+ throw writeError("scope_required", 'That is an occurrence of a repeating event: say scope "one", "future" (this and every later one) or "all" (the whole series).');
596
+ }
597
+ if (found.kind !== "series" && scope !== null)
598
+ throw writeError("scope_not_allowed", "scope applies to an occurrence of a repeating event only.");
599
+ const a = found.event.attributes;
600
+ const title = typeof a.summary === "string" ? a.summary : "this event";
601
+ const date = raw.date;
602
+ const effect = scope === "one" ? `only the occurrence of "${title}" on ${date}`
603
+ : scope === "future" ? `"${title}" on ${date} and every later occurrence`
604
+ : scope === "all" ? `the whole series "${title}", every occurrence past and future, including ones edited on their own`
605
+ : found.kind === "detached" ? `this occurrence of "${title}", which was edited on its own (the rest of the series stays)`
606
+ : `"${title}"`;
607
+ return { found, scope, effect, date };
608
+ }
609
+ /** Delete, then read the date back until the event is gone. */
610
+ export async function commitDelete(input, timeZone, categoryIdsOf) {
611
+ const plan = await planDelete(input, timeZone, categoryIdsOf);
612
+ const id = String(plan.found.event.id);
613
+ try {
614
+ // An occurrence edited on its own is deleted by its own id with no scope, as the app does.
615
+ await deleteCalendarEvent(id, plan.scope ?? undefined);
616
+ }
617
+ catch (error) {
618
+ throw mapWriteFailure(error);
619
+ }
620
+ const back = await readBackUntil(() => getCalendarEvents({ dateMin: plan.date, dateMax: plan.date, timezone: timeZone }), (list) => !list.some((e) => String(e.id) === id));
621
+ if (!back.ok)
622
+ throw writeError("not_confirmed", "Skylight accepted the delete but the event still shows on reading it back. Read the calendar before trying again.", { eventId: id });
623
+ return { deleted: true, id, scope: plan.scope };
624
+ }
625
+ //# sourceMappingURL=lib-writes.js.map