langmail-mcp 0.0.0 → 0.2.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.
Files changed (138) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +89 -169
  3. package/dist/chunk-0fxfqny0.js +12642 -0
  4. package/dist/langmail-mcp.js +7 -0
  5. package/package.json +93 -98
  6. package/THIRD_PARTY_NOTICES.md +0 -388
  7. package/dist/attachments/download.js +0 -69
  8. package/dist/attachments/routes.js +0 -42
  9. package/dist/attachments/tickets.js +0 -45
  10. package/dist/attachments/upload-tickets.js +0 -43
  11. package/dist/attachments/upload.js +0 -136
  12. package/dist/caldav/account-settings.js +0 -92
  13. package/dist/caldav/agenda.js +0 -277
  14. package/dist/caldav/alarm.js +0 -97
  15. package/dist/caldav/client.js +0 -408
  16. package/dist/caldav/ical.js +0 -248
  17. package/dist/caldav/occurrence.js +0 -534
  18. package/dist/caldav/recurrence.js +0 -313
  19. package/dist/caldav/rsvp.js +0 -107
  20. package/dist/caldav/scheduling-handover.js +0 -22
  21. package/dist/caldav/timezone.js +0 -103
  22. package/dist/caldav/types.js +0 -5
  23. package/dist/config.js +0 -219
  24. package/dist/contacts/address-class.js +0 -79
  25. package/dist/contacts/birthdays.js +0 -81
  26. package/dist/contacts/card.js +0 -58
  27. package/dist/contacts/constants.js +0 -46
  28. package/dist/contacts/fold.js +0 -309
  29. package/dist/contacts/index.js +0 -10
  30. package/dist/contacts/merge.js +0 -388
  31. package/dist/contacts/observations.js +0 -115
  32. package/dist/contacts/profile.js +0 -402
  33. package/dist/contacts/scoring.js +0 -146
  34. package/dist/contacts/types.js +0 -7
  35. package/dist/contacts/upsert.js +0 -131
  36. package/dist/drafts/attachments.js +0 -254
  37. package/dist/drafts/idempotency.js +0 -60
  38. package/dist/drafts/send-guard.js +0 -184
  39. package/dist/email-render/email-viewer.html +0 -143
  40. package/dist/email-render/image-proxy.js +0 -389
  41. package/dist/email-render/meta.js +0 -48
  42. package/dist/email-render/sanitize.js +0 -93
  43. package/dist/email-render/viewer-resource.js +0 -104
  44. package/dist/http/bearer.js +0 -30
  45. package/dist/http/guard.js +0 -57
  46. package/dist/http/hosts.js +0 -10
  47. package/dist/http/listener.js +0 -170
  48. package/dist/http/routes.js +0 -72
  49. package/dist/ical/ical-parse.js +0 -357
  50. package/dist/ical/index.js +0 -4
  51. package/dist/ical/timezone.js +0 -22
  52. package/dist/ical/windows-zones.js +0 -155
  53. package/dist/index.js +0 -79
  54. package/dist/jmap/blob.js +0 -49
  55. package/dist/jmap/contacts.js +0 -226
  56. package/dist/jmap/drafts.js +0 -480
  57. package/dist/jmap/email.js +0 -668
  58. package/dist/jmap/index.js +0 -12
  59. package/dist/jmap/keywords.js +0 -22
  60. package/dist/jmap/live.js +0 -21
  61. package/dist/jmap/origin.js +0 -113
  62. package/dist/jmap/patch.js +0 -29
  63. package/dist/jmap/request.js +0 -37
  64. package/dist/jmap/session.js +0 -89
  65. package/dist/jmap/sieve.js +0 -71
  66. package/dist/jmap/submission.js +0 -107
  67. package/dist/jmap/timeout.js +0 -30
  68. package/dist/jmap/types.js +0 -6
  69. package/dist/logger.js +0 -48
  70. package/dist/mcp/handler.js +0 -255
  71. package/dist/mcp/http.js +0 -29
  72. package/dist/mcp/instructions.js +0 -44
  73. package/dist/mcp/links.js +0 -64
  74. package/dist/mcp/test-client.js +0 -43
  75. package/dist/mcp/tool-logging.js +0 -67
  76. package/dist/observability/errors.js +0 -41
  77. package/dist/rules/apply.js +0 -236
  78. package/dist/rules/rule.js +0 -280
  79. package/dist/rules/store.js +0 -92
  80. package/dist/tools/annotations.js +0 -71
  81. package/dist/tools/archive-emails.js +0 -40
  82. package/dist/tools/calendar-lookup.js +0 -64
  83. package/dist/tools/contact-common.js +0 -146
  84. package/dist/tools/contact-format.js +0 -72
  85. package/dist/tools/contact-write-through.js +0 -37
  86. package/dist/tools/create-calendar-event.js +0 -231
  87. package/dist/tools/create-calendar.js +0 -54
  88. package/dist/tools/create-contact.js +0 -172
  89. package/dist/tools/create-draft.js +0 -369
  90. package/dist/tools/create-mail-rule.js +0 -101
  91. package/dist/tools/delete-calendar-event.js +0 -165
  92. package/dist/tools/delete-contact.js +0 -60
  93. package/dist/tools/delete-draft.js +0 -129
  94. package/dist/tools/delete-mail-rule.js +0 -38
  95. package/dist/tools/download-attachment.js +0 -90
  96. package/dist/tools/download-email.js +0 -112
  97. package/dist/tools/draft-common.js +0 -600
  98. package/dist/tools/email-types.js +0 -58
  99. package/dist/tools/error-detail.js +0 -10
  100. package/dist/tools/file-emails-common.js +0 -75
  101. package/dist/tools/format.js +0 -131
  102. package/dist/tools/forward-message.js +0 -237
  103. package/dist/tools/forward-quote.js +0 -179
  104. package/dist/tools/get-draft.js +0 -61
  105. package/dist/tools/get-email.js +0 -164
  106. package/dist/tools/get-thread.js +0 -67
  107. package/dist/tools/keywords.js +0 -43
  108. package/dist/tools/list-calendar-events.js +0 -180
  109. package/dist/tools/list-calendars.js +0 -44
  110. package/dist/tools/list-drafts.js +0 -134
  111. package/dist/tools/list-mail-rules.js +0 -28
  112. package/dist/tools/list-unsubscribe.js +0 -152
  113. package/dist/tools/list-upcoming-birthdays.js +0 -165
  114. package/dist/tools/mail-rule-common.js +0 -43
  115. package/dist/tools/mail-rule-format.js +0 -79
  116. package/dist/tools/mailbox-lookup.js +0 -13
  117. package/dist/tools/mark-emails.js +0 -78
  118. package/dist/tools/merge-contacts.js +0 -145
  119. package/dist/tools/move-calendar-events.js +0 -340
  120. package/dist/tools/move-emails.js +0 -64
  121. package/dist/tools/one-click-post.js +0 -275
  122. package/dist/tools/preview-email.js +0 -204
  123. package/dist/tools/preview-mail-rule.js +0 -79
  124. package/dist/tools/reply-quote.js +0 -426
  125. package/dist/tools/reply-to-message.js +0 -292
  126. package/dist/tools/respond-to-event.js +0 -110
  127. package/dist/tools/result.js +0 -9
  128. package/dist/tools/search-contacts.js +0 -431
  129. package/dist/tools/search-emails.js +0 -570
  130. package/dist/tools/send-draft.js +0 -308
  131. package/dist/tools/trash-emails.js +0 -36
  132. package/dist/tools/unsubscribe-from-list.js +0 -249
  133. package/dist/tools/update-calendar-event.js +0 -973
  134. package/dist/tools/update-calendar.js +0 -100
  135. package/dist/tools/update-contact.js +0 -382
  136. package/dist/tools/update-draft.js +0 -714
  137. package/dist/tools/update-mail-rule.js +0 -103
  138. package/dist/tools/upload-attachments.js +0 -126
@@ -1,534 +0,0 @@
1
- // Splices a single-occurrence override into a recurring calendar object.
2
- //
3
- // A recurring event and its per-occurrence overrides share one UID and live in
4
- // a single calendar object (RFC 5545 §3.8.4.4): the master VEVENT holds the
5
- // RRULE; each override VEVENT carries a RECURRENCE-ID naming the instance it
6
- // replaces. Editing one occurrence therefore means adding (or replacing) an
7
- // override VEVENT while leaving the master — and every other occurrence —
8
- // exactly as stored, then PUTting the whole object back so Stalwart's
9
- // server-side scheduler (RFC 6638) diffs it and fans out an iMIP REQUEST scoped
10
- // to that instance.
11
- //
12
- // Pure string in/out (no live server), so the merge is unit-testable — the same
13
- // shape as rsvp.ts and ical-parse.ts.
14
- import { icalDateToIso, parseWallClockInZone } from "../ical/index.js";
15
- import { foldLine, maxSequence } from "./ical.js";
16
- import { toIcalUtc } from "./recurrence.js";
17
- import { toWallClockIso, toZonedDate } from "./timezone.js";
18
- const CRLF = "\r\n";
19
- // Line break between content lines (CRLF, bare CR, or LF). Output is always
20
- // re-joined with CRLF (RFC 5545 §3.1); folded continuation lines keep their
21
- // leading space and so survive the round-trip.
22
- const LINE_RE = /\r\n|\r|\n/u;
23
- // A RECURRENCE-ID content line, with optional parameters (e.g. `;VALUE=DATE`,
24
- // `;TZID=…`), capturing the value after the first colon. Datetime values are
25
- // short and never folded, so a single physical line is enough.
26
- const RECURRENCE_ID_RE = /^RECURRENCE-ID(?:;[^:]*)?:(.*)$/iu;
27
- const TZID_RE = /(?:^|;)TZID=([^;:]+)/iu;
28
- const METHOD_RE = /^METHOD:/iu;
29
- const VTIMEZONE_TZID_RE = /^TZID:(.*)$/iu;
30
- // An EXDATE content line, capturing the (possibly comma-separated) values after
31
- // the first colon. Matched against an unfolded line (see unfoldLines): a
32
- // foreign series with many cancelled days folds its EXDATE list.
33
- const EXDATE_RE = /^EXDATE(?:;[^:]*)?:(.*)$/iu;
34
- const SEQUENCE_RE = /^SEQUENCE:/iu;
35
- const DTSTART_RE = /^DTSTART(;[^:]*)?:/iu;
36
- const RRULE_RE = /^RRULE[:;]/iu;
37
- // Separates a VCALENDAR into its calendar-level header lines and its top-level
38
- // components, tracking BEGIN/END depth so a nested VALARM never ends a VEVENT
39
- // early. Blank lines are dropped (iCalendar has none; a trailing newline would
40
- // otherwise leak an empty line back on re-join).
41
- const BEGIN_DELIMITER_RE = /^BEGIN:/iu;
42
- const END_DELIMITER_RE = /^END:/iu;
43
- const BEGIN_VCALENDAR_RE = /^BEGIN:VCALENDAR\s*$/iu;
44
- const splitCalendar = (ical) => {
45
- const header = [];
46
- const components = [];
47
- let current = null;
48
- let depth = 0;
49
- for (const line of ical.split(LINE_RE)) {
50
- if (line === "") {
51
- continue;
52
- }
53
- // Component names are case-insensitive (RFC 5545 §3.1) and some producers
54
- // write them in lowercase; `name` is normalized to uppercase so every
55
- // `c.name === 'VEVENT'` check below sees them.
56
- if (current) {
57
- current.lines.push(line);
58
- if (BEGIN_DELIMITER_RE.test(line)) {
59
- depth += 1;
60
- }
61
- else if (END_DELIMITER_RE.test(line)) {
62
- depth -= 1;
63
- if (depth === 0) {
64
- components.push(current);
65
- current = null;
66
- }
67
- }
68
- continue;
69
- }
70
- if (BEGIN_DELIMITER_RE.test(line) && !BEGIN_VCALENDAR_RE.test(line)) {
71
- current = {
72
- lines: [line],
73
- name: line.slice("BEGIN:".length).trim().toUpperCase(),
74
- };
75
- depth = 1;
76
- continue;
77
- }
78
- header.push(line);
79
- }
80
- return { components, header };
81
- };
82
- // The RECURRENCE-ID of a component as an epoch-ms instant, or null when it has
83
- // none (the master) or the value can't be parsed. Comparison is by instant so
84
- // overrides dedup even when serialized with `TZID` wall-clock digits.
85
- const recurrenceIdMs = (component) => {
86
- for (const line of component.lines) {
87
- const match = RECURRENCE_ID_RE.exec(line);
88
- if (match) {
89
- const iso = icalDateToIso((match[1] ?? "").trim());
90
- const timeZone = TZID_RE.exec(line)?.[1]?.replace(/^"|"$/gu, "");
91
- const ms = timeZone && !iso.endsWith("Z")
92
- ? parseWallClockInZone(iso, timeZone).getTime()
93
- : Date.parse(iso);
94
- return Number.isNaN(ms) ? null : ms;
95
- }
96
- }
97
- return null;
98
- };
99
- // Pulls the sole VEVENT out of a freshly built override VCALENDAR (buildInvite
100
- // output). It always contains exactly one; anything else is a programmer error.
101
- const overrideVevent = (override) => {
102
- const vevent = override.components.find((c) => c.name === "VEVENT");
103
- if (!vevent) {
104
- throw new Error("override iCalendar has no VEVENT");
105
- }
106
- return vevent;
107
- };
108
- // The start of an ATTENDEE content line. Only a physical line's start matches —
109
- // folded continuations keep their leading space and never do.
110
- const ATTENDEE_LINE_RE = /^ATTENDEE[;:]/iu;
111
- // Only the VEVENT's own ATTENDEE lines count: an EMAIL VALARM carries its
112
- // recipient as an ATTENDEE too, and that is no one to schedule.
113
- const veventHasAttendee = (lines) => {
114
- let depth = 0;
115
- for (const line of lines) {
116
- if (BEGIN_DELIMITER_RE.test(line)) {
117
- depth += 1;
118
- }
119
- else if (END_DELIMITER_RE.test(line)) {
120
- depth -= 1;
121
- }
122
- else if (depth === 1 && ATTENDEE_LINE_RE.test(line)) {
123
- return true;
124
- }
125
- }
126
- return false;
127
- };
128
- const hasAttendee = (components) => components.some((c) => c.name === "VEVENT" && veventHasAttendee(c.lines));
129
- // Re-emits the calendar-level property block (everything before END:VCALENDAR).
130
- // METHOD:REQUEST is forced when the object still names an attendee: stored
131
- // objects usually carry no METHOD, and a stray METHOD:PUBLISH/CANCEL would keep
132
- // Stalwart from scheduling the iMIP update we're issuing. With zero ATTENDEEs
133
- // there is nobody to schedule — and RFC 5546 forbids a REQUEST without one — so
134
- // any METHOD is dropped instead (mirrors buildInvite for personal events).
135
- const calendarPropertyLines = (header, components) => {
136
- const [begin = "BEGIN:VCALENDAR", ...rest] = header
137
- .slice(0, -1)
138
- .filter((l) => !METHOD_RE.test(l));
139
- return hasAttendee(components)
140
- ? [begin, "METHOD:REQUEST", ...rest]
141
- : [begin, ...rest];
142
- };
143
- const componentKey = (component) => {
144
- if (component.name === "VTIMEZONE") {
145
- const tzid = component.lines.find((line) => VTIMEZONE_TZID_RE.test(line));
146
- return `VTIMEZONE:${VTIMEZONE_TZID_RE.exec(tzid ?? "")?.[1] ?? ""}`;
147
- }
148
- return `${component.name}:${component.lines.join("\n")}`;
149
- };
150
- // Merges `overrideIcal`'s VEVENT into the stored `masterIcal`, returning the
151
- // combined VCALENDAR to PUT back. The master and every unrelated occurrence are
152
- // preserved verbatim (only the line endings are normalized to CRLF); any prior
153
- // override for the same instant is replaced so the object never carries two
154
- // VEVENTs with the same RECURRENCE-ID; and a METHOD:REQUEST is guaranteed on
155
- // the result whenever it still names an attendee — stored objects may drop it,
156
- // but it's what triggers Stalwart's scheduling. An attendee-less (personal)
157
- // series gets no METHOD at all (see calendarPropertyLines).
158
- export const spliceOccurrenceOverride = (masterIcal, overrideIcal, recurrenceId) => {
159
- const master = splitCalendar(masterIcal);
160
- const override = splitCalendar(overrideIcal);
161
- const overrideEvent = overrideVevent(override);
162
- const targetMs = new Date(recurrenceId).getTime();
163
- const kept = master.components.filter((c) => !(c.name === "VEVENT" && recurrenceIdMs(c) === targetMs));
164
- const keptKeys = new Set(kept.map(componentKey));
165
- const missingOverrideComponents = override.components.filter((c) => c.name !== "VEVENT" && !keptKeys.has(componentKey(c)));
166
- const components = [...kept, ...missingOverrideComponents, overrideEvent];
167
- const orderedComponents = [
168
- ...components.filter((c) => c.name !== "VEVENT"),
169
- ...components.filter((c) => c.name === "VEVENT"),
170
- ];
171
- // The header's last line is END:VCALENDAR; everything before it is the
172
- // calendar-level property block we re-emit (with METHOD handled there).
173
- const end = master.header.at(-1) ?? "END:VCALENDAR";
174
- const head = calendarPropertyLines(master.header, orderedComponents);
175
- return ([...head, ...orderedComponents.flatMap((c) => c.lines), end].join(CRLF) +
176
- CRLF);
177
- };
178
- // The master VEVENT of a recurring object carries the RRULE and is not itself an
179
- // override (no RECURRENCE-ID) — RFC 5545 §3.8.4.4. Both conditions matter: an
180
- // EXDATE only excludes instances of a component that actually has the RRULE, so
181
- // the target must be the rule-bearing VEVENT, never a stray or an override.
182
- const isMaster = (component) => component.name === "VEVENT" &&
183
- recurrenceIdMs(component) === null &&
184
- component.lines.some((l) => RRULE_RE.test(l));
185
- // A component's physical lines with RFC 5545 folds joined back into logical
186
- // lines, for reading. (Splices keep writing `lines` verbatim.)
187
- const unfoldLines = (lines) => lines.reduce((acc, line) => {
188
- if ((line.startsWith(" ") || line.startsWith("\t")) && acc.length > 0) {
189
- acc[acc.length - 1] += line.slice(1);
190
- }
191
- else {
192
- acc.push(line);
193
- }
194
- return acc;
195
- }, []);
196
- // True when the master already carries an EXDATE for `targetMs`. Comparison is
197
- // by instant (same UTC invariant as recurrenceIdMs) so a re-cancel is detected
198
- // regardless of value formatting. EXDATE is multi-valued (RFC 5545 §3.8.5.1),
199
- // so each comma-separated instant on the logical line is checked.
200
- const masterExcludes = (master, targetMs) => {
201
- for (const line of unfoldLines(master.lines)) {
202
- const match = EXDATE_RE.exec(line);
203
- if (!match) {
204
- continue;
205
- }
206
- // A TZID-qualified value is wall clock in that zone (same resolution as
207
- // recurrenceIdMs); without it `Date.parse` would read it as local time.
208
- const timeZone = TZID_RE.exec(line.slice(0, line.indexOf(":")))?.[1]?.replace(/^"|"$/gu, "");
209
- for (const value of (match[1] ?? "").split(",")) {
210
- const iso = icalDateToIso(value.trim());
211
- const ms = timeZone && iso.includes("T") && !iso.endsWith("Z")
212
- ? parseWallClockInZone(iso, timeZone).getTime()
213
- : Date.parse(iso);
214
- if (!Number.isNaN(ms) && ms === targetMs) {
215
- return true;
216
- }
217
- }
218
- }
219
- return false;
220
- };
221
- // The TZID of the master's DTSTART, or undefined for a UTC (or DATE) start.
222
- // The VEVENT's own DTSTART precedes any VALARM (RFC 5545 §3.6.1), so the first
223
- // match is the right one.
224
- const startTimeZone = (master) => {
225
- const params = unfoldLines(master.lines)
226
- .map((line) => DTSTART_RE.exec(line))
227
- .find((match) => match !== null)?.[1];
228
- return params ? TZID_RE.exec(params)?.[1]?.replace(/^"|"$/gu, "") : undefined;
229
- };
230
- // The EXDATE naming `recurrenceId` in the master DTSTART's own form (RFC 5545
231
- // §3.8.5.1): a DATE for an all-day series, zone wall clock for a TZID start
232
- // (the RRULE expands on that wall clock, so a UTC value may match no
233
- // occurrence), else UTC. The TZID is written as stored, so it names the
234
- // object's own VTIMEZONE; a Windows name's wall clock is computed in its IANA
235
- // zone (toZonedDate). delete_calendar_event refuses a series whose TZID is
236
- // neither before it gets here (see seriesTimeZone); the UTC fallback for such a
237
- // TZID only keeps this pure function from emitting a NaN wall clock.
238
- const exdateLine = (master, recurrenceId, allDay) => {
239
- if (allDay) {
240
- return `EXDATE;VALUE=DATE:${toIcalUtc(recurrenceId).slice(0, 8)}`;
241
- }
242
- const instant = new Date(recurrenceId);
243
- const timeZone = startTimeZone(master);
244
- if (!timeZone || Number.isNaN(toZonedDate(instant, timeZone).getTime())) {
245
- return `EXDATE:${toIcalUtc(recurrenceId)}`;
246
- }
247
- const wallClock = toWallClockIso(instant, timeZone).replaceAll(/[-:]/gu, "");
248
- return `EXDATE;TZID=${timeZone}:${wallClock}`;
249
- };
250
- // Rewrites the master's lines to exclude one instant: replace its SEQUENCE line
251
- // with the bumped value (or add one when the master carried none) and splice the
252
- // EXDATE in just before END:VEVENT. Every other line is preserved verbatim.
253
- const excludeInstant = (lines, exdate, sequence) => {
254
- let sequenceSeen = false;
255
- const rewritten = lines.map((line) => {
256
- if (SEQUENCE_RE.test(line)) {
257
- sequenceSeen = true;
258
- return `SEQUENCE:${sequence}`;
259
- }
260
- return line;
261
- });
262
- // splitCalendar keeps the component BEGIN/END inclusive. Insert the new
263
- // content lines before the first sub-component (e.g. a VALARM), else before
264
- // END:VEVENT: RFC 5545 §3.6.1 puts a VEVENT's properties before its alarms.
265
- const firstNested = rewritten.findIndex((line, i) => i > 0 && BEGIN_DELIMITER_RE.test(line));
266
- const at = firstNested === -1 ? rewritten.length - 1 : firstNested;
267
- const inserts = sequenceSeen ? [exdate] : [`SEQUENCE:${sequence}`, exdate];
268
- return [...rewritten.slice(0, at), ...inserts, ...rewritten.slice(at)];
269
- };
270
- // Removes a single occurrence from a stored recurring object by excluding its
271
- // instant on the master, returning the combined VCALENDAR to PUT back. The
272
- // master keeps its RRULE and every unrelated occurrence verbatim (only line
273
- // endings normalize to CRLF); a new EXDATE names the cancelled instant and the
274
- // master's SEQUENCE bumps past every SEQUENCE in the object so attendee clients
275
- // treat the re-scheduled series as newer and re-apply it — dropping just that
276
- // instance (RFC 5546; Stalwart delivers the exclusion as an updated-series
277
- // REQUEST carrying the EXDATE, not a per-instance CANCEL); any override VEVENT
278
- // for the same instant is dropped so no orphan dangles beside the EXDATE; and a
279
- // METHOD:REQUEST is guaranteed whenever the object still names an attendee —
280
- // what triggers Stalwart's scheduling on PUT (an attendee-less personal series
281
- // gets no METHOD; see calendarPropertyLines).
282
- //
283
- // Idempotent: if the master already excludes the instant (a double-cancel), the
284
- // input is returned unchanged so the caller can skip the PUT (no scheduling diff)
285
- // while still reporting success.
286
- // `allDay` marks a master whose DTSTART is a DATE: the EXDATE must then be a
287
- // DATE too (RFC 5545 §3.8.5.1 — the value type of DTSTART).
288
- export const spliceOccurrenceCancellation = (masterIcal, recurrenceId, allDay = false) => {
289
- const calendar = splitCalendar(masterIcal);
290
- const targetMs = new Date(recurrenceId).getTime();
291
- // The caller only reaches here after confirming the object is a recurring
292
- // series, so a missing rule-bearing master is a real invariant violation.
293
- // Surface it loudly rather than PUT an object with no EXDATE added and falsely
294
- // report the occurrence cancelled (same fail-loud stance as overrideVevent).
295
- const master = calendar.components.find(isMaster);
296
- if (!master) {
297
- throw new Error("spliceOccurrenceCancellation: no recurring master VEVENT (one with an RRULE) found");
298
- }
299
- if (masterExcludes(master, targetMs)) {
300
- return masterIcal;
301
- }
302
- const sequence = maxSequence(masterIcal) + 1;
303
- const exdate = exdateLine(master, recurrenceId, allDay);
304
- const components = calendar.components
305
- // Drop any prior override for the cancelled instant.
306
- .filter((c) => !(c.name === "VEVENT" && recurrenceIdMs(c) === targetMs))
307
- // Exclude the instant on the master (identity compare — master survives the
308
- // filter above, since its recurrenceIdMs is null, not targetMs).
309
- .map((c) => c === master
310
- ? { ...c, lines: excludeInstant(c.lines, exdate, sequence) }
311
- : c);
312
- const end = calendar.header.at(-1) ?? "END:VCALENDAR";
313
- const head = calendarPropertyLines(calendar.header, components);
314
- return ([...head, ...components.flatMap((c) => c.lines), end].join(CRLF) + CRLF);
315
- };
316
- const BEGIN_VALARM_RE = /^BEGIN:VALARM\s*$/iu;
317
- const SUMMARY_LINE_RE = /^SUMMARY(?:;[^:]*)?:(.*)$/iu;
318
- // A VEVENT's lines with every top-level VALARM removed, and its SUMMARY value
319
- // (still TEXT-escaped, folds joined) for the replacement alarm's DESCRIPTION.
320
- // Both are TEXT, so the escaped value is copied as is — escaping it again
321
- // would double every backslash.
322
- const stripAlarms = (lines) => {
323
- const kept = [];
324
- let summary = "";
325
- let depth = 0;
326
- let skipping = false;
327
- let inSummary = false;
328
- for (const line of lines) {
329
- if (inSummary && (line.startsWith(" ") || line.startsWith("\t"))) {
330
- summary += line.slice(1);
331
- kept.push(line);
332
- continue;
333
- }
334
- inSummary = false;
335
- if (BEGIN_DELIMITER_RE.test(line)) {
336
- depth += 1;
337
- skipping ||= depth === 2 && BEGIN_VALARM_RE.test(line);
338
- }
339
- if (!skipping) {
340
- kept.push(line);
341
- const match = depth === 1 ? SUMMARY_LINE_RE.exec(line) : null;
342
- if (match) {
343
- summary = match[1] ?? "";
344
- inSummary = true;
345
- }
346
- }
347
- if (END_DELIMITER_RE.test(line)) {
348
- depth -= 1;
349
- skipping &&= depth >= 2;
350
- }
351
- }
352
- return { kept, summary };
353
- };
354
- // Replaces the reminders on every VEVENT of a stored object — the master and
355
- // any overrides — with one DISPLAY alarm `minutesBefore` the start, or none
356
- // when `minutesBefore` is null. With `recurrenceId`, only the override for that
357
- // instant is touched. Every other line is kept verbatim: no SEQUENCE
358
- // bump, no rebuilt ATTENDEEs, so attendee responses survive and nobody is
359
- // re-invited over what is the organizer's own reminder.
360
- //
361
- // Throws when the object holds no VEVENT: returning it unchanged would let the
362
- // caller report a reminder change that never happened (same stance as
363
- // spliceOccurrenceCancellation).
364
- export const spliceAlarms = (ical, minutesBefore, recurrenceId) => {
365
- const calendar = splitCalendar(ical);
366
- const targetMs = recurrenceId === undefined ? undefined : new Date(recurrenceId).getTime();
367
- const isTarget = (c) => c.name === "VEVENT" &&
368
- (targetMs === undefined || recurrenceIdMs(c) === targetMs);
369
- if (!calendar.components.some(isTarget)) {
370
- throw new Error("spliceAlarms: no matching VEVENT found");
371
- }
372
- // An override may omit SUMMARY (a foreign client's minimal override); its
373
- // alarm then takes the series title from the master rather than "Reminder".
374
- const masterComponent = calendar.components.find((c) => c.name === "VEVENT" && recurrenceIdMs(c) === null);
375
- const seriesTitle = masterComponent
376
- ? stripAlarms(masterComponent.lines).summary
377
- : "";
378
- const components = calendar.components.map((c) => {
379
- if (!isTarget(c)) {
380
- return c;
381
- }
382
- const { kept, summary } = stripAlarms(c.lines);
383
- if (minutesBefore === null) {
384
- return { ...c, lines: kept };
385
- }
386
- const alarm = [
387
- "BEGIN:VALARM",
388
- "ACTION:DISPLAY",
389
- `TRIGGER:${minutesBefore === 0 ? "PT0S" : `-PT${minutesBefore}M`}`,
390
- `DESCRIPTION:${summary || seriesTitle || "Reminder"}`,
391
- "END:VALARM",
392
- ].map(foldLine);
393
- return { ...c, lines: [...kept.slice(0, -1), ...alarm, ...kept.slice(-1)] };
394
- });
395
- const end = calendar.header.at(-1) ?? "END:VCALENDAR";
396
- return ([
397
- ...calendar.header.slice(0, -1),
398
- ...components.flatMap((c) => c.lines),
399
- end,
400
- ].join(CRLF) + CRLF);
401
- };
402
- // Properties an edit writes itself (through buildInvite) or decides, so a
403
- // stored copy must never be carried across: it would duplicate the built one
404
- // or contradict the edit (a DURATION beside the new DTEND, an all-day marker
405
- // on an event made timed, a stale LAST-MODIFIED). RRULE and EXRULE belong to
406
- // the recurrence the edit resolves; RDATE is decided per edit (see
407
- // CarryOptions.replaced).
408
- const EDIT_OWNED_PROPERTIES = new Set([
409
- "ATTENDEE",
410
- "DESCRIPTION",
411
- "DTEND",
412
- "DTSTAMP",
413
- "DTSTART",
414
- "DURATION",
415
- "EXDATE",
416
- "EXRULE",
417
- "LAST-MODIFIED",
418
- "LOCATION",
419
- "ORGANIZER",
420
- "RECURRENCE-ID",
421
- "REQUEST-STATUS",
422
- "RRULE",
423
- "SEQUENCE",
424
- "SUMMARY",
425
- "UID",
426
- "X-MICROSOFT-CDO-ALLDAYEVENT",
427
- "X-MICROSOFT-MSNCALENDAR-ALLDAYEVENT",
428
- ]);
429
- const PROPERTY_NAME_RE = /^([^;:]+)/u;
430
- const propertyName = (line) => PROPERTY_NAME_RE.exec(line)?.[1]?.trim().toUpperCase() ?? "";
431
- // A VEVENT's own (depth 1) properties, each as its physical lines (the first
432
- // line plus its folded continuations), in source order. Sub-components such
433
- // as VALARM are left out.
434
- const topLevelProperties = (lines) => {
435
- const properties = [];
436
- let depth = 0;
437
- for (const line of lines) {
438
- if (BEGIN_DELIMITER_RE.test(line)) {
439
- depth += 1;
440
- continue;
441
- }
442
- if (END_DELIMITER_RE.test(line)) {
443
- depth -= 1;
444
- continue;
445
- }
446
- if (depth !== 1) {
447
- continue;
448
- }
449
- const last = properties.at(-1);
450
- if ((line.startsWith(" ") || line.startsWith("\t")) && last) {
451
- last.lines.push(line);
452
- }
453
- else {
454
- properties.push({ lines: [line], name: propertyName(line) });
455
- }
456
- }
457
- return properties;
458
- };
459
- // The TZIDs a carried property's parameters name (e.g. a DTSTART-like X-
460
- // property, or an RDATE), so their VTIMEZONEs can come along.
461
- const TZID_PARAM_RE = /;TZID=("[^"]*"|[^;:]*)/giu;
462
- const referencedZones = (lines) => {
463
- const unfolded = unfoldLines(lines)[0] ?? "";
464
- const params = unfolded.slice(0, unfolded.indexOf(":") === -1 ? undefined : unfolded.indexOf(":"));
465
- return [...params.matchAll(TZID_PARAM_RE)].map((m) => (m[1] ?? "").replace(/^"|"$/gu, ""));
466
- };
467
- // Carries every property of the stored VEVENT that the freshly built one does
468
- // not set onto it: CATEGORIES, CLASS, URL, TRANSP, STATUS, X- properties and
469
- // whatever else the builder doesn't model, so an edit changes only what the
470
- // caller asked for. Stored lines are copied verbatim (folds included) and go
471
- // before the built VEVENT's first sub-component, after its own properties; a
472
- // VTIMEZONE a carried property names comes along when the built object lacks
473
- // it. `built` is buildInvite output: one VEVENT.
474
- export const carryStoredProperties = (built, storedIcal, options = {}) => {
475
- const target = splitCalendar(built);
476
- const stored = splitCalendar(storedIcal);
477
- const builtEvent = overrideVevent(target);
478
- const source = storedSource(stored.components, options.recurrenceId);
479
- if (!source) {
480
- return built;
481
- }
482
- const builtNames = new Set(topLevelProperties(builtEvent.lines).map((p) => p.name));
483
- const replaced = options.replaced ?? [];
484
- const isReplaced = (name) => replaced.some((r) => r.endsWith("*") ? name.startsWith(r.slice(0, -1)) : name === r);
485
- const carried = topLevelProperties(source.lines).filter((p) => p.name !== "" &&
486
- !EDIT_OWNED_PROPERTIES.has(p.name) &&
487
- !builtNames.has(p.name) &&
488
- !isReplaced(p.name));
489
- if (carried.length === 0) {
490
- return built;
491
- }
492
- const firstNested = builtEvent.lines.findIndex((line, i) => i > 0 && BEGIN_DELIMITER_RE.test(line));
493
- const at = firstNested === -1 ? builtEvent.lines.length - 1 : firstNested;
494
- const patchedEvent = {
495
- ...builtEvent,
496
- lines: [
497
- ...builtEvent.lines.slice(0, at),
498
- ...carried.flatMap((p) => p.lines),
499
- ...builtEvent.lines.slice(at),
500
- ],
501
- };
502
- const builtZones = new Set(target.components.filter((c) => c.name === "VTIMEZONE").map(componentKey));
503
- const zones = [...new Set(carried.flatMap((p) => referencedZones(p.lines)))]
504
- .map((tzid) => stored.components.find((c) => componentKey(c) === `VTIMEZONE:${tzid}`))
505
- .filter((c) => c !== undefined && !builtZones.has(componentKey(c)));
506
- const components = [
507
- ...target.components.filter((c) => c.name !== "VEVENT"),
508
- ...zones,
509
- ...target.components
510
- .filter((c) => c.name === "VEVENT")
511
- .map((c) => (c === builtEvent ? patchedEvent : c)),
512
- ];
513
- const end = target.header.at(-1) ?? "END:VCALENDAR";
514
- return ([
515
- ...target.header.slice(0, -1),
516
- ...components.flatMap((c) => c.lines),
517
- end,
518
- ].join(CRLF) + CRLF);
519
- };
520
- // The stored VEVENT whose properties an edit keeps: the override for
521
- // `recurrenceId` if there is one, else the master (no RECURRENCE-ID), else —
522
- // an object holding a single invited instance — the only VEVENT.
523
- const storedSource = (components, recurrenceId) => {
524
- const events = components.filter((c) => c.name === "VEVENT");
525
- if (recurrenceId !== undefined) {
526
- const targetMs = new Date(recurrenceId).getTime();
527
- const override = events.find((c) => recurrenceIdMs(c) === targetMs);
528
- if (override) {
529
- return override;
530
- }
531
- }
532
- return (events.find((c) => recurrenceIdMs(c) === null) ??
533
- (events.length === 1 ? events[0] : undefined));
534
- };