@wtfalch/calendar 0.1.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 (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +15 -0
  3. package/dist/calendar/calendar-client.d.ts +7 -0
  4. package/dist/calendar/calendar-client.js +242 -0
  5. package/dist/calendar/calendar.css +953 -0
  6. package/dist/calendar/client.d.ts +87 -0
  7. package/dist/calendar/client.js +233 -0
  8. package/dist/calendar/errors.d.ts +28 -0
  9. package/dist/calendar/errors.js +61 -0
  10. package/dist/calendar/fake/index.d.ts +36 -0
  11. package/dist/calendar/fake/index.js +79 -0
  12. package/dist/calendar/fake/sample.d.ts +66 -0
  13. package/dist/calendar/fake/sample.js +116 -0
  14. package/dist/calendar/fake/store.d.ts +79 -0
  15. package/dist/calendar/fake/store.js +906 -0
  16. package/dist/calendar/index.d.ts +12 -0
  17. package/dist/calendar/index.js +11 -0
  18. package/dist/calendar/push.d.ts +38 -0
  19. package/dist/calendar/push.js +129 -0
  20. package/dist/calendar/react/AvailabilityRibbon.d.ts +40 -0
  21. package/dist/calendar/react/AvailabilityRibbon.js +108 -0
  22. package/dist/calendar/react/Calendar.d.ts +28 -0
  23. package/dist/calendar/react/Calendar.js +431 -0
  24. package/dist/calendar/react/EventDetail.d.ts +22 -0
  25. package/dist/calendar/react/EventDetail.js +91 -0
  26. package/dist/calendar/react/EventEditor.d.ts +52 -0
  27. package/dist/calendar/react/EventEditor.js +188 -0
  28. package/dist/calendar/react/ShareDialog.d.ts +25 -0
  29. package/dist/calendar/react/ShareDialog.js +125 -0
  30. package/dist/calendar/react/Toolbar.d.ts +29 -0
  31. package/dist/calendar/react/Toolbar.js +58 -0
  32. package/dist/calendar/react/index.d.ts +9 -0
  33. package/dist/calendar/react/index.js +8 -0
  34. package/dist/calendar/react/participants.d.ts +34 -0
  35. package/dist/calendar/react/participants.js +40 -0
  36. package/dist/calendar/types.d.ts +384 -0
  37. package/dist/calendar/types.js +40 -0
  38. package/dist/calendar/uri.d.ts +13 -0
  39. package/dist/calendar/uri.js +22 -0
  40. package/dist/calendar/wire.d.ts +177 -0
  41. package/dist/calendar/wire.js +349 -0
  42. package/package.json +82 -0
@@ -0,0 +1,906 @@
1
+ /**
2
+ * A calendar universe in memory, and the JMAP that answers questions about
3
+ * it.
4
+ *
5
+ * **A fake transport, not a fake API.** This answers JMAP calls the same way
6
+ * a running Stalwart does, so a component or a client method drawn against
7
+ * this fake is drawn through exactly the code that will face a real server —
8
+ * including the four load-bearing behaviours confirmed live against Stalwart
9
+ * v0.16.20 (https://github.com/wtfalch/messaging/issues/145):
10
+ *
11
+ * 1. `CalendarEvent/query` without `expandRecurrences` returns master
12
+ * events only; with it, and both `after`/`before`, dated occurrences —
13
+ * and with it but no bounds, `invalidArguments`.
14
+ * 2. An invite (`CalendarEvent/set create` with `sendSchedulingMessages`)
15
+ * lands a copy straight in the invitee's own calendar; the invitee's own
16
+ * reply (`update` with `sendSchedulingMessages`) updates every other
17
+ * copy sharing the same `uid`, including the organiser's.
18
+ * 3. A grant written to `Calendar/set update {shareWith}` reads back on the
19
+ * next `Calendar/get`.
20
+ * 4. `Principal/getAvailability` returns busy periods for a calendar shared
21
+ * with at least `mayReadItems` — no second opt-in needed — and an empty
22
+ * list for one shared with nothing at all.
23
+ *
24
+ * It implements only the methods `@wtfalch/calendar` sends. Anything else
25
+ * answers `unknownMethod`, which is what a real server does and what the
26
+ * error path expects.
27
+ *
28
+ * Wire shapes below (`myRights`/`shareWith` as boolean-flag objects, the
29
+ * `calendars`/`calendars:parse` capability strings, the session capability
30
+ * object's field names, `recurrenceRule` singular, `calendarAddress`, the
31
+ * synthetic-occurrence id carrying a `baseEventId`) are grounded in direct
32
+ * evidence from #137/#138/#145 rather than guessed; the wire's own method-arg
33
+ * shapes for bounds and `expandRecurrences` are accepted in more than one
34
+ * place (see `firstString`) since this package's own client, built alongside
35
+ * this fake rather than before it, has not settled which one it sends.
36
+ */
37
+ import { ME, OTHER_PRINCIPALS } from "./sample.js";
38
+ /** Every right `Calendar.myRights`/`shareWith` can carry (#138 §1). */
39
+ const RIGHTS = [
40
+ 'mayReadFreeBusy',
41
+ 'mayReadItems',
42
+ 'mayWriteAll',
43
+ 'mayWriteOwn',
44
+ 'mayUpdatePrivate',
45
+ 'mayRSVP',
46
+ 'mayShare',
47
+ 'mayDelete',
48
+ ];
49
+ const ALL_RIGHTS = Object.fromEntries(RIGHTS.map((right) => [right, true]));
50
+ /** `shareWith`'s grantee objects on the wire, echoed back the way the real
51
+ * server does it: all eight rights, every one an explicit boolean, not just
52
+ * the ones actually granted (#145's second run, `wire-live-transcript.test.ts`'s
53
+ * `LIVE_SHARE_GRANTED`). This fake's own storage keeps only the true
54
+ * entries (`calendar.shareWith[grantee]`), so this fills the other six in
55
+ * as `false` on the way out -- the fake must not be kinder than the
56
+ * server. */
57
+ function fullRightsEcho(rights) {
58
+ return Object.fromEntries(RIGHTS.map((right) => [right, rights[right] === true]));
59
+ }
60
+ const OCCURRENCE_SEPARATOR = '~';
61
+ const MAX_OCCURRENCES = 1_000;
62
+ function occurrenceId(masterId, date) {
63
+ return `${masterId}${OCCURRENCE_SEPARATOR}${date.toISOString()}`;
64
+ }
65
+ function splitOccurrenceId(id) {
66
+ const index = id.indexOf(OCCURRENCE_SEPARATOR);
67
+ if (index === -1)
68
+ return null;
69
+ return { masterId: id.slice(0, index), iso: id.slice(index + OCCURRENCE_SEPARATOR.length) };
70
+ }
71
+ function toDuration(minutes) {
72
+ if (minutes > 0 && minutes % 60 === 0)
73
+ return `PT${minutes / 60}H`;
74
+ return `PT${minutes}M`;
75
+ }
76
+ /** The inverse of `toDuration`, for the little arithmetic `PT1H30M`-shaped
77
+ * durations need. Anything it cannot parse is treated as zero-length,
78
+ * which is a fake's business, not a real server's. */
79
+ function minutesFromDuration(duration) {
80
+ const match = /^PT(?:(\d+)H)?(?:(\d+)M)?$/.exec(duration);
81
+ const hours = Number(match?.[1] ?? 0);
82
+ const minutes = Number(match?.[2] ?? 0);
83
+ return hours * 60 + minutes;
84
+ }
85
+ function advance(date, frequency, interval) {
86
+ const next = new Date(date);
87
+ if (frequency === 'daily')
88
+ next.setUTCDate(next.getUTCDate() + interval);
89
+ else if (frequency === 'weekly')
90
+ next.setUTCDate(next.getUTCDate() + 7 * interval);
91
+ else if (frequency === 'monthly')
92
+ next.setUTCMonth(next.getUTCMonth() + interval);
93
+ else
94
+ next.setUTCFullYear(next.getUTCFullYear() + interval);
95
+ return next;
96
+ }
97
+ /** Every occurrence start in `[rangeAfter, rangeBefore)`, expanding
98
+ * server-side exactly as real Stalwart does (#137 "Recurrence") — this
99
+ * package's own client never expands a rule itself. Capped, so a rule with
100
+ * no `count`/`until` and a distant `rangeBefore` cannot loop forever. */
101
+ function occurrenceStarts(seriesStart, rule, rangeAfter, rangeBefore) {
102
+ const interval = rule.interval ?? 1;
103
+ const until = rule.until ? new Date(rule.until) : null;
104
+ const starts = [];
105
+ let current = seriesStart;
106
+ for (let index = 0; index < MAX_OCCURRENCES; index++) {
107
+ if (until && current > until)
108
+ break;
109
+ if (rule.count !== undefined && index >= rule.count)
110
+ break;
111
+ if (current >= rangeBefore)
112
+ break;
113
+ if (current >= rangeAfter)
114
+ starts.push(current);
115
+ current = advance(current, rule.frequency, interval);
116
+ }
117
+ return starts;
118
+ }
119
+ function firstString(...values) {
120
+ for (const value of values)
121
+ if (typeof value === 'string')
122
+ return value;
123
+ return undefined;
124
+ }
125
+ function slug(calendarAddress) {
126
+ return calendarAddress.split('@')[0] || calendarAddress;
127
+ }
128
+ /** `wire.ts`'s `locationToWire` shape: a map of `Location` objects, keyed
129
+ * arbitrarily, of which this fake — like the real client's own
130
+ * `locationFromWire` — only ever reads the first `name`. */
131
+ function firstLocationName(locations) {
132
+ if (!locations || typeof locations !== 'object')
133
+ return undefined;
134
+ const first = Object.values(locations)[0];
135
+ return typeof first?.name === 'string' ? first.name : undefined;
136
+ }
137
+ function locationToWireMap(location) {
138
+ return location === undefined ? null : { main: { '@type': 'Location', name: location } };
139
+ }
140
+ function rolesToMap(roles) {
141
+ if (!roles)
142
+ return undefined;
143
+ if (Array.isArray(roles))
144
+ return Object.fromEntries(roles.map((role) => [String(role), true]));
145
+ return Object.fromEntries(Object.entries(roles)
146
+ .filter(([, value]) => value === true)
147
+ .map(([key]) => [key, true]));
148
+ }
149
+ /** Accepts either the client-level array shape or a wire-level map keyed by
150
+ * an arbitrary id, mirroring how the live transcript itself chose the key
151
+ * `"bob"` for bob's own entry (#145) — this fake does not assume the
152
+ * concurrently-built client picks the same one every time. */
153
+ function normalizeParticipants(input) {
154
+ if (!input)
155
+ return undefined;
156
+ const entries = Array.isArray(input)
157
+ ? input.map((item) => [undefined, item])
158
+ : Object.entries(input).map(([key, value]) => [
159
+ key,
160
+ value,
161
+ ]);
162
+ const out = {};
163
+ for (const [key, participant] of entries) {
164
+ const calendarAddress = String(participant.calendarAddress ?? '');
165
+ if (!calendarAddress)
166
+ continue;
167
+ const id = key ?? slug(calendarAddress);
168
+ out[id] = {
169
+ calendarAddress,
170
+ name: typeof participant.name === 'string' ? participant.name : undefined,
171
+ roles: rolesToMap(participant.roles),
172
+ participationStatus: participant.participationStatus,
173
+ };
174
+ }
175
+ return out;
176
+ }
177
+ /** RFC 6901 §3, for a result reference's path only — none of this fake's own
178
+ * patch paths need unescaping, since none of its ids ever contain `~`. */
179
+ function unpointer(segment) {
180
+ return segment.replaceAll('~1', '/').replaceAll('~0', '~');
181
+ }
182
+ function pointer(value, path) {
183
+ let current = value;
184
+ for (const rawSegment of path.split('/').filter(Boolean)) {
185
+ const segment = unpointer(rawSegment);
186
+ if (segment === '*') {
187
+ if (!Array.isArray(current))
188
+ return [];
189
+ const rest = path.slice(path.indexOf('*') + 1);
190
+ return current.flatMap((item) => pointer(item, rest));
191
+ }
192
+ if (Array.isArray(current))
193
+ current = current[Number(segment)];
194
+ else if (current && typeof current === 'object')
195
+ current = current[segment];
196
+ else
197
+ return undefined;
198
+ }
199
+ return current;
200
+ }
201
+ const ERROR_TYPES = new Set(['invalidArguments', 'unknownMethod']);
202
+ export class FakeCalendarStore {
203
+ me;
204
+ #now;
205
+ #latency;
206
+ #counter = 0;
207
+ #accounts = new Map();
208
+ #emailToAccountId = new Map();
209
+ /** Every seeded principal, by account id -- what `Principal/get` answers
210
+ * from, seeded the same run `#seed` builds the account buckets from. */
211
+ #principals = new Map();
212
+ /** Every invite `CalendarEvent/set create` landed in someone else's
213
+ * calendar, for a test that asserts the invite actually reached them
214
+ * rather than only that the call succeeded. */
215
+ invitesSent = [];
216
+ /** Every reply that propagated a participant-status change to another
217
+ * copy of the same event. */
218
+ repliesSent = [];
219
+ constructor(options = {}) {
220
+ this.me = options.me ?? ME;
221
+ this.#now = options.now ?? new Date('2026-09-17T09:00:00Z');
222
+ this.#latency = options.latency ?? 0;
223
+ for (const principal of [this.me, ...(options.otherPrincipals ?? OTHER_PRINCIPALS)]) {
224
+ this.#seed(principal);
225
+ }
226
+ }
227
+ #seed(principal) {
228
+ const bucket = { calendars: new Map(), events: new Map() };
229
+ for (const seedCalendar of principal.calendars) {
230
+ bucket.calendars.set(seedCalendar.id, {
231
+ id: seedCalendar.id,
232
+ name: seedCalendar.name,
233
+ description: seedCalendar.description,
234
+ color: seedCalendar.color,
235
+ isVisible: seedCalendar.isVisible ?? true,
236
+ includeInAvailability: seedCalendar.includeInAvailability ?? 'all',
237
+ shareWith: Object.fromEntries(Object.entries(seedCalendar.shareWith ?? {}).map(([accountId, rights]) => [
238
+ accountId,
239
+ Object.fromEntries(rights.map((right) => [right, true])),
240
+ ])),
241
+ });
242
+ for (const seedEvent of seedCalendar.events ?? []) {
243
+ bucket.events.set(seedEvent.uid, {
244
+ id: seedEvent.uid,
245
+ uid: seedEvent.uid,
246
+ calendarIds: { [seedCalendar.id]: true },
247
+ title: seedEvent.title,
248
+ description: seedEvent.description,
249
+ start: new Date(this.#now.getTime() + seedEvent.startOffsetMinutes * 60_000)
250
+ .toISOString()
251
+ .slice(0, 19),
252
+ timeZone: 'UTC',
253
+ duration: toDuration(seedEvent.durationMinutes),
254
+ isAllDay: seedEvent.isAllDay ?? false,
255
+ location: seedEvent.location,
256
+ recurrenceRule: seedEvent.recurrenceRule,
257
+ status: seedEvent.status ?? 'confirmed',
258
+ sequence: 0,
259
+ });
260
+ }
261
+ }
262
+ this.#accounts.set(principal.accountId, bucket);
263
+ this.#emailToAccountId.set(principal.email.toLowerCase(), principal.accountId);
264
+ this.#principals.set(principal.accountId, principal);
265
+ }
266
+ #account(accountId) {
267
+ let bucket = this.#accounts.get(accountId);
268
+ if (!bucket) {
269
+ bucket = { calendars: new Map(), events: new Map() };
270
+ this.#accounts.set(accountId, bucket);
271
+ }
272
+ return bucket;
273
+ }
274
+ /** The session document, as Stalwart writes it. */
275
+ session(origin) {
276
+ const meId = this.me.accountId;
277
+ return {
278
+ capabilities: {
279
+ 'urn:ietf:params:jmap:core': {},
280
+ // Field names confirmed live against Stalwart v0.16.20 (#137).
281
+ 'urn:ietf:params:jmap:calendars': {
282
+ maxCalendarsPerEvent: 1,
283
+ minDateTime: '1900-01-01T00:00:00Z',
284
+ maxDateTime: '2100-01-01T00:00:00Z',
285
+ maxExpandedQueryDuration: 'P400D',
286
+ maxParticipantsPerEvent: 100,
287
+ mayCreateCalendar: true,
288
+ },
289
+ 'urn:ietf:params:jmap:calendars:parse': {},
290
+ },
291
+ accounts: {
292
+ [meId]: {
293
+ name: this.me.email,
294
+ isPersonal: true,
295
+ isReadOnly: false,
296
+ accountCapabilities: {
297
+ 'urn:ietf:params:jmap:calendars': {},
298
+ 'urn:ietf:params:jmap:calendars:parse': {},
299
+ },
300
+ },
301
+ },
302
+ primaryAccounts: {
303
+ 'urn:ietf:params:jmap:calendars': meId,
304
+ 'urn:ietf:params:jmap:calendars:parse': meId,
305
+ },
306
+ username: this.me.email,
307
+ apiUrl: `${origin}/jmap/`,
308
+ downloadUrl: `${origin}/jmap/download/{accountId}/{blobId}/{name}?accept={type}`,
309
+ uploadUrl: `${origin}/jmap/upload/{accountId}/`,
310
+ eventSourceUrl: `${origin}/jmap/eventsource/?types={types}&closeafter={closeafter}&ping={ping}`,
311
+ state: 'fake-session',
312
+ };
313
+ }
314
+ /** Answer one method call. Exported for the transport, and for a test that
315
+ * wants to drive one side of a scheduling exchange directly — the
316
+ * invitee's reply, in particular, since `fakeCalendar()` only ever hands
317
+ * back one `CalendarClient`, for the organiser. */
318
+ call(method, args) {
319
+ switch (method) {
320
+ case 'Calendar/get':
321
+ return this.#calendarGet(args);
322
+ case 'Calendar/set':
323
+ return this.#calendarSet(args);
324
+ case 'CalendarEvent/query':
325
+ return this.#eventQuery(args);
326
+ case 'CalendarEvent/get':
327
+ return this.#eventGet(args);
328
+ case 'CalendarEvent/set':
329
+ return this.#eventSet(args);
330
+ case 'Principal/getAvailability':
331
+ return this.#getAvailability(args);
332
+ case 'Principal/query':
333
+ return this.#principalQuery(args);
334
+ case 'Principal/get':
335
+ return this.#principalGet(args);
336
+ default:
337
+ return {
338
+ type: 'unknownMethod',
339
+ description: `the fake calendar does not implement ${method}`,
340
+ };
341
+ }
342
+ }
343
+ /** `Principal/query` filtered by email. The live server answers at most one
344
+ * id for an address, so this does too, and an address nobody has comes
345
+ * back as an empty list rather than an error (MSG-055 slice 3 plan). Any
346
+ * other filter is unsupported here rather than quietly ignored: a filter
347
+ * the fake pretends to honour is how this package lost two field names. */
348
+ #principalQuery(args) {
349
+ const accountId = String(args.accountId ?? this.me.accountId);
350
+ const filter = (args.filter ?? {});
351
+ const keys = Object.keys(filter);
352
+ if (keys.length !== 1 || keys[0] !== 'email') {
353
+ return {
354
+ type: 'unsupportedFilter',
355
+ description: 'the fake calendar only filters principals by email',
356
+ };
357
+ }
358
+ const id = this.#emailToAccountId.get(String(filter.email).toLowerCase());
359
+ return { accountId, queryState: 'p1', ids: id ? [id] : [] };
360
+ }
361
+ /** `Principal/get`, in the shape the live server sends: `description` is the
362
+ * friendly name and `name` repeats the address (`wire-live-transcript.test.ts`'s
363
+ * `LIVE_PRINCIPALS`). A seed with no name sends `null`, not a fabricated
364
+ * one, so the client's fallback is exercised rather than hidden. */
365
+ #principalGet(args) {
366
+ const accountId = String(args.accountId ?? this.me.accountId);
367
+ const ids = Array.isArray(args.ids) ? args.ids.map(String) : [...this.#principals.keys()];
368
+ const list = [];
369
+ const notFound = [];
370
+ for (const id of ids) {
371
+ const principal = this.#principals.get(id);
372
+ if (!principal) {
373
+ notFound.push(id);
374
+ continue;
375
+ }
376
+ list.push({
377
+ id: principal.accountId,
378
+ type: 'individual',
379
+ name: principal.email,
380
+ description: principal.name ?? null,
381
+ email: principal.email,
382
+ });
383
+ }
384
+ return { accountId, state: 'p1', list, notFound };
385
+ }
386
+ #calendarGet(args) {
387
+ const accountId = String(args.accountId ?? this.me.accountId);
388
+ const account = this.#account(accountId);
389
+ const list = [...account.calendars.values()].map((calendar) => ({
390
+ id: calendar.id,
391
+ name: calendar.name,
392
+ description: calendar.description ?? null,
393
+ color: calendar.color ?? null,
394
+ isVisible: calendar.isVisible,
395
+ includeInAvailability: calendar.includeInAvailability,
396
+ // Every calendar this account's own Calendar/get returns is one it
397
+ // owns, so myRights is always full (#138 §1) — this fake never models
398
+ // a shared calendar surfacing in its owner's own account list.
399
+ myRights: { ...ALL_RIGHTS },
400
+ shareWith: Object.fromEntries(Object.entries(calendar.shareWith).map(([grantee, rights]) => [
401
+ grantee,
402
+ fullRightsEcho(rights),
403
+ ])),
404
+ }));
405
+ return { accountId, state: 'c1', list, notFound: [] };
406
+ }
407
+ /** Only `update` is implemented: `CalendarClient` never creates or
408
+ * destroys a calendar, only shares one via `shareWith` (`types.ts`'s
409
+ * `CalendarClient.shareCalendar`). */
410
+ #calendarSet(args) {
411
+ const accountId = String(args.accountId ?? this.me.accountId);
412
+ const account = this.#account(accountId);
413
+ const update = (args.update ?? {});
414
+ const updated = {};
415
+ const notUpdated = {};
416
+ for (const [id, patch] of Object.entries(update)) {
417
+ const calendar = account.calendars.get(id);
418
+ if (!calendar) {
419
+ notUpdated[id] = { type: 'notFound' };
420
+ continue;
421
+ }
422
+ for (const [path, value] of Object.entries(patch)) {
423
+ if (path === 'shareWith') {
424
+ calendar.shareWith = value;
425
+ }
426
+ else if (path.startsWith('shareWith/')) {
427
+ // Un-escaped, because the client escapes: RFC 6901 order, `~1`
428
+ // before `~0`, or a literal `~1` in an id would decode wrong. No
429
+ // real account id carries either character, but a fake that skips
430
+ // the step is a fake that could disagree with the server without
431
+ // any test noticing.
432
+ const grantee = path
433
+ .slice('shareWith/'.length)
434
+ .replaceAll('~1', '/')
435
+ .replaceAll('~0', '~');
436
+ if (value === null)
437
+ delete calendar.shareWith[grantee];
438
+ else
439
+ calendar.shareWith[grantee] = value;
440
+ }
441
+ else if (path === 'isVisible') {
442
+ calendar.isVisible = Boolean(value);
443
+ }
444
+ else if (path === 'includeInAvailability') {
445
+ calendar.includeInAvailability = value;
446
+ }
447
+ else if (path === 'name') {
448
+ calendar.name = String(value);
449
+ }
450
+ else {
451
+ notUpdated[id] = { type: 'invalidPatch', description: `cannot patch ${path}` };
452
+ }
453
+ }
454
+ if (!notUpdated[id])
455
+ updated[id] = null;
456
+ }
457
+ return {
458
+ accountId,
459
+ oldState: '1',
460
+ newState: '2',
461
+ created: null,
462
+ notCreated: null,
463
+ updated,
464
+ notUpdated: Object.keys(notUpdated).length > 0 ? notUpdated : null,
465
+ };
466
+ }
467
+ #eventQuery(args) {
468
+ const accountId = String(args.accountId ?? this.me.accountId);
469
+ const account = this.#account(accountId);
470
+ const filter = (args.filter ?? {});
471
+ const expand = args.expandRecurrences === true || filter.expandRecurrences === true;
472
+ const after = firstString(args.after, filter.after);
473
+ const before = firstString(args.before, filter.before);
474
+ if (expand) {
475
+ if (!after || !before) {
476
+ return {
477
+ type: 'invalidArguments',
478
+ description: 'expandRecurrences requires both after and before',
479
+ };
480
+ }
481
+ const rangeAfter = new Date(after);
482
+ const rangeBefore = new Date(before);
483
+ const ids = [];
484
+ for (const event of account.events.values()) {
485
+ if (event.recurrenceRule) {
486
+ for (const start of occurrenceStarts(new Date(`${event.start}Z`), event.recurrenceRule, rangeAfter, rangeBefore)) {
487
+ // An excluded occurrence is gone from the expansion, which is how
488
+ // Stalwart answers a destroy on one — see `#overrideFor`.
489
+ if (this.#overrideFor(event, start)?.excluded === true)
490
+ continue;
491
+ ids.push(occurrenceId(event.id, start));
492
+ }
493
+ }
494
+ else {
495
+ const start = new Date(`${event.start}Z`);
496
+ if (start >= rangeAfter && start < rangeBefore)
497
+ ids.push(event.id);
498
+ }
499
+ }
500
+ return { accountId, queryState: 'q1', canCalculateChanges: false, position: 0, ids };
501
+ }
502
+ // Unexpanded: every master event, including a recurring one's own single
503
+ // id — never one of its occurrences (MSG-053 acceptance criteria).
504
+ const ids = [...account.events.values()]
505
+ .filter((event) => {
506
+ if (!after && !before)
507
+ return true;
508
+ const start = new Date(`${event.start}Z`);
509
+ return (!after || start >= new Date(after)) && (!before || start < new Date(before));
510
+ })
511
+ .map((event) => event.id);
512
+ return { accountId, queryState: 'q1', canCalculateChanges: false, position: 0, ids };
513
+ }
514
+ #eventGet(args) {
515
+ const accountId = String(args.accountId ?? this.me.accountId);
516
+ const account = this.#account(accountId);
517
+ const ids = (args.ids ?? []);
518
+ const list = [];
519
+ const notFound = [];
520
+ for (const id of ids) {
521
+ const split = splitOccurrenceId(id);
522
+ if (split) {
523
+ const master = account.events.get(split.masterId);
524
+ if (!master || !master.recurrenceRule) {
525
+ notFound.push(id);
526
+ continue;
527
+ }
528
+ list.push(this.#projectOccurrence(master, id, split.iso));
529
+ continue;
530
+ }
531
+ const event = account.events.get(id);
532
+ if (!event) {
533
+ notFound.push(id);
534
+ continue;
535
+ }
536
+ list.push(this.#projectEvent(event));
537
+ }
538
+ return { accountId, state: 'e1', list, notFound };
539
+ }
540
+ #projectEvent(event) {
541
+ return {
542
+ id: event.id,
543
+ calendarIds: { ...event.calendarIds },
544
+ uid: event.uid,
545
+ title: event.title,
546
+ description: event.description ?? null,
547
+ start: event.start,
548
+ timeZone: event.timeZone,
549
+ duration: event.duration,
550
+ // `showWithoutTime`/`locations`, not `isAllDay`/`location`: RFC 8984's
551
+ // own names, which `wire.ts`'s `eventFromWire` parses (its doc comment
552
+ // logs the mismatch with this contract's simpler names as a Finding
553
+ // for MSG-055 to confirm live).
554
+ showWithoutTime: event.isAllDay,
555
+ locations: locationToWireMap(event.location),
556
+ recurrenceRule: event.recurrenceRule ? { ...event.recurrenceRule } : null,
557
+ participants: event.participants
558
+ ? Object.fromEntries(Object.entries(event.participants).map(([id, participant]) => [id, { ...participant }]))
559
+ : null,
560
+ status: event.status,
561
+ sequence: event.sequence,
562
+ };
563
+ }
564
+ /** A synthetic per-occurrence id, distinct from the master's — real
565
+ * Stalwart carries a `baseEventId` back-reference on exactly this shape
566
+ * (#137 "Recurrence"). No `recurrenceRule` on the occurrence itself: only
567
+ * the master carries the rule.
568
+ *
569
+ * Whatever the master's `recurrenceOverrides` says about this occurrence
570
+ * wins over the master's own fields, which is how a one-occurrence edit
571
+ * reads back. Confirmed live for MSG-055. */
572
+ #projectOccurrence(master, id, iso) {
573
+ const override = master.recurrenceOverrides?.[this.#overrideKey(iso)] ?? {};
574
+ const { excluded: _excluded, '@type': _type, ...fields } = override;
575
+ return {
576
+ ...this.#projectEvent(master),
577
+ id,
578
+ baseEventId: master.id,
579
+ recurrenceId: iso,
580
+ start: iso.slice(0, 19),
581
+ recurrenceRule: null,
582
+ ...fields,
583
+ };
584
+ }
585
+ /** The key `recurrenceOverrides` is mapped by: a local date-time with no
586
+ * offset and no trailing `Z`, matching what the server returns as an
587
+ * occurrence's `recurrenceId`. */
588
+ #overrideKey(iso) {
589
+ return iso.replace(/Z$/, '').slice(0, 19);
590
+ }
591
+ #overrideFor(master, start) {
592
+ return master.recurrenceOverrides?.[this.#overrideKey(start.toISOString())];
593
+ }
594
+ #eventSet(args) {
595
+ const accountId = String(args.accountId ?? this.me.accountId);
596
+ const account = this.#account(accountId);
597
+ // Opt-in per request, unlike CalDAV's server-wide default — a caller
598
+ // that forgets this sends no invites (types.ts's `SchedulingOptions`;
599
+ // #137 "Scheduling").
600
+ const sendScheduling = args.sendSchedulingMessages === true;
601
+ const create = (args.create ?? {});
602
+ const created = {};
603
+ for (const [key, draft] of Object.entries(create)) {
604
+ const event = this.#toWireEvent(draft);
605
+ account.events.set(event.id, event);
606
+ created[key] = { id: event.id, uid: event.uid, sequence: event.sequence };
607
+ if (sendScheduling)
608
+ this.#sendInvites(event);
609
+ }
610
+ const update = (args.update ?? {});
611
+ const updated = {};
612
+ const notUpdated = {};
613
+ for (const [id, patch] of Object.entries(update)) {
614
+ // A synthetic occurrence id is a real target: the server takes the patch
615
+ // and writes it into the master's `recurrenceOverrides` rather than
616
+ // touching the series. Confirmed live against Stalwart v0.16.20 for
617
+ // MSG-055 — `CalendarEvent/set {update: {<occurrenceId>: {…}}}` answers
618
+ // `updated`, and the other occurrences keep their own fields.
619
+ const split = splitOccurrenceId(id);
620
+ if (split) {
621
+ const master = account.events.get(split.masterId);
622
+ if (!master?.recurrenceRule) {
623
+ notUpdated[id] = { type: 'notFound' };
624
+ continue;
625
+ }
626
+ this.#writeOverride(master, split.iso, patch);
627
+ updated[id] = null;
628
+ continue;
629
+ }
630
+ const event = account.events.get(id);
631
+ if (!event) {
632
+ notUpdated[id] = { type: 'notFound' };
633
+ continue;
634
+ }
635
+ this.#applyPatch(event, patch);
636
+ event.sequence += 1;
637
+ updated[id] = null;
638
+ if (sendScheduling)
639
+ this.#propagateStatus(accountId, event);
640
+ }
641
+ const destroy = (args.destroy ?? []);
642
+ for (const id of destroy) {
643
+ // Destroying one occurrence destroys nothing: the server records
644
+ // `{excluded: true}` against that recurrence id on the master, and the
645
+ // occurrence drops out of the next expansion. Confirmed live.
646
+ const split = splitOccurrenceId(id);
647
+ if (split) {
648
+ const master = account.events.get(split.masterId);
649
+ if (master?.recurrenceRule)
650
+ this.#writeOverride(master, split.iso, { excluded: true });
651
+ continue;
652
+ }
653
+ account.events.delete(id);
654
+ }
655
+ return {
656
+ accountId,
657
+ oldState: '1',
658
+ newState: '2',
659
+ created,
660
+ notCreated: null,
661
+ updated,
662
+ notUpdated: Object.keys(notUpdated).length > 0 ? notUpdated : null,
663
+ destroyed: destroy,
664
+ notDestroyed: null,
665
+ };
666
+ }
667
+ /** Merge a patch into one occurrence's override on the master. The patch
668
+ * arrives already in wire field names, so it is stored as it came and read
669
+ * back by `#projectOccurrence`. */
670
+ #writeOverride(master, iso, patch) {
671
+ const key = this.#overrideKey(iso);
672
+ const overrides = master.recurrenceOverrides ?? {};
673
+ overrides[key] = { '@type': 'Event', ...(overrides[key] ?? {}), ...patch };
674
+ master.recurrenceOverrides = overrides;
675
+ }
676
+ #toWireEvent(draft) {
677
+ const id = `evt${++this.#counter}`;
678
+ const calendarId = typeof draft.calendarId === 'string'
679
+ ? draft.calendarId
680
+ : Object.keys(draft.calendarIds ?? {})[0];
681
+ return {
682
+ id,
683
+ uid: typeof draft.uid === 'string' ? draft.uid : id,
684
+ calendarIds: calendarId ? { [calendarId]: true } : {},
685
+ title: typeof draft.title === 'string' ? draft.title : '',
686
+ description: typeof draft.description === 'string' ? draft.description : undefined,
687
+ start: typeof draft.start === 'string' ? draft.start : this.#now.toISOString().slice(0, 19),
688
+ timeZone: draft.timeZone ?? null,
689
+ duration: typeof draft.duration === 'string' ? draft.duration : 'PT1H',
690
+ isAllDay: Boolean(draft.showWithoutTime ?? draft.isAllDay),
691
+ location: firstLocationName(draft.locations) ??
692
+ (typeof draft.location === 'string' ? draft.location : undefined),
693
+ recurrenceRule: draft.recurrenceRule,
694
+ participants: normalizeParticipants(draft.participants),
695
+ status: draft.status ?? 'confirmed',
696
+ sequence: 0,
697
+ };
698
+ }
699
+ /** Land a copy straight in each known invitee's own calendar, unprompted —
700
+ * exactly what live testing found real Stalwart does, `autoAddInvitations
701
+ * = false` notwithstanding (#145 amendment). An invitee this fake has
702
+ * never heard of is silently skipped: it has no calendar to land in, and
703
+ * that is a gap in the seed data, not a bug worth a fake's own error
704
+ * path. */
705
+ #sendInvites(event) {
706
+ if (!event.participants)
707
+ return;
708
+ for (const participant of Object.values(event.participants)) {
709
+ // The scheme comes off first. A live Stalwart v0.16.20 writes
710
+ // `mailto:bob@example.org` in `calendarAddress` -- pinned verbatim in
711
+ // `test/wire-live-transcript.test.ts` -- while this map is keyed on the
712
+ // bare address. Looking up the raw value found nothing for every
713
+ // participant the real wire shape produces, so this fake delivered
714
+ // invites only for addresses written the one way the server never
715
+ // writes them.
716
+ const inviteeId = this.#emailToAccountId.get(participant.calendarAddress.replace(/^mailto:/i, '').toLowerCase());
717
+ if (!inviteeId || inviteeId === this.me.accountId)
718
+ continue;
719
+ const account = this.#account(inviteeId);
720
+ const defaultCalendarId = [...account.calendars.keys()][0];
721
+ if (!defaultCalendarId)
722
+ continue;
723
+ const copyId = `evt${++this.#counter}`;
724
+ account.events.set(copyId, {
725
+ ...event,
726
+ id: copyId,
727
+ calendarIds: { [defaultCalendarId]: true },
728
+ });
729
+ this.invitesSent.push({ accountId: inviteeId, eventId: copyId, uid: event.uid });
730
+ }
731
+ }
732
+ /** Mirror this copy's participants onto every other copy sharing the same
733
+ * `uid`, in any account — the shared scheduling engine real Stalwart runs
734
+ * underneath both CalDAV and JMAP (#145: "the reply reached alice... with
735
+ * no action on her part"). */
736
+ #propagateStatus(fromAccountId, event) {
737
+ for (const [accountId, account] of this.#accounts) {
738
+ if (accountId === fromAccountId)
739
+ continue;
740
+ for (const other of account.events.values()) {
741
+ if (other.uid !== event.uid)
742
+ continue;
743
+ other.participants = event.participants;
744
+ other.sequence += 1;
745
+ this.repliesSent.push({ accountId, eventId: other.id, uid: event.uid });
746
+ }
747
+ }
748
+ }
749
+ #applyPatch(event, patch) {
750
+ for (const [path, value] of Object.entries(patch)) {
751
+ if (path.startsWith('participants/')) {
752
+ const [participantId, field] = path.slice('participants/'.length).split('/');
753
+ if (!participantId)
754
+ continue;
755
+ const participants = { ...(event.participants ?? {}) };
756
+ if (field) {
757
+ const existing = participants[participantId] ?? { calendarAddress: '' };
758
+ participants[participantId] = { ...existing, [field]: value };
759
+ }
760
+ else if (value === null) {
761
+ delete participants[participantId];
762
+ }
763
+ else {
764
+ participants[participantId] = value;
765
+ }
766
+ event.participants = participants;
767
+ }
768
+ else if (path === 'participants') {
769
+ event.participants = normalizeParticipants(value);
770
+ }
771
+ else if (path === 'calendarIds') {
772
+ const calendarId = Object.keys(value ?? {})[0];
773
+ if (calendarId)
774
+ event.calendarIds = { [calendarId]: true };
775
+ }
776
+ else if (path === 'uid') {
777
+ event.uid = String(value);
778
+ }
779
+ else if (path === 'title') {
780
+ event.title = String(value);
781
+ }
782
+ else if (path === 'description') {
783
+ event.description = typeof value === 'string' ? value : undefined;
784
+ }
785
+ else if (path === 'start') {
786
+ event.start = String(value);
787
+ }
788
+ else if (path === 'timeZone') {
789
+ event.timeZone = value;
790
+ }
791
+ else if (path === 'location') {
792
+ event.location = typeof value === 'string' ? value : undefined;
793
+ }
794
+ else if (path === 'locations') {
795
+ event.location = firstLocationName(value);
796
+ }
797
+ else if (path === 'duration') {
798
+ event.duration = String(value);
799
+ }
800
+ else if (path === 'showWithoutTime') {
801
+ event.isAllDay = Boolean(value);
802
+ }
803
+ else if (path === 'recurrenceRule') {
804
+ event.recurrenceRule = value;
805
+ }
806
+ else if (path === 'status') {
807
+ event.status = value;
808
+ }
809
+ // Anything else is accepted and ignored: this fake supports only the
810
+ // patch paths this package's own client sends.
811
+ }
812
+ }
813
+ /** Busy periods for the queried principal's calendars, gated by the ACL
814
+ * share alone — `mayReadItems` is sufficient on its own; no share at all
815
+ * answers empty (#145 amendment, contradicting #137's original
816
+ * two-rights claim).
817
+ *
818
+ * The principal being asked about is the method's own `accountId`
819
+ * argument, not a separate `id` field: `Principal/getAvailability` reads
820
+ * a *different* account's calendars, authorized by the caller's own
821
+ * token, the same secondary-account pattern JMAP mail already uses for a
822
+ * shared mailbox (`calendar-client.ts`'s `getAvailability`). This fake
823
+ * only ever authenticates one session, so the caller granted rights
824
+ * against is always `this.me.accountId`. */
825
+ #getAvailability(args) {
826
+ const callerId = this.me.accountId;
827
+ const principalId = String(args.accountId ?? args.id ?? '');
828
+ const after = firstString(args.after, args.utcStart);
829
+ const before = firstString(args.before, args.utcEnd);
830
+ const rangeAfter = after ? new Date(after) : new Date(0);
831
+ const rangeBefore = before ? new Date(before) : new Date(8_640_000_000_000_000);
832
+ const account = this.#accounts.get(principalId);
833
+ const periods = [];
834
+ if (account) {
835
+ for (const event of account.events.values()) {
836
+ const calendarId = Object.keys(event.calendarIds)[0];
837
+ const calendar = calendarId ? account.calendars.get(calendarId) : undefined;
838
+ if (!calendar?.shareWith[callerId]?.mayReadItems)
839
+ continue;
840
+ periods.push(...this.#periodsForEvent(event, rangeAfter, rangeBefore));
841
+ }
842
+ }
843
+ periods.sort((a, b) => (a.utcStart < b.utcStart ? -1 : 1));
844
+ return { accountId: principalId, list: periods };
845
+ }
846
+ #periodsForEvent(event, rangeAfter, rangeBefore) {
847
+ if (event.status === 'cancelled')
848
+ return [];
849
+ const busyStatus = event.status === 'tentative' ? 'tentative' : 'confirmed';
850
+ const durationMs = minutesFromDuration(event.duration) * 60_000;
851
+ const starts = event.recurrenceRule
852
+ ? occurrenceStarts(new Date(`${event.start}Z`), event.recurrenceRule, rangeAfter, rangeBefore)
853
+ : [new Date(`${event.start}Z`)];
854
+ return starts
855
+ .filter((start) => start < rangeBefore && new Date(start.getTime() + durationMs) > rangeAfter)
856
+ .map((start) => ({
857
+ utcStart: start.toISOString(),
858
+ utcEnd: new Date(start.getTime() + durationMs).toISOString(),
859
+ busyStatus,
860
+ event: null,
861
+ }));
862
+ }
863
+ #resolveRefs(args, done) {
864
+ const out = {};
865
+ for (const [key, value] of Object.entries(args)) {
866
+ if (!key.startsWith('#')) {
867
+ out[key] = value;
868
+ continue;
869
+ }
870
+ const reference = value;
871
+ const source = done.find(([, , id]) => id === reference.resultOf)?.[1];
872
+ out[key.slice(1)] = source ? pointer(source, reference.path) : [];
873
+ }
874
+ return out;
875
+ }
876
+ /** A `fetch` that answers this calendar universe. Hand it to whatever the
877
+ * package's client is built on. */
878
+ fetch = async (input, init) => {
879
+ if (this.#latency > 0)
880
+ await new Promise((resolve) => setTimeout(resolve, this.#latency));
881
+ const url = String(input);
882
+ const json = (body) => new Response(JSON.stringify(body), {
883
+ status: 200,
884
+ headers: { 'Content-Type': 'application/json' },
885
+ });
886
+ if (!init || (init.method ?? 'GET') === 'GET') {
887
+ if (url.includes('/jmap/eventsource')) {
888
+ // An open stream that never sends: `subscribe` stays connected and
889
+ // quiet, mirroring `@wtfalch/email/mailbox/fake`.
890
+ return new Response(new ReadableStream(), {
891
+ headers: { 'Content-Type': 'text/event-stream' },
892
+ });
893
+ }
894
+ return json(this.session(new URL(url).origin));
895
+ }
896
+ const body = JSON.parse(String(init.body));
897
+ const responses = [];
898
+ for (const [method, callArgs, id] of body.methodCalls) {
899
+ const resolved = this.#resolveRefs(callArgs, responses);
900
+ const result = this.call(method, resolved);
901
+ const isError = typeof result.type === 'string' && ERROR_TYPES.has(result.type);
902
+ responses.push([isError ? 'error' : method, result, id]);
903
+ }
904
+ return json({ methodResponses: responses, sessionState: 'fake-session' });
905
+ };
906
+ }