@miguelarios/cal-mcp 0.16.0 → 0.19.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.19.0 (2026-09-14)
4
+
5
+ - `list_calendars` reports `description`, `timezone` (the calendar's default IANA zone, from RFC 7809 `calendar-timezone-id` when the server sends it, else the `TZID` inside RFC 4791 `calendar-timezone`) and `order` (Apple `calendar-order`), each `null` where the provider does not say (#46). `read_only` was already there.
6
+ - `create_calendar` and `update_calendar` take `timezone` and `order`. The zone is validated as an IANA name and written as a `VTIMEZONE` in `calendar-timezone`; the id form is deliberately not written, since SabreDAV-based servers reject unknown properties and a `PROPPATCH` is all-or-nothing. `order` must be a non-negative integer.
7
+ - Bumped `@miguelarios/pim-core` dependency to `^0.14.0` for `generateVTimezoneIcs`.
8
+
9
+ ## 0.18.0 (2026-09-14)
10
+
11
+ - `get_free_busy` — busy periods across one or more calendars in a range, merged and typed as `busy`, `tentative` or `unavailable`, with no event details (#48). The server's own `free-busy-query` REPORT (RFC 4791 §7.10) is used where it answers one; otherwise the answer is computed from the expanded events, with the same all-day and transparency rules as `find_free_slots`. `sources` reports which path each calendar took.
12
+ - `findFreeSlots` and `getFreeBusy` share one event-collection path; `find_free_slots` output is unchanged.
13
+ - Bumped `@miguelarios/pim-core` dependency to `^0.13.0` for `parseIcsFreeBusy`.
14
+
15
+ ## 0.17.0 (2026-09-14)
16
+
17
+ - `update_event` accepts `span: "future"`: changes the given occurrence of a recurring event and every later one (#38). The series is split at that occurrence — the existing object is ended just before it, keeping earlier occurrences and their overrides, and a new object with a new UID carries the remaining pattern with the changes applied. The result is the new series' event, so callers pick up the UID to use from now on. A `COUNT` is reduced by the occurrences already spent, `EXDATE`/`RDATE` values are divided between the halves, and a cut at the first occurrence edits the whole series in place. Per-occurrence overrides on or after the cut are discarded, and only then is the user asked to confirm. `occurrence_date` must be an occurrence the series generates, otherwise `validation_error`. The new object is written before the old one is cut, so a mid-way failure can only leave a visible duplicate tail, never missing occurrences.
18
+ - Bumped `@miguelarios/pim-core` dependency to `^0.12.0` for `splitRecurrenceIcs`.
19
+
3
20
  ## 0.16.0 (2026-09-14)
4
21
 
5
22
  - `delete_event` accepts `span: "future"`: deletes the given occurrence of a recurring event and every later one, keeping earlier occurrences and their overrides (#41). The master `RRULE` gets `UNTIL` set to just before the occurrence (replacing any `COUNT`), and overrides, `RDATE`s and `EXDATE`s past the cut are dropped. Cutting at the first occurrence deletes the object outright rather than leaving an empty series. Gated on confirmation like a full delete, since the removed occurrences cannot be recovered.
package/README.md CHANGED
@@ -39,7 +39,7 @@ Add multiple providers by using different IDs: `CALDAV_NEXTCLOUD_URL`, `CALDAV_N
39
39
 
40
40
  Optional env vars: `PIM_TIMEZONE`.
41
41
 
42
- ## Tools (11)
42
+ ## Tools (16)
43
43
 
44
44
  See [docs/tools/cal-mcp.md](../../docs/tools/cal-mcp.md) for full parameter and output details.
45
45
 
@@ -57,6 +57,10 @@ See [docs/tools/cal-mcp.md](../../docs/tools/cal-mcp.md) for full parameter and
57
57
  | `create_events_batch` | Create multiple events at once |
58
58
  | `import_ics` | Import events from .ics content |
59
59
  | `find_free_slots` | Find available time slots across calendars |
60
+ | `get_free_busy` | Busy periods in a range, typed, without event details |
61
+ | `create_calendar` | Create a calendar collection |
62
+ | `update_calendar` | Rename or recolour a calendar |
63
+ | `delete_calendar` | Delete a calendar and every event in it |
60
64
 
61
65
  ## License
62
66
 
@@ -1,9 +1,14 @@
1
1
  import { type CalDavConfig } from "@miguelarios/pim-core";
2
- import { type ParsedAlarm } from "@miguelarios/pim-core/ics";
2
+ import { type FreeBusyPeriod, type ParsedAlarm } from "@miguelarios/pim-core/ics";
3
3
  export interface CalendarInfo {
4
4
  calendar_id: string;
5
5
  display_name: string;
6
6
  color: string | null;
7
+ description: string | null;
8
+ /** IANA zone the calendar defaults to (`calendar-timezone`), when the provider reports one. */
9
+ timezone: string | null;
10
+ /** Sort position among the account's calendars (Apple `calendar-order`), when reported. */
11
+ order: number | null;
7
12
  source: string;
8
13
  read_only: boolean;
9
14
  url: string;
@@ -69,6 +74,26 @@ export interface CalendarObjectMeta {
69
74
  url: string;
70
75
  etag?: string;
71
76
  }
77
+ export interface FreeBusyOptions {
78
+ ignoreTentative?: boolean;
79
+ includeAllDayAsBusy?: boolean;
80
+ }
81
+ /** Where a calendar's busy periods came from. */
82
+ export type FreeBusySource = "server" | "computed";
83
+ export interface FreeBusyResult {
84
+ busy: FreeBusyPeriod[];
85
+ sources: Record<string, FreeBusySource>;
86
+ }
87
+ /**
88
+ * Merges overlapping or touching periods of the same type; output is sorted
89
+ * by start. Periods are visited in start order, so by the time one is
90
+ * considered every merged interval of its type that could overlap it already
91
+ * exists, and there is at most one: two intervals of the same type that
92
+ * overlapped each other would have been merged when the second arrived. That
93
+ * is why matching against any existing interval, not just the last, is both
94
+ * safe and needed — the last interval may be of another type.
95
+ */
96
+ export declare function mergeFreeBusy(periods: FreeBusyPeriod[]): FreeBusyPeriod[];
72
97
  export declare function buildCanonicalHref(calendarUrl: string, uid: string): string | null;
73
98
  export declare const DEBUG_TIMINGS: Array<{
74
99
  op: string;
@@ -143,6 +168,8 @@ export declare class CalDavService {
143
168
  displayName: string;
144
169
  description?: string;
145
170
  color?: string;
171
+ timezone?: string;
172
+ order?: number;
146
173
  slug?: string;
147
174
  }): Promise<CalendarCollection>;
148
175
  /**
@@ -157,6 +184,8 @@ export declare class CalDavService {
157
184
  displayName?: string;
158
185
  description?: string;
159
186
  color?: string;
187
+ timezone?: string;
188
+ order?: number;
160
189
  }): Promise<CalendarCollection>;
161
190
  /** Deletes a calendar collection — and with it every event inside. */
162
191
  deleteCalendar(calendarId: string): Promise<CalendarCollection>;
@@ -197,6 +226,29 @@ export declare class CalDavService {
197
226
  url: string;
198
227
  etag: string;
199
228
  }>;
229
+ /** Fetches the events of one calendar in a range, reduced to what free/busy needs. */
230
+ private collectBusyCandidates;
231
+ /** Which candidates actually block time under the given options. */
232
+ private static blocksTime;
233
+ /**
234
+ * Asks the server for a calendar's busy periods with a `free-busy-query`
235
+ * REPORT (RFC 4791 §7.10). The reply is `text/calendar` rather than a
236
+ * multistatus document, so it goes through `fetch` directly instead of
237
+ * tsdav, whose request helpers parse every reply as XML. Returns `null`
238
+ * when the server declines — the report is optional for servers to
239
+ * support, and SabreDAV-based ones (Nextcloud) only answer it on the
240
+ * scheduling outbox — so the caller can fall back to computing.
241
+ */
242
+ private fetchServerFreeBusy;
243
+ /**
244
+ * Busy periods across `calendarIds` in [start, end): from the server's own
245
+ * `free-busy-query` where it answers one, otherwise computed from the
246
+ * expanded events the same way `findFreeSlots` does (#48). `sources` says
247
+ * which path each calendar took, since the two can differ on all-day and
248
+ * transparent events, which are the server's call on its path and the
249
+ * options' on ours.
250
+ */
251
+ getFreeBusy(calendarIds: string[], start: string, end: string, options?: FreeBusyOptions): Promise<FreeBusyResult>;
200
252
  findFreeSlots(calendarIds: string[], start: string, end: string, durationMinutes: number, options?: FindFreeSlotsOptions): Promise<FreeSlot[]>;
201
253
  private toEventFull;
202
254
  private formatSlots;
@@ -1 +1 @@
1
- {"version":3,"file":"CalDavService.d.ts","sourceRoot":"","sources":["../../src/services/CalDavService.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,YAAY,EAUlB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,KAAK,WAAW,EAIjB,MAAM,2BAA2B,CAAC;AAUnC,MAAM,WAAW,YAAY;IAC3B,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,OAAO,CAAC;IACnB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,6DAA6D;AAC7D,MAAM,WAAW,kBA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AAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IAoBvD,sFAAsF;YACxE,qBAAqB;IAqCnC,oEAAoE;IACpE,OAAO,CAAC,MAAM,CAAC,UAAU;IAWzB;;;;;;;;OAQG;YACW,mBAAmB;IAoCjC;;;;;;;OAOG;IACG,WAAW,CACf,WAAW,EAAE,MAAM,EAAE,EACrB,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,eAAoB,GAC5B,OAAO,CAAC,cAAc,CAAC;IA+CpB,aAAa,CACjB,WAAW,EAAE,MAAM,EAAE,EACrB,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,MAAM,EACX,eAAe,EAAE,MAAM,EACvB,OAAO,GAAE,oBAAyB,GACjC,OAAO,CAAC,QAAQ,EAAE,CAAC;IAyKtB,OAAO,CAAC,WAAW;IA0BnB,OAAO,CAAC,WAAW;CAOpB"}
@@ -1,8 +1,34 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { CalendarError, ErrorCode, ValidationError, checkDavCollectionResponse, formatInTimezone, getLocalDateParts, getTimezone, toPimError, zonedTimeToUtc, } from "@miguelarios/pim-core";
3
- import { parseIcsEvents, } from "@miguelarios/pim-core/ics";
3
+ import { generateVTimezoneIcs, parseIcsEvents, parseIcsFreeBusy, } from "@miguelarios/pim-core/ics";
4
4
  import { DAVClient } from "tsdav";
5
5
  import { deleteCachedObject, getCachedObject, moveCachedCalendar, purgeCachedCalendar, setCachedObject, } from "./urlCache.js";
6
+ /**
7
+ * Merges overlapping or touching periods of the same type; output is sorted
8
+ * by start. Periods are visited in start order, so by the time one is
9
+ * considered every merged interval of its type that could overlap it already
10
+ * exists, and there is at most one: two intervals of the same type that
11
+ * overlapped each other would have been merged when the second arrived. That
12
+ * is why matching against any existing interval, not just the last, is both
13
+ * safe and needed — the last interval may be of another type.
14
+ */
15
+ export function mergeFreeBusy(periods) {
16
+ const sorted = [...periods].sort((a, b) => a.start.localeCompare(b.start) || a.type.localeCompare(b.type));
17
+ const out = [];
18
+ for (const period of sorted) {
19
+ const last = out.find((p) => p.type === period.type && p.end >= period.start && p.start <= period.end);
20
+ if (last) {
21
+ if (period.end > last.end)
22
+ last.end = period.end;
23
+ if (period.start < last.start)
24
+ last.start = period.start;
25
+ }
26
+ else {
27
+ out.push({ ...period });
28
+ }
29
+ }
30
+ return out.sort((a, b) => a.start.localeCompare(b.start));
31
+ }
6
32
  /** Derives a URL slug from a display name; falls back to a random one when nothing survives. */
7
33
  function slugify(displayName) {
8
34
  const slug = displayName
@@ -31,6 +57,87 @@ const CALENDAR_DAV_NAMESPACES = {
31
57
  "xmlns:cal": "urn:ietf:params:xml:ns:caldav",
32
58
  "xmlns:ical": "http://apple.com/ns/ical/",
33
59
  };
60
+ /**
61
+ * The collection properties asked for in the calendar listing: tsdav's own
62
+ * set, plus RFC 7809's `calendar-timezone-id` and Apple's `calendar-order`,
63
+ * which tsdav does not request by default and only hands back through
64
+ * `projectedProps`. Prefixes are tsdav's namespace shorthands.
65
+ */
66
+ const CALENDAR_LIST_PROPS = {
67
+ "c:calendar-description": {},
68
+ "c:calendar-timezone": {},
69
+ "c:calendar-timezone-id": {},
70
+ "d:displayname": {},
71
+ "ca:calendar-color": {},
72
+ "ca:calendar-order": {},
73
+ "cs:getctag": {},
74
+ "d:resourcetype": {},
75
+ "c:supported-calendar-component-set": {},
76
+ "d:sync-token": {},
77
+ };
78
+ const CALENDAR_LIST_PROJECTION = { calendarTimezoneId: true, calendarOrder: true };
79
+ /**
80
+ * The calendar's default zone as an IANA name: RFC 7809's id property when
81
+ * the server sends it, else the TZID of the VTIMEZONE in `calendar-timezone`.
82
+ */
83
+ function timezoneOf(calendar) {
84
+ const c = calendar;
85
+ const id = c.projectedProps?.calendarTimezoneId;
86
+ if (typeof id === "string" && id.trim())
87
+ return id.trim();
88
+ if (typeof c.timezone === "string") {
89
+ const match = c.timezone.match(/^TZID:(.+?)\r?$/m);
90
+ if (match)
91
+ return match[1].trim();
92
+ }
93
+ return null;
94
+ }
95
+ function orderOf(calendar) {
96
+ const raw = calendar.projectedProps
97
+ ?.calendarOrder;
98
+ if (typeof raw === "number" && Number.isInteger(raw))
99
+ return raw;
100
+ if (typeof raw === "string" && /^\d+$/.test(raw.trim()))
101
+ return Number(raw.trim());
102
+ return null;
103
+ }
104
+ function descriptionOf(calendar) {
105
+ const d = calendar.description;
106
+ return typeof d === "string" && d.length > 0 ? d : null;
107
+ }
108
+ /** An IANA zone name the runtime knows, returned trimmed. */
109
+ function normalizeCalendarTimezone(timezone) {
110
+ const trimmed = timezone.trim();
111
+ try {
112
+ new Intl.DateTimeFormat("en-US", { timeZone: trimmed });
113
+ }
114
+ catch {
115
+ throw new ValidationError(`Invalid timezone "${timezone}" — use an IANA zone name (e.g. America/Chicago)`, "timezone");
116
+ }
117
+ if (generateVTimezoneIcs(trimmed) === null) {
118
+ throw new ValidationError(`Timezone "${timezone}" has no VTIMEZONE definition available to write`, "timezone");
119
+ }
120
+ return trimmed;
121
+ }
122
+ function normalizeCalendarOrder(order) {
123
+ if (!Number.isInteger(order) || order < 0) {
124
+ throw new ValidationError(`Invalid order ${order} — use a non-negative integer`, "order");
125
+ }
126
+ return order;
127
+ }
128
+ /**
129
+ * The property that carries a calendar's default zone. Only RFC 4791's
130
+ * `calendar-timezone` (a VTIMEZONE) is written: RFC 7809's
131
+ * `calendar-timezone-id` is not implemented by SabreDAV-based servers, and a
132
+ * PROPPATCH is all-or-nothing, so including it would fail the whole update
133
+ * there. The id form is still read when a server sends it.
134
+ */
135
+ function calendarTimezoneProps(timezone) {
136
+ if (timezone === undefined)
137
+ return {};
138
+ const vtimezone = generateVTimezoneIcs(timezone);
139
+ return vtimezone === null ? {} : { "cal:calendar-timezone": vtimezone };
140
+ }
34
141
  /** tsdav types `displayName` loosely; calendars without one read as "". */
35
142
  function displayNameOf(calendar) {
36
143
  const name = calendar?.displayName;
@@ -293,7 +400,10 @@ export class CalDavService {
293
400
  for (const [providerId, account] of this.accounts) {
294
401
  try {
295
402
  const client = await this.getClient(account);
296
- const calendars = await client.fetchCalendars();
403
+ const calendars = await client.fetchCalendars({
404
+ props: CALENDAR_LIST_PROPS,
405
+ projectedProps: CALENDAR_LIST_PROJECTION,
406
+ });
297
407
  this.calendarsCache.set(providerId, calendars);
298
408
  for (const cal of calendars) {
299
409
  const displayName = displayNameOf(cal);
@@ -302,6 +412,9 @@ export class CalDavService {
302
412
  calendar_id: `${providerId}/${displayName}`,
303
413
  display_name: displayName,
304
414
  color: cal.calendarColor ?? null,
415
+ description: descriptionOf(cal),
416
+ timezone: timezoneOf(cal),
417
+ order: orderOf(cal),
305
418
  source: providerId,
306
419
  read_only: !canWrite,
307
420
  url: cal.url,
@@ -419,6 +532,8 @@ export class CalDavService {
419
532
  throw new ValidationError(`Invalid slug "${opts.slug}" — use lowercase letters, digits and hyphens, starting with a letter or digit`, "slug");
420
533
  }
421
534
  const color = opts.color !== undefined ? normalizeCalendarColor(opts.color) : undefined;
535
+ const timezone = opts.timezone !== undefined ? normalizeCalendarTimezone(opts.timezone) : undefined;
536
+ const order = opts.order !== undefined ? normalizeCalendarOrder(opts.order) : undefined;
422
537
  const client = await this.getClient(account);
423
538
  const existing = await this.fetchCalendarsFor(client, account.id);
424
539
  // A second calendar with the same display name on the same provider would
@@ -465,6 +580,8 @@ export class CalDavService {
465
580
  ? { "cal:calendar-description": opts.description }
466
581
  : {}),
467
582
  ...(color !== undefined ? { "ical:calendar-color": color } : {}),
583
+ ...calendarTimezoneProps(timezone),
584
+ ...(order !== undefined ? { "ical:calendar-order": String(order) } : {}),
468
585
  },
469
586
  },
470
587
  },
@@ -499,13 +616,17 @@ export class CalDavService {
499
616
  async updateCalendarMeta(calendarId, opts) {
500
617
  if (opts.displayName === undefined &&
501
618
  opts.description === undefined &&
502
- opts.color === undefined) {
503
- throw new ValidationError("Nothing to change — provide a display_name, color and/or description");
619
+ opts.color === undefined &&
620
+ opts.timezone === undefined &&
621
+ opts.order === undefined) {
622
+ throw new ValidationError("Nothing to change — provide a display_name, color, description, timezone and/or order");
504
623
  }
505
624
  if (opts.displayName !== undefined && opts.displayName.trim() === "") {
506
625
  throw new ValidationError("display_name cannot be empty", "display_name");
507
626
  }
508
627
  const color = opts.color !== undefined ? normalizeCalendarColor(opts.color) : undefined;
628
+ const timezone = opts.timezone !== undefined ? normalizeCalendarTimezone(opts.timezone) : undefined;
629
+ const order = opts.order !== undefined ? normalizeCalendarOrder(opts.order) : undefined;
509
630
  const { account, calendarName } = this.resolveAccount(calendarId);
510
631
  const client = await this.getClient(account);
511
632
  const calendar = await this.findCalendar(client, calendarName, account.id);
@@ -537,6 +658,8 @@ export class CalDavService {
537
658
  ? { "cal:calendar-description": opts.description }
538
659
  : {}),
539
660
  ...(color !== undefined ? { "ical:calendar-color": color } : {}),
661
+ ...calendarTimezoneProps(timezone),
662
+ ...(order !== undefined ? { "ical:calendar-order": String(order) } : {}),
540
663
  },
541
664
  },
542
665
  },
@@ -594,7 +717,10 @@ export class CalDavService {
594
717
  const cached = this.calendarsCache.get(providerId);
595
718
  if (cached)
596
719
  return cached;
597
- const calendars = await client.fetchCalendars();
720
+ const calendars = await client.fetchCalendars({
721
+ props: CALENDAR_LIST_PROPS,
722
+ projectedProps: CALENDAR_LIST_PROJECTION,
723
+ });
598
724
  this.calendarsCache.set(providerId, calendars);
599
725
  return calendars;
600
726
  }
@@ -954,6 +1080,143 @@ export class CalDavService {
954
1080
  throw toPimError(error instanceof Error ? error : new Error(String(error)));
955
1081
  }
956
1082
  }
1083
+ /** Fetches the events of one calendar in a range, reduced to what free/busy needs. */
1084
+ async collectBusyCandidates(calendarId, start, end) {
1085
+ const out = [];
1086
+ try {
1087
+ const { account, calendarName } = this.resolveAccount(calendarId);
1088
+ const client = await this.getClient(account);
1089
+ const calendar = await this.findCalendar(client, calendarName, account.id);
1090
+ const objects = await client.fetchCalendarObjects({
1091
+ calendar,
1092
+ timeRange: { start, end },
1093
+ expand: true,
1094
+ });
1095
+ for (const obj of objects) {
1096
+ if (!obj.data)
1097
+ continue;
1098
+ const parsed = parseIcsEvents(obj.data, { start, end });
1099
+ for (const event of parsed) {
1100
+ out.push({
1101
+ start: event.start,
1102
+ end: event.end,
1103
+ status: event.status,
1104
+ availability: event.availability,
1105
+ all_day: event.all_day,
1106
+ calendar_id: calendarId,
1107
+ });
1108
+ }
1109
+ }
1110
+ }
1111
+ catch (error) {
1112
+ if (error instanceof CalendarError)
1113
+ throw error;
1114
+ throw toPimError(error instanceof Error ? error : new Error(String(error)));
1115
+ }
1116
+ return out;
1117
+ }
1118
+ /** Which candidates actually block time under the given options. */
1119
+ static blocksTime(e, options) {
1120
+ // Skip all-day events unless includeAllDayAsBusy
1121
+ if (e.all_day && !options.includeAllDayAsBusy)
1122
+ return false;
1123
+ // Skip free events
1124
+ if (e.availability === "free")
1125
+ return false;
1126
+ // Skip tentative when ignoreTentative
1127
+ if (options.ignoreTentative && e.status === "tentative")
1128
+ return false;
1129
+ // Everything else blocks
1130
+ return true;
1131
+ }
1132
+ /**
1133
+ * Asks the server for a calendar's busy periods with a `free-busy-query`
1134
+ * REPORT (RFC 4791 §7.10). The reply is `text/calendar` rather than a
1135
+ * multistatus document, so it goes through `fetch` directly instead of
1136
+ * tsdav, whose request helpers parse every reply as XML. Returns `null`
1137
+ * when the server declines — the report is optional for servers to
1138
+ * support, and SabreDAV-based ones (Nextcloud) only answer it on the
1139
+ * scheduling outbox — so the caller can fall back to computing.
1140
+ */
1141
+ async fetchServerFreeBusy(account, calendarUrl, start, end) {
1142
+ const stamp = (iso) => `${new Date(iso).toISOString().slice(0, 19).replace(/[-:]/g, "")}Z`;
1143
+ const body = [
1144
+ `<?xml version="1.0" encoding="utf-8" ?>`,
1145
+ `<C:free-busy-query xmlns:C="urn:ietf:params:xml:ns:caldav">`,
1146
+ `<C:time-range start="${stamp(start)}" end="${stamp(end)}"/>`,
1147
+ `</C:free-busy-query>`,
1148
+ ].join("\n");
1149
+ try {
1150
+ const response = await fetch(new URL(calendarUrl, account.url).toString(), {
1151
+ method: "REPORT",
1152
+ headers: {
1153
+ Authorization: `Basic ${Buffer.from(`${account.username}:${account.password}`).toString("base64")}`,
1154
+ "Content-Type": "application/xml; charset=utf-8",
1155
+ // RFC 4791 §7.10: the report is applied to the collection itself,
1156
+ // with the time-range in the body as scope; Depth 0 is what the
1157
+ // §7.10.1 example sends and what is assumed when the header is absent.
1158
+ Depth: "0",
1159
+ },
1160
+ body,
1161
+ });
1162
+ if (!response.ok)
1163
+ return null;
1164
+ const contentType = response.headers.get("content-type") ?? "";
1165
+ if (!contentType.toLowerCase().includes("text/calendar"))
1166
+ return null;
1167
+ return parseIcsFreeBusy(await response.text());
1168
+ }
1169
+ catch {
1170
+ return null;
1171
+ }
1172
+ }
1173
+ /**
1174
+ * Busy periods across `calendarIds` in [start, end): from the server's own
1175
+ * `free-busy-query` where it answers one, otherwise computed from the
1176
+ * expanded events the same way `findFreeSlots` does (#48). `sources` says
1177
+ * which path each calendar took, since the two can differ on all-day and
1178
+ * transparent events, which are the server's call on its path and the
1179
+ * options' on ours.
1180
+ */
1181
+ async getFreeBusy(calendarIds, start, end, options = {}) {
1182
+ const busy = [];
1183
+ const sources = {};
1184
+ for (const calendarId of calendarIds) {
1185
+ const { account, calendarName } = this.resolveAccount(calendarId);
1186
+ const client = await this.getClient(account);
1187
+ const calendar = await this.findCalendar(client, calendarName, account.id);
1188
+ const fromServer = await this.fetchServerFreeBusy(account, calendar.url, start, end);
1189
+ if (fromServer !== null) {
1190
+ sources[calendarId] = "server";
1191
+ for (const period of fromServer) {
1192
+ if (options.ignoreTentative && period.type === "tentative")
1193
+ continue;
1194
+ busy.push(period);
1195
+ }
1196
+ continue;
1197
+ }
1198
+ sources[calendarId] = "computed";
1199
+ for (const candidate of await this.collectBusyCandidates(calendarId, start, end)) {
1200
+ if (!CalDavService.blocksTime(candidate, options))
1201
+ continue;
1202
+ busy.push({
1203
+ start: new Date(candidate.start).toISOString(),
1204
+ end: new Date(candidate.end).toISOString(),
1205
+ type: candidate.status === "tentative" ? "tentative" : "busy",
1206
+ });
1207
+ }
1208
+ }
1209
+ const rangeStart = new Date(start).toISOString();
1210
+ const rangeEnd = new Date(end).toISOString();
1211
+ const clipped = busy
1212
+ .map((p) => ({
1213
+ ...p,
1214
+ start: p.start < rangeStart ? rangeStart : p.start,
1215
+ end: p.end > rangeEnd ? rangeEnd : p.end,
1216
+ }))
1217
+ .filter((p) => p.start < p.end);
1218
+ return { busy: mergeFreeBusy(clipped), sources };
1219
+ }
957
1220
  async findFreeSlots(calendarIds, start, end, durationMinutes, options = {}) {
958
1221
  // 1. Fetch all events across specified calendars
959
1222
  const allEvents = [];
@@ -961,51 +1224,10 @@ export class CalDavService {
961
1224
  // Skip excluded calendars
962
1225
  if (options.excludeCalendars?.includes(calendarId))
963
1226
  continue;
964
- try {
965
- const { account, calendarName } = this.resolveAccount(calendarId);
966
- const client = await this.getClient(account);
967
- const calendar = await this.findCalendar(client, calendarName, account.id);
968
- const objects = await client.fetchCalendarObjects({
969
- calendar,
970
- timeRange: { start, end },
971
- expand: true,
972
- });
973
- for (const obj of objects) {
974
- if (!obj.data)
975
- continue;
976
- const parsed = parseIcsEvents(obj.data, { start, end });
977
- for (const event of parsed) {
978
- allEvents.push({
979
- start: event.start,
980
- end: event.end,
981
- status: event.status,
982
- availability: event.availability,
983
- all_day: event.all_day,
984
- calendar_id: calendarId,
985
- });
986
- }
987
- }
988
- }
989
- catch (error) {
990
- if (error instanceof CalendarError)
991
- throw error;
992
- throw toPimError(error instanceof Error ? error : new Error(String(error)));
993
- }
1227
+ allEvents.push(...(await this.collectBusyCandidates(calendarId, start, end)));
994
1228
  }
995
1229
  // 2. Filter events — skip free, all-day (unless opted in), and optionally tentative
996
- const busyIntervals = allEvents.filter((e) => {
997
- // Skip all-day events unless includeAllDayAsBusy
998
- if (e.all_day && !options.includeAllDayAsBusy)
999
- return false;
1000
- // Skip free events
1001
- if (e.availability === "free")
1002
- return false;
1003
- // Skip tentative when ignoreTentative
1004
- if (options.ignoreTentative && e.status === "tentative")
1005
- return false;
1006
- // Everything else blocks
1007
- return true;
1008
- });
1230
+ const busyIntervals = allEvents.filter((e) => CalDavService.blocksTime(e, options));
1009
1231
  // 3. Merge overlapping busy intervals
1010
1232
  const sorted = busyIntervals
1011
1233
  .map((e) => ({