@wtfalch/calendar 0.3.0 → 0.3.2
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/README.md +9 -1
- package/dist/calendar/calendar-client.js +32 -2
- package/dist/calendar/client.d.ts +1 -1
- package/dist/calendar/client.js +26 -2
- package/dist/calendar/types.d.ts +8 -0
- package/package.json +3 -7
- package/dist/calendar/fake/index.d.ts +0 -36
- package/dist/calendar/fake/index.js +0 -79
- package/dist/calendar/fake/sample.d.ts +0 -67
- package/dist/calendar/fake/sample.js +0 -116
- package/dist/calendar/fake/store.d.ts +0 -122
- package/dist/calendar/fake/store.js +0 -1398
|
@@ -1,1398 +0,0 @@
|
|
|
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 six load-bearing behaviours confirmed live against Stalwart
|
|
9
|
-
* v0.16.20 (https://github.com/wtfalch/messaging/issues/145 for 1-4, issue
|
|
10
|
-
* #17 for 5, issue #15 for 6, https://github.com/wtfalch/calendar/issues):
|
|
11
|
-
*
|
|
12
|
-
* 1. `CalendarEvent/query` without `expandRecurrences` returns master
|
|
13
|
-
* events only; with it, and both `after`/`before`, dated occurrences —
|
|
14
|
-
* and with it but no bounds, `invalidArguments`
|
|
15
|
-
* (https://github.com/wtfalch/messaging/issues/145).
|
|
16
|
-
* 2. An invite (`CalendarEvent/set create` with `sendSchedulingMessages`)
|
|
17
|
-
* lands a copy straight in the invitee's own calendar. An organiser edit
|
|
18
|
-
* (`update` with `sendSchedulingMessages`) bumps `sequence` and mirrors
|
|
19
|
-
* the whole `participants` map onto every other copy sharing the same
|
|
20
|
-
* `uid`. A reply from someone who is *not* this copy's organiser -- a
|
|
21
|
-
* patch touching only one participant's
|
|
22
|
-
* `participationStatus`/`participationComment`, `respond`'s own shape --
|
|
23
|
-
* is different: it bumps `sequence` nowhere, and it carries only the
|
|
24
|
-
* status, never the comment, to the other copies. The organiser sending
|
|
25
|
-
* that identical shape on her own event is still an ordinary edit, not a
|
|
26
|
-
* reply (T11 live capture and re-capture,
|
|
27
|
-
* https://github.com/wtfalch/calendar/issues/11) -- and a reply against a
|
|
28
|
-
* synthetic occurrence id is refused outright
|
|
29
|
-
* (`"Multiple organizers found in iCalendar object"`), never silently
|
|
30
|
-
* written into `recurrenceOverrides`.
|
|
31
|
-
* 3. A grant written to `Calendar/set update {shareWith}` reads back on the
|
|
32
|
-
* next `Calendar/get` (https://github.com/wtfalch/messaging/issues/145).
|
|
33
|
-
* 4. `Principal/getAvailability` returns busy periods for a calendar shared
|
|
34
|
-
* with at least `mayReadItems` — no second opt-in needed — and an empty
|
|
35
|
-
* list for one shared with nothing at all.
|
|
36
|
-
* 5. `CalendarEvent/query`'s `text` filter matches a case-insensitive
|
|
37
|
-
* substring of either `title` or `description` in one pass, and needs no
|
|
38
|
-
* `after`/`before` at all unless `expandRecurrences` is also set, in
|
|
39
|
-
* which case both are still required regardless of `text`.
|
|
40
|
-
* 6. An `alerts` map -- offset or absolute trigger, display action,
|
|
41
|
-
* `acknowledged` -- round-trips through `CalendarEvent/set create` and
|
|
42
|
-
* `get` unchanged (T15, issue #15). A trigger with neither `offset` nor
|
|
43
|
-
* `when` is accepted on write but comes back with no `trigger` key at
|
|
44
|
-
* all (T15 amendment); `CalendarEvent/set` on `alerts` replaces the
|
|
45
|
-
* whole map, so a write that does not carry `acknowledged` forward
|
|
46
|
-
* wipes it.
|
|
47
|
-
*
|
|
48
|
-
* It implements only the methods `@wtfalch/calendar` sends. Anything else
|
|
49
|
-
* answers `unknownMethod`, which is what a real server does and what the
|
|
50
|
-
* error path expects.
|
|
51
|
-
*
|
|
52
|
-
* Wire shapes below (`myRights`/`shareWith` as boolean-flag objects, the
|
|
53
|
-
* `calendars`/`calendars:parse` capability strings, the session capability
|
|
54
|
-
* object's field names, `recurrenceRule` singular, `calendarAddress`, the
|
|
55
|
-
* synthetic-occurrence id carrying a `baseEventId`) are grounded in direct
|
|
56
|
-
* evidence from #137/#138/#145 rather than guessed; the wire's own method-arg
|
|
57
|
-
* shapes for bounds and `expandRecurrences` are accepted in more than one
|
|
58
|
-
* place (see `firstString`) since this package's own client, built alongside
|
|
59
|
-
* this fake rather than before it, has not settled which one it sends.
|
|
60
|
-
*/
|
|
61
|
-
import { ME, OTHER_PRINCIPALS } from "./sample.js";
|
|
62
|
-
/** Every right `Calendar.myRights`/`shareWith` can carry (#138 §1). */
|
|
63
|
-
const RIGHTS = [
|
|
64
|
-
'mayReadFreeBusy',
|
|
65
|
-
'mayReadItems',
|
|
66
|
-
'mayWriteAll',
|
|
67
|
-
'mayWriteOwn',
|
|
68
|
-
'mayUpdatePrivate',
|
|
69
|
-
'mayRSVP',
|
|
70
|
-
'mayShare',
|
|
71
|
-
'mayDelete',
|
|
72
|
-
];
|
|
73
|
-
const ALL_RIGHTS = Object.fromEntries(RIGHTS.map((right) => [right, true]));
|
|
74
|
-
/** `shareWith`'s grantee objects on the wire, echoed back the way the real
|
|
75
|
-
* server does it: all eight rights, every one an explicit boolean, not just
|
|
76
|
-
* the ones actually granted (#145's second run, `wire-live-transcript.test.ts`'s
|
|
77
|
-
* `LIVE_SHARE_GRANTED`). This fake's own storage keeps only the true
|
|
78
|
-
* entries (`calendar.shareWith[grantee]`), so this fills the other six in
|
|
79
|
-
* as `false` on the way out -- the fake must not be kinder than the
|
|
80
|
-
* server. */
|
|
81
|
-
function fullRightsEcho(rights) {
|
|
82
|
-
return Object.fromEntries(RIGHTS.map((right) => [right, rights[right] === true]));
|
|
83
|
-
}
|
|
84
|
-
/** How two touches on the same id in one `.../set` call net out, before the
|
|
85
|
-
* log even sees them: `destroy` always wins (nothing later can matter once
|
|
86
|
-
* an id is gone), otherwise the later op wins except that `create` survives
|
|
87
|
-
* a later `update` -- an id created and then edited in the same call is
|
|
88
|
-
* still, from a change feed's point of view, simply `created`. */
|
|
89
|
-
function mergeOp(previous, next) {
|
|
90
|
-
if (previous === undefined)
|
|
91
|
-
return next;
|
|
92
|
-
if (next === 'destroy')
|
|
93
|
-
return 'destroy';
|
|
94
|
-
if (previous === 'create')
|
|
95
|
-
return 'create';
|
|
96
|
-
return next;
|
|
97
|
-
}
|
|
98
|
-
const OCCURRENCE_SEPARATOR = '~';
|
|
99
|
-
const MAX_OCCURRENCES = 1_000;
|
|
100
|
-
/** The shared campaign Stalwart's own `urn:ietf:params:jmap:core.
|
|
101
|
-
* maxCallsInRequest`, measured live for issue #13: a 16-call
|
|
102
|
-
* `Principal/getAvailability` batch answers 16 `methodResponses`, and a
|
|
103
|
-
* 17-call one is refused whole (`test/wire-live-transcript.test.ts`'s
|
|
104
|
-
* `LIVE_LIMIT_REFUSAL`). Advertised here and enforced in `fetch` below, so
|
|
105
|
-
* a client that stops chunking -- or that hardcodes some other number --
|
|
106
|
-
* fails a fake-backed test immediately, with no live server needed to
|
|
107
|
-
* catch it a second time. */
|
|
108
|
-
const MAX_CALLS_IN_REQUEST = 16;
|
|
109
|
-
function occurrenceId(masterId, date) {
|
|
110
|
-
return `${masterId}${OCCURRENCE_SEPARATOR}${date.toISOString()}`;
|
|
111
|
-
}
|
|
112
|
-
function splitOccurrenceId(id) {
|
|
113
|
-
const index = id.indexOf(OCCURRENCE_SEPARATOR);
|
|
114
|
-
if (index === -1)
|
|
115
|
-
return null;
|
|
116
|
-
return { masterId: id.slice(0, index), iso: id.slice(index + OCCURRENCE_SEPARATOR.length) };
|
|
117
|
-
}
|
|
118
|
-
function toDuration(minutes) {
|
|
119
|
-
if (minutes > 0 && minutes % 60 === 0)
|
|
120
|
-
return `PT${minutes / 60}H`;
|
|
121
|
-
return `PT${minutes}M`;
|
|
122
|
-
}
|
|
123
|
-
/** The inverse of `toDuration`, for the little arithmetic `PT1H30M`-shaped
|
|
124
|
-
* durations need. Anything it cannot parse is treated as zero-length,
|
|
125
|
-
* which is a fake's business, not a real server's. */
|
|
126
|
-
function minutesFromDuration(duration) {
|
|
127
|
-
const match = /^PT(?:(\d+)H)?(?:(\d+)M)?$/.exec(duration);
|
|
128
|
-
const hours = Number(match?.[1] ?? 0);
|
|
129
|
-
const minutes = Number(match?.[2] ?? 0);
|
|
130
|
-
return hours * 60 + minutes;
|
|
131
|
-
}
|
|
132
|
-
function advance(date, frequency, interval) {
|
|
133
|
-
const next = new Date(date);
|
|
134
|
-
if (frequency === 'daily')
|
|
135
|
-
next.setUTCDate(next.getUTCDate() + interval);
|
|
136
|
-
else if (frequency === 'weekly')
|
|
137
|
-
next.setUTCDate(next.getUTCDate() + 7 * interval);
|
|
138
|
-
else if (frequency === 'monthly')
|
|
139
|
-
next.setUTCMonth(next.getUTCMonth() + interval);
|
|
140
|
-
else
|
|
141
|
-
next.setUTCFullYear(next.getUTCFullYear() + interval);
|
|
142
|
-
return next;
|
|
143
|
-
}
|
|
144
|
-
/** Every occurrence start in `[rangeAfter, rangeBefore)`, expanding
|
|
145
|
-
* server-side exactly as real Stalwart does (#137 "Recurrence") — this
|
|
146
|
-
* package's own client never expands a rule itself. Capped, so a rule with
|
|
147
|
-
* no `count`/`until` and a distant `rangeBefore` cannot loop forever. */
|
|
148
|
-
function occurrenceStarts(seriesStart, rule, rangeAfter, rangeBefore) {
|
|
149
|
-
const interval = rule.interval ?? 1;
|
|
150
|
-
const until = rule.until ? new Date(rule.until) : null;
|
|
151
|
-
const starts = [];
|
|
152
|
-
let current = seriesStart;
|
|
153
|
-
for (let index = 0; index < MAX_OCCURRENCES; index++) {
|
|
154
|
-
if (until && current > until)
|
|
155
|
-
break;
|
|
156
|
-
if (rule.count !== undefined && index >= rule.count)
|
|
157
|
-
break;
|
|
158
|
-
if (current >= rangeBefore)
|
|
159
|
-
break;
|
|
160
|
-
if (current >= rangeAfter)
|
|
161
|
-
starts.push(current);
|
|
162
|
-
current = advance(current, rule.frequency, interval);
|
|
163
|
-
}
|
|
164
|
-
return starts;
|
|
165
|
-
}
|
|
166
|
-
function firstString(...values) {
|
|
167
|
-
for (const value of values)
|
|
168
|
-
if (typeof value === 'string')
|
|
169
|
-
return value;
|
|
170
|
-
return undefined;
|
|
171
|
-
}
|
|
172
|
-
function slug(calendarAddress) {
|
|
173
|
-
return calendarAddress.split('@')[0] || calendarAddress;
|
|
174
|
-
}
|
|
175
|
-
/** `wire.ts`'s `locationToWire` shape: a map of `Location` objects, keyed
|
|
176
|
-
* arbitrarily, of which this fake — like the real client's own
|
|
177
|
-
* `locationFromWire` — only ever reads the first `name`. */
|
|
178
|
-
function firstLocationName(locations) {
|
|
179
|
-
if (!locations || typeof locations !== 'object')
|
|
180
|
-
return undefined;
|
|
181
|
-
const first = Object.values(locations)[0];
|
|
182
|
-
return typeof first?.name === 'string' ? first.name : undefined;
|
|
183
|
-
}
|
|
184
|
-
function locationToWireMap(location) {
|
|
185
|
-
return location === undefined ? null : { main: { '@type': 'Location', name: location } };
|
|
186
|
-
}
|
|
187
|
-
/** `wire.ts`'s `virtualLocationsFromWire` shape: a map of `VirtualLocation`
|
|
188
|
-
* objects, keyed arbitrarily -- accepted from a raw JMAP write this fake's
|
|
189
|
-
* own client never made, so entries missing a string `uri` are dropped
|
|
190
|
-
* rather than crashing (#16). */
|
|
191
|
-
function virtualLocationsFromWireMap(value) {
|
|
192
|
-
if (!value || typeof value !== 'object')
|
|
193
|
-
return undefined;
|
|
194
|
-
const list = Object.values(value)
|
|
195
|
-
.map((entry) => entry)
|
|
196
|
-
.filter((entry) => typeof entry.uri === 'string')
|
|
197
|
-
.map((entry) => ({
|
|
198
|
-
uri: entry.uri,
|
|
199
|
-
name: typeof entry.name === 'string' ? entry.name : undefined,
|
|
200
|
-
}));
|
|
201
|
-
return list.length > 0 ? list : undefined;
|
|
202
|
-
}
|
|
203
|
-
function virtualLocationsToWireMap(locations) {
|
|
204
|
-
if (!locations)
|
|
205
|
-
return null;
|
|
206
|
-
return Object.fromEntries(locations.map((location, i) => [
|
|
207
|
-
`v${i}`,
|
|
208
|
-
{
|
|
209
|
-
'@type': 'VirtualLocation',
|
|
210
|
-
uri: location.uri,
|
|
211
|
-
...(location.name === undefined ? {} : { name: location.name }),
|
|
212
|
-
},
|
|
213
|
-
]));
|
|
214
|
-
}
|
|
215
|
-
function rolesToMap(roles) {
|
|
216
|
-
if (!roles)
|
|
217
|
-
return undefined;
|
|
218
|
-
if (Array.isArray(roles))
|
|
219
|
-
return Object.fromEntries(roles.map((role) => [String(role), true]));
|
|
220
|
-
return Object.fromEntries(Object.entries(roles)
|
|
221
|
-
.filter(([, value]) => value === true)
|
|
222
|
-
.map(([key]) => [key, true]));
|
|
223
|
-
}
|
|
224
|
-
/** Accepts either the client-level array shape or a wire-level map keyed by
|
|
225
|
-
* an arbitrary id, mirroring how the live transcript itself chose the key
|
|
226
|
-
* `"bob"` for bob's own entry (#145) — this fake does not assume the
|
|
227
|
-
* concurrently-built client picks the same one every time. */
|
|
228
|
-
function normalizeParticipants(input) {
|
|
229
|
-
if (!input)
|
|
230
|
-
return undefined;
|
|
231
|
-
const entries = Array.isArray(input)
|
|
232
|
-
? input.map((item) => [undefined, item])
|
|
233
|
-
: Object.entries(input).map(([key, value]) => [
|
|
234
|
-
key,
|
|
235
|
-
value,
|
|
236
|
-
]);
|
|
237
|
-
const out = {};
|
|
238
|
-
for (const [key, participant] of entries) {
|
|
239
|
-
const calendarAddress = String(participant.calendarAddress ?? '');
|
|
240
|
-
if (!calendarAddress)
|
|
241
|
-
continue;
|
|
242
|
-
const id = key ?? slug(calendarAddress);
|
|
243
|
-
out[id] = {
|
|
244
|
-
calendarAddress,
|
|
245
|
-
name: typeof participant.name === 'string' ? participant.name : undefined,
|
|
246
|
-
roles: rolesToMap(participant.roles),
|
|
247
|
-
participationStatus: participant.participationStatus,
|
|
248
|
-
};
|
|
249
|
-
}
|
|
250
|
-
return out;
|
|
251
|
-
}
|
|
252
|
-
/** The pattern `respond`'s own patch always writes: one participant's
|
|
253
|
-
* `participationStatus`, optionally alongside that same participant's
|
|
254
|
-
* `participationComment` (T11 live capture — the wire name a real server
|
|
255
|
-
* answers to, not JSCalendar's plain `comment`). */
|
|
256
|
-
const REPLY_PATCH_PATH = /^participants\/([^/]+)\/(participationStatus|participationComment)$/;
|
|
257
|
-
/** The participant id an update patch replies for, or `null` when the patch
|
|
258
|
-
* is not shaped like a reply at all — an organiser edit, which may touch
|
|
259
|
-
* anything, including the whole `participants` map in one go. Every key in
|
|
260
|
-
* a genuine reply patch names the *same* participant; a patch that mixes
|
|
261
|
-
* another field in, or touches two participants at once, is an organiser
|
|
262
|
-
* edit and must not be mistaken for one attendee's own answer. */
|
|
263
|
-
function replyParticipantId(patch) {
|
|
264
|
-
const keys = Object.keys(patch);
|
|
265
|
-
if (keys.length === 0)
|
|
266
|
-
return null;
|
|
267
|
-
let id = null;
|
|
268
|
-
for (const key of keys) {
|
|
269
|
-
const match = REPLY_PATCH_PATH.exec(key);
|
|
270
|
-
if (!match)
|
|
271
|
-
return null;
|
|
272
|
-
const participantId = match[1];
|
|
273
|
-
if (id !== null && id !== participantId)
|
|
274
|
-
return null;
|
|
275
|
-
id = participantId;
|
|
276
|
-
}
|
|
277
|
-
return id;
|
|
278
|
-
}
|
|
279
|
-
/** RFC 6901 §3, for a result reference's path only — none of this fake's own
|
|
280
|
-
* patch paths need unescaping, since none of its ids ever contain `~`. */
|
|
281
|
-
function unpointer(segment) {
|
|
282
|
-
return segment.replaceAll('~1', '/').replaceAll('~0', '~');
|
|
283
|
-
}
|
|
284
|
-
function pointer(value, path) {
|
|
285
|
-
let current = value;
|
|
286
|
-
for (const rawSegment of path.split('/').filter(Boolean)) {
|
|
287
|
-
const segment = unpointer(rawSegment);
|
|
288
|
-
if (segment === '*') {
|
|
289
|
-
if (!Array.isArray(current))
|
|
290
|
-
return [];
|
|
291
|
-
const rest = path.slice(path.indexOf('*') + 1);
|
|
292
|
-
return current.flatMap((item) => pointer(item, rest));
|
|
293
|
-
}
|
|
294
|
-
if (Array.isArray(current))
|
|
295
|
-
current = current[Number(segment)];
|
|
296
|
-
else if (current && typeof current === 'object')
|
|
297
|
-
current = current[segment];
|
|
298
|
-
else
|
|
299
|
-
return undefined;
|
|
300
|
-
}
|
|
301
|
-
return current;
|
|
302
|
-
}
|
|
303
|
-
const ERROR_TYPES = new Set(['invalidArguments', 'unknownMethod', 'cannotCalculateChanges']);
|
|
304
|
-
export class FakeCalendarStore {
|
|
305
|
-
me;
|
|
306
|
-
#now;
|
|
307
|
-
#latency;
|
|
308
|
-
#counter = 0;
|
|
309
|
-
#accounts = new Map();
|
|
310
|
-
#emailToAccountId = new Map();
|
|
311
|
-
/** Every seeded principal, by account id -- what `Principal/get` answers
|
|
312
|
-
* from, seeded the same run `#seed` builds the account buckets from. */
|
|
313
|
-
#principals = new Map();
|
|
314
|
-
/** Every invite `CalendarEvent/set create` landed in someone else's
|
|
315
|
-
* calendar, for a test that asserts the invite actually reached them
|
|
316
|
-
* rather than only that the call succeeded. */
|
|
317
|
-
invitesSent = [];
|
|
318
|
-
/** Every reply that propagated a participant-status change to another
|
|
319
|
-
* copy of the same event. */
|
|
320
|
-
repliesSent = [];
|
|
321
|
-
constructor(options = {}) {
|
|
322
|
-
this.me = options.me ?? ME;
|
|
323
|
-
this.#now = options.now ?? new Date('2026-09-17T09:00:00Z');
|
|
324
|
-
this.#latency = options.latency ?? 0;
|
|
325
|
-
for (const principal of [this.me, ...(options.otherPrincipals ?? OTHER_PRINCIPALS)]) {
|
|
326
|
-
this.#seed(principal);
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
#seed(principal) {
|
|
330
|
-
const bucket = {
|
|
331
|
-
calendars: new Map(),
|
|
332
|
-
events: new Map(),
|
|
333
|
-
eventState: 0,
|
|
334
|
-
eventLog: [],
|
|
335
|
-
calendarState: 0,
|
|
336
|
-
calendarLog: [],
|
|
337
|
-
};
|
|
338
|
-
for (const seedCalendar of principal.calendars) {
|
|
339
|
-
bucket.calendars.set(seedCalendar.id, {
|
|
340
|
-
id: seedCalendar.id,
|
|
341
|
-
name: seedCalendar.name,
|
|
342
|
-
description: seedCalendar.description,
|
|
343
|
-
color: seedCalendar.color,
|
|
344
|
-
isVisible: seedCalendar.isVisible ?? true,
|
|
345
|
-
includeInAvailability: seedCalendar.includeInAvailability ?? 'all',
|
|
346
|
-
shareWith: Object.fromEntries(Object.entries(seedCalendar.shareWith ?? {}).map(([accountId, rights]) => [
|
|
347
|
-
accountId,
|
|
348
|
-
Object.fromEntries(rights.map((right) => [right, true])),
|
|
349
|
-
])),
|
|
350
|
-
});
|
|
351
|
-
for (const seedEvent of seedCalendar.events ?? []) {
|
|
352
|
-
bucket.events.set(seedEvent.uid, {
|
|
353
|
-
id: seedEvent.uid,
|
|
354
|
-
uid: seedEvent.uid,
|
|
355
|
-
calendarIds: { [seedCalendar.id]: true },
|
|
356
|
-
title: seedEvent.title,
|
|
357
|
-
description: seedEvent.description,
|
|
358
|
-
start: new Date(this.#now.getTime() + seedEvent.startOffsetMinutes * 60_000)
|
|
359
|
-
.toISOString()
|
|
360
|
-
.slice(0, 19),
|
|
361
|
-
timeZone: 'UTC',
|
|
362
|
-
duration: toDuration(seedEvent.durationMinutes),
|
|
363
|
-
isAllDay: seedEvent.isAllDay ?? false,
|
|
364
|
-
location: seedEvent.location,
|
|
365
|
-
recurrenceRule: seedEvent.recurrenceRule,
|
|
366
|
-
status: seedEvent.status ?? 'confirmed',
|
|
367
|
-
freeBusyStatus: seedEvent.freeBusyStatus,
|
|
368
|
-
sequence: 0,
|
|
369
|
-
});
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
this.#accounts.set(principal.accountId, bucket);
|
|
373
|
-
this.#emailToAccountId.set(principal.email.toLowerCase(), principal.accountId);
|
|
374
|
-
this.#principals.set(principal.accountId, principal);
|
|
375
|
-
}
|
|
376
|
-
#account(accountId) {
|
|
377
|
-
let bucket = this.#accounts.get(accountId);
|
|
378
|
-
if (!bucket) {
|
|
379
|
-
bucket = {
|
|
380
|
-
calendars: new Map(),
|
|
381
|
-
events: new Map(),
|
|
382
|
-
eventState: 0,
|
|
383
|
-
eventLog: [],
|
|
384
|
-
calendarState: 0,
|
|
385
|
-
calendarLog: [],
|
|
386
|
-
};
|
|
387
|
-
this.#accounts.set(accountId, bucket);
|
|
388
|
-
}
|
|
389
|
-
return bucket;
|
|
390
|
-
}
|
|
391
|
-
/** Record one `.../set` call's worth of touches at a fresh state, once --
|
|
392
|
-
* every id touched in the same call shares one new state number, matching
|
|
393
|
-
* how this fake already answers one `oldState`/`newState` pair per call
|
|
394
|
-
* rather than one per object (wtfalch/calendar#65). A no-op call (`touched`
|
|
395
|
-
* empty) never advances the state at all. */
|
|
396
|
-
#bumpEventLog(account, touched) {
|
|
397
|
-
if (touched.size === 0)
|
|
398
|
-
return;
|
|
399
|
-
account.eventState += 1;
|
|
400
|
-
for (const [id, op] of touched)
|
|
401
|
-
account.eventLog.push({ state: account.eventState, id, op });
|
|
402
|
-
}
|
|
403
|
-
/** `Calendar/set`'s own counterpart to `#bumpEventLog`, over the separate
|
|
404
|
-
* `calendarState`/`calendarLog` pair -- the two `/changes` streams never
|
|
405
|
-
* share a state space (matching `sync.ts`'s own `calendar_event_state`/
|
|
406
|
-
* `calendar_state` split). */
|
|
407
|
-
#bumpCalendarLog(account, touched) {
|
|
408
|
-
if (touched.size === 0)
|
|
409
|
-
return;
|
|
410
|
-
account.calendarState += 1;
|
|
411
|
-
for (const [id, op] of touched) {
|
|
412
|
-
account.calendarLog.push({ state: account.calendarState, id, op });
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
/**
|
|
416
|
-
* `CalendarEvent/changes`/`Calendar/changes`'s shared answer shape (RFC
|
|
417
|
-
* 8620 §5.2), computed from one type's own log. `maxChanges` truncates on a
|
|
418
|
-
* whole-state boundary, never splitting one `.../set` call's ids across two
|
|
419
|
-
* `changes()` answers -- this fake never logs a state with zero ids in it,
|
|
420
|
-
* so "the next state would exceed maxChanges" and "stop before it" are the
|
|
421
|
-
* same decision.
|
|
422
|
-
*/
|
|
423
|
-
#computeChanges(log, sinceState, maxChanges) {
|
|
424
|
-
// Every id that existed the instant before `sinceState`'s own boundary --
|
|
425
|
-
// replayed from the start of the log, which this fake keeps in full
|
|
426
|
-
// (never pruned), so "unknown to this fake" (checked by the caller) only
|
|
427
|
-
// ever means malformed or in-the-future, never "too old to still have a
|
|
428
|
-
// record of".
|
|
429
|
-
const existedAtSince = new Set();
|
|
430
|
-
for (const entry of log) {
|
|
431
|
-
if (entry.state > sinceState)
|
|
432
|
-
break;
|
|
433
|
-
if (entry.op === 'destroy')
|
|
434
|
-
existedAtSince.delete(entry.id);
|
|
435
|
-
else
|
|
436
|
-
existedAtSince.add(entry.id);
|
|
437
|
-
}
|
|
438
|
-
const window = log.filter((entry) => entry.state > sinceState);
|
|
439
|
-
const states = [...new Set(window.map((entry) => entry.state))].sort((a, b) => a - b);
|
|
440
|
-
const includedStates = [];
|
|
441
|
-
let idsSoFar = new Set();
|
|
442
|
-
for (const state of states) {
|
|
443
|
-
const idsAtState = new Set(window.filter((entry) => entry.state === state).map((entry) => entry.id));
|
|
444
|
-
const union = new Set([...idsSoFar, ...idsAtState]);
|
|
445
|
-
if (includedStates.length > 0 && union.size > maxChanges)
|
|
446
|
-
break;
|
|
447
|
-
includedStates.push(state);
|
|
448
|
-
idsSoFar = union;
|
|
449
|
-
}
|
|
450
|
-
const hasMoreChanges = includedStates.length < states.length;
|
|
451
|
-
const newState = includedStates.length > 0 ? includedStates[includedStates.length - 1] : sinceState;
|
|
452
|
-
const includedEntries = window.filter((entry) => includedStates.includes(entry.state));
|
|
453
|
-
const perId = new Map();
|
|
454
|
-
for (const entry of includedEntries) {
|
|
455
|
-
const ops = perId.get(entry.id) ?? [];
|
|
456
|
-
ops.push(entry.op);
|
|
457
|
-
perId.set(entry.id, ops);
|
|
458
|
-
}
|
|
459
|
-
const created = [];
|
|
460
|
-
const updated = [];
|
|
461
|
-
const destroyed = [];
|
|
462
|
-
for (const [id, ops] of perId) {
|
|
463
|
-
const existedBefore = existedAtSince.has(id);
|
|
464
|
-
const lastOp = ops[ops.length - 1];
|
|
465
|
-
if (!existedBefore) {
|
|
466
|
-
// Created and destroyed within the same window: never seen at all,
|
|
467
|
-
// the same netting RFC 8620 §5.2's own `/changes` semantics expect.
|
|
468
|
-
if (lastOp !== 'destroy')
|
|
469
|
-
created.push(id);
|
|
470
|
-
}
|
|
471
|
-
else if (lastOp === 'destroy') {
|
|
472
|
-
destroyed.push(id);
|
|
473
|
-
}
|
|
474
|
-
else {
|
|
475
|
-
updated.push(id);
|
|
476
|
-
}
|
|
477
|
-
}
|
|
478
|
-
return { created, updated, destroyed, newState: String(newState), hasMoreChanges };
|
|
479
|
-
}
|
|
480
|
-
/** `sinceState` unparseable, negative, or naming a state this account has
|
|
481
|
-
* never reached is answered as `cannotCalculateChanges` -- RFC 8620 §5.2's
|
|
482
|
-
* own error for a `/changes` call the server cannot resolve
|
|
483
|
-
* (wtfalch/calendar#65). */
|
|
484
|
-
#changesFor(accountId, log, currentState, args) {
|
|
485
|
-
const sinceStateRaw = String(args.sinceState ?? '');
|
|
486
|
-
const sinceState = Number(sinceStateRaw);
|
|
487
|
-
if (!Number.isInteger(sinceState) || sinceState < 0 || sinceState > currentState) {
|
|
488
|
-
return {
|
|
489
|
-
type: 'cannotCalculateChanges',
|
|
490
|
-
description: `sinceState ${JSON.stringify(sinceStateRaw)} is unknown to this fake calendar`,
|
|
491
|
-
};
|
|
492
|
-
}
|
|
493
|
-
const maxChanges = typeof args.maxChanges === 'number' && args.maxChanges > 0 ? args.maxChanges : 1_000;
|
|
494
|
-
const result = this.#computeChanges(log, sinceState, maxChanges);
|
|
495
|
-
return { accountId, oldState: sinceStateRaw, ...result };
|
|
496
|
-
}
|
|
497
|
-
#eventChanges(args) {
|
|
498
|
-
const accountId = String(args.accountId ?? this.me.accountId);
|
|
499
|
-
const account = this.#account(accountId);
|
|
500
|
-
return this.#changesFor(accountId, account.eventLog, account.eventState, args);
|
|
501
|
-
}
|
|
502
|
-
#calendarChanges(args) {
|
|
503
|
-
const accountId = String(args.accountId ?? this.me.accountId);
|
|
504
|
-
const account = this.#account(accountId);
|
|
505
|
-
return this.#changesFor(accountId, account.calendarLog, account.calendarState, args);
|
|
506
|
-
}
|
|
507
|
-
/**
|
|
508
|
-
* The session document, as Stalwart writes it.
|
|
509
|
-
*
|
|
510
|
-
* **Every seeded principal is listed in `accounts`, not only `me`**
|
|
511
|
-
* (wtfalch/calendar#65): this fake never inspects the bearer token a
|
|
512
|
-
* caller actually presents (it is a fake calendar universe, not an auth
|
|
513
|
-
* simulator), so it cannot tell "the signed-in browser session" apart from
|
|
514
|
-
* "a service credential minted for someone else's account" the way a real
|
|
515
|
-
* Stalwart would -- a real server's session document lists only the
|
|
516
|
-
* account(s) the presented credential can reach. Listing every seeded
|
|
517
|
-
* account here is the honest reflection of that: this fake would answer
|
|
518
|
-
* *some* session document for a service credential regardless of whose
|
|
519
|
-
* account it names, so it answers one where that account is actually
|
|
520
|
-
* there, rather than failing every service-credential test on a check this
|
|
521
|
-
* fake has no way to enforce for real. `primaryAccounts` still names `me`
|
|
522
|
-
* -- unrelated to whether another account is reachable by naming it
|
|
523
|
-
* explicitly via `CalendarClientOptions.accountId`, the same way a real
|
|
524
|
-
* session's own primary account says nothing about which other accounts
|
|
525
|
-
* the credential can also reach.
|
|
526
|
-
*/
|
|
527
|
-
session(origin) {
|
|
528
|
-
const meId = this.me.accountId;
|
|
529
|
-
const accounts = {};
|
|
530
|
-
for (const [accountId, principal] of this.#principals) {
|
|
531
|
-
accounts[accountId] = {
|
|
532
|
-
name: principal.email,
|
|
533
|
-
isPersonal: accountId === meId,
|
|
534
|
-
isReadOnly: false,
|
|
535
|
-
accountCapabilities: {
|
|
536
|
-
'urn:ietf:params:jmap:calendars': {},
|
|
537
|
-
'urn:ietf:params:jmap:calendars:parse': {},
|
|
538
|
-
},
|
|
539
|
-
};
|
|
540
|
-
}
|
|
541
|
-
return {
|
|
542
|
-
capabilities: {
|
|
543
|
-
'urn:ietf:params:jmap:core': { maxCallsInRequest: MAX_CALLS_IN_REQUEST },
|
|
544
|
-
// Field names confirmed live against Stalwart v0.16.20 (#137).
|
|
545
|
-
'urn:ietf:params:jmap:calendars': {
|
|
546
|
-
maxCalendarsPerEvent: 1,
|
|
547
|
-
minDateTime: '1900-01-01T00:00:00Z',
|
|
548
|
-
maxDateTime: '2100-01-01T00:00:00Z',
|
|
549
|
-
maxExpandedQueryDuration: 'P400D',
|
|
550
|
-
maxParticipantsPerEvent: 100,
|
|
551
|
-
mayCreateCalendar: true,
|
|
552
|
-
},
|
|
553
|
-
'urn:ietf:params:jmap:calendars:parse': {},
|
|
554
|
-
},
|
|
555
|
-
accounts,
|
|
556
|
-
primaryAccounts: {
|
|
557
|
-
'urn:ietf:params:jmap:calendars': meId,
|
|
558
|
-
'urn:ietf:params:jmap:calendars:parse': meId,
|
|
559
|
-
},
|
|
560
|
-
username: this.me.email,
|
|
561
|
-
apiUrl: `${origin}/jmap/`,
|
|
562
|
-
downloadUrl: `${origin}/jmap/download/{accountId}/{blobId}/{name}?accept={type}`,
|
|
563
|
-
uploadUrl: `${origin}/jmap/upload/{accountId}/`,
|
|
564
|
-
eventSourceUrl: `${origin}/jmap/eventsource/?types={types}&closeafter={closeafter}&ping={ping}`,
|
|
565
|
-
state: 'fake-session',
|
|
566
|
-
};
|
|
567
|
-
}
|
|
568
|
-
/** Answer one method call. Exported for the transport, and for a test that
|
|
569
|
-
* wants to drive one side of a scheduling exchange directly — the
|
|
570
|
-
* invitee's reply, in particular, since `fakeCalendar()` only ever hands
|
|
571
|
-
* back one `CalendarClient`, for the organiser. */
|
|
572
|
-
call(method, args) {
|
|
573
|
-
switch (method) {
|
|
574
|
-
case 'Calendar/get':
|
|
575
|
-
return this.#calendarGet(args);
|
|
576
|
-
case 'Calendar/set':
|
|
577
|
-
return this.#calendarSet(args);
|
|
578
|
-
case 'CalendarEvent/query':
|
|
579
|
-
return this.#eventQuery(args);
|
|
580
|
-
case 'CalendarEvent/get':
|
|
581
|
-
return this.#eventGet(args);
|
|
582
|
-
case 'CalendarEvent/set':
|
|
583
|
-
return this.#eventSet(args);
|
|
584
|
-
case 'CalendarEvent/changes':
|
|
585
|
-
return this.#eventChanges(args);
|
|
586
|
-
case 'Calendar/changes':
|
|
587
|
-
return this.#calendarChanges(args);
|
|
588
|
-
case 'Principal/getAvailability':
|
|
589
|
-
return this.#getAvailability(args);
|
|
590
|
-
case 'Principal/query':
|
|
591
|
-
return this.#principalQuery(args);
|
|
592
|
-
case 'Principal/get':
|
|
593
|
-
return this.#principalGet(args);
|
|
594
|
-
default:
|
|
595
|
-
return {
|
|
596
|
-
type: 'unknownMethod',
|
|
597
|
-
description: `the fake calendar does not implement ${method}`,
|
|
598
|
-
};
|
|
599
|
-
}
|
|
600
|
-
}
|
|
601
|
-
/** `Principal/query` filtered by email. The live server answers at most one
|
|
602
|
-
* id for an address, so this does too, and an address nobody has comes
|
|
603
|
-
* back as an empty list rather than an error (MSG-055 slice 3 plan). Any
|
|
604
|
-
* other filter is unsupported here rather than quietly ignored: a filter
|
|
605
|
-
* the fake pretends to honour is how this package lost two field names. */
|
|
606
|
-
#principalQuery(args) {
|
|
607
|
-
const accountId = String(args.accountId ?? this.me.accountId);
|
|
608
|
-
const filter = (args.filter ?? {});
|
|
609
|
-
const keys = Object.keys(filter);
|
|
610
|
-
if (keys.length !== 1 || keys[0] !== 'email') {
|
|
611
|
-
return {
|
|
612
|
-
type: 'unsupportedFilter',
|
|
613
|
-
description: 'the fake calendar only filters principals by email',
|
|
614
|
-
};
|
|
615
|
-
}
|
|
616
|
-
const id = this.#emailToAccountId.get(String(filter.email).toLowerCase());
|
|
617
|
-
return { accountId, queryState: 'p1', ids: id ? [id] : [] };
|
|
618
|
-
}
|
|
619
|
-
/** `Principal/get`, in the shape the live server sends: `description` is the
|
|
620
|
-
* friendly name and `name` repeats the address (`wire-live-transcript.test.ts`'s
|
|
621
|
-
* `LIVE_PRINCIPALS`). A seed with no name sends `null`, not a fabricated
|
|
622
|
-
* one, so the client's fallback is exercised rather than hidden. */
|
|
623
|
-
#principalGet(args) {
|
|
624
|
-
const accountId = String(args.accountId ?? this.me.accountId);
|
|
625
|
-
const ids = Array.isArray(args.ids) ? args.ids.map(String) : [...this.#principals.keys()];
|
|
626
|
-
const list = [];
|
|
627
|
-
const notFound = [];
|
|
628
|
-
for (const id of ids) {
|
|
629
|
-
const principal = this.#principals.get(id);
|
|
630
|
-
if (!principal) {
|
|
631
|
-
notFound.push(id);
|
|
632
|
-
continue;
|
|
633
|
-
}
|
|
634
|
-
list.push({
|
|
635
|
-
id: principal.accountId,
|
|
636
|
-
type: 'individual',
|
|
637
|
-
name: principal.email,
|
|
638
|
-
description: principal.name ?? null,
|
|
639
|
-
email: principal.email,
|
|
640
|
-
});
|
|
641
|
-
}
|
|
642
|
-
return { accountId, state: 'p1', list, notFound };
|
|
643
|
-
}
|
|
644
|
-
#calendarGet(args) {
|
|
645
|
-
const accountId = String(args.accountId ?? this.me.accountId);
|
|
646
|
-
const account = this.#account(accountId);
|
|
647
|
-
const list = [...account.calendars.values()].map((calendar) => ({
|
|
648
|
-
id: calendar.id,
|
|
649
|
-
name: calendar.name,
|
|
650
|
-
description: calendar.description ?? null,
|
|
651
|
-
color: calendar.color ?? null,
|
|
652
|
-
isVisible: calendar.isVisible,
|
|
653
|
-
includeInAvailability: calendar.includeInAvailability,
|
|
654
|
-
// Every calendar this account's own Calendar/get returns is one it
|
|
655
|
-
// owns, so myRights is always full (#138 §1) — this fake never models
|
|
656
|
-
// a shared calendar surfacing in its owner's own account list.
|
|
657
|
-
myRights: { ...ALL_RIGHTS },
|
|
658
|
-
shareWith: Object.fromEntries(Object.entries(calendar.shareWith).map(([grantee, rights]) => [
|
|
659
|
-
grantee,
|
|
660
|
-
fullRightsEcho(rights),
|
|
661
|
-
])),
|
|
662
|
-
}));
|
|
663
|
-
return { accountId, state: 'c1', list, notFound: [] };
|
|
664
|
-
}
|
|
665
|
-
/** Only `update` is implemented: `CalendarClient` never creates or
|
|
666
|
-
* destroys a calendar, only shares one via `shareWith` (`types.ts`'s
|
|
667
|
-
* `CalendarClient.shareCalendar`). */
|
|
668
|
-
#calendarSet(args) {
|
|
669
|
-
const accountId = String(args.accountId ?? this.me.accountId);
|
|
670
|
-
const account = this.#account(accountId);
|
|
671
|
-
const update = (args.update ?? {});
|
|
672
|
-
const updated = {};
|
|
673
|
-
const notUpdated = {};
|
|
674
|
-
const touched = new Map();
|
|
675
|
-
for (const [id, patch] of Object.entries(update)) {
|
|
676
|
-
const calendar = account.calendars.get(id);
|
|
677
|
-
if (!calendar) {
|
|
678
|
-
notUpdated[id] = { type: 'notFound' };
|
|
679
|
-
continue;
|
|
680
|
-
}
|
|
681
|
-
for (const [path, value] of Object.entries(patch)) {
|
|
682
|
-
if (path === 'shareWith') {
|
|
683
|
-
calendar.shareWith = value;
|
|
684
|
-
}
|
|
685
|
-
else if (path.startsWith('shareWith/')) {
|
|
686
|
-
// Un-escaped, because the client escapes: RFC 6901 order, `~1`
|
|
687
|
-
// before `~0`, or a literal `~1` in an id would decode wrong. No
|
|
688
|
-
// real account id carries either character, but a fake that skips
|
|
689
|
-
// the step is a fake that could disagree with the server without
|
|
690
|
-
// any test noticing.
|
|
691
|
-
const grantee = path
|
|
692
|
-
.slice('shareWith/'.length)
|
|
693
|
-
.replaceAll('~1', '/')
|
|
694
|
-
.replaceAll('~0', '~');
|
|
695
|
-
if (value === null)
|
|
696
|
-
delete calendar.shareWith[grantee];
|
|
697
|
-
else
|
|
698
|
-
calendar.shareWith[grantee] = value;
|
|
699
|
-
}
|
|
700
|
-
else if (path === 'isVisible') {
|
|
701
|
-
calendar.isVisible = Boolean(value);
|
|
702
|
-
}
|
|
703
|
-
else if (path === 'includeInAvailability') {
|
|
704
|
-
calendar.includeInAvailability = value;
|
|
705
|
-
}
|
|
706
|
-
else if (path === 'name') {
|
|
707
|
-
calendar.name = String(value);
|
|
708
|
-
}
|
|
709
|
-
else {
|
|
710
|
-
notUpdated[id] = { type: 'invalidPatch', description: `cannot patch ${path}` };
|
|
711
|
-
}
|
|
712
|
-
}
|
|
713
|
-
if (!notUpdated[id]) {
|
|
714
|
-
updated[id] = null;
|
|
715
|
-
touched.set(id, 'update');
|
|
716
|
-
}
|
|
717
|
-
}
|
|
718
|
-
this.#bumpCalendarLog(account, touched);
|
|
719
|
-
return {
|
|
720
|
-
accountId,
|
|
721
|
-
oldState: '1',
|
|
722
|
-
newState: '2',
|
|
723
|
-
created: null,
|
|
724
|
-
notCreated: null,
|
|
725
|
-
updated,
|
|
726
|
-
notUpdated: Object.keys(notUpdated).length > 0 ? notUpdated : null,
|
|
727
|
-
};
|
|
728
|
-
}
|
|
729
|
-
#eventQuery(args) {
|
|
730
|
-
const accountId = String(args.accountId ?? this.me.accountId);
|
|
731
|
-
const account = this.#account(accountId);
|
|
732
|
-
const filter = (args.filter ?? {});
|
|
733
|
-
const expand = args.expandRecurrences === true || filter.expandRecurrences === true;
|
|
734
|
-
const after = firstString(args.after, filter.after);
|
|
735
|
-
const before = firstString(args.before, filter.before);
|
|
736
|
-
// `text` -- `searchEvents`'s own filter (issue #17) -- matches a
|
|
737
|
-
// case-insensitive substring of either `title` or `description` in one
|
|
738
|
-
// pass, live-confirmed against Stalwart v0.16.20 (2026-09-21): no
|
|
739
|
-
// `after`/`before` at all is a valid, unbounded query, exactly like the
|
|
740
|
-
// unfiltered listing below.
|
|
741
|
-
const text = typeof filter.text === 'string' ? filter.text.toLowerCase() : undefined;
|
|
742
|
-
const matchesText = (event) => text === undefined ||
|
|
743
|
-
event.title.toLowerCase().includes(text) ||
|
|
744
|
-
(event.description?.toLowerCase().includes(text) ?? false);
|
|
745
|
-
const limit = typeof args.limit === 'number' ? args.limit : undefined;
|
|
746
|
-
const limited = (ids) => (limit === undefined ? ids : ids.slice(0, limit));
|
|
747
|
-
if (expand) {
|
|
748
|
-
if (!after || !before) {
|
|
749
|
-
return {
|
|
750
|
-
type: 'invalidArguments',
|
|
751
|
-
description: 'expandRecurrences requires both after and before',
|
|
752
|
-
};
|
|
753
|
-
}
|
|
754
|
-
const rangeAfter = new Date(after);
|
|
755
|
-
const rangeBefore = new Date(before);
|
|
756
|
-
const ids = [];
|
|
757
|
-
for (const event of account.events.values()) {
|
|
758
|
-
if (!matchesText(event))
|
|
759
|
-
continue;
|
|
760
|
-
if (event.recurrenceRule) {
|
|
761
|
-
for (const start of occurrenceStarts(new Date(`${event.start}Z`), event.recurrenceRule, rangeAfter, rangeBefore)) {
|
|
762
|
-
// An excluded occurrence is gone from the expansion, which is how
|
|
763
|
-
// Stalwart answers a destroy on one — see `#overrideFor`.
|
|
764
|
-
if (this.#overrideFor(event, start)?.excluded === true)
|
|
765
|
-
continue;
|
|
766
|
-
ids.push(occurrenceId(event.id, start));
|
|
767
|
-
}
|
|
768
|
-
}
|
|
769
|
-
else {
|
|
770
|
-
const start = new Date(`${event.start}Z`);
|
|
771
|
-
if (start >= rangeAfter && start < rangeBefore)
|
|
772
|
-
ids.push(event.id);
|
|
773
|
-
}
|
|
774
|
-
}
|
|
775
|
-
return {
|
|
776
|
-
accountId,
|
|
777
|
-
queryState: 'q1',
|
|
778
|
-
canCalculateChanges: false,
|
|
779
|
-
position: 0,
|
|
780
|
-
ids: limited(ids),
|
|
781
|
-
};
|
|
782
|
-
}
|
|
783
|
-
// Unexpanded: every master event, including a recurring one's own single
|
|
784
|
-
// id — never one of its occurrences (MSG-053 acceptance criteria).
|
|
785
|
-
const ids = [...account.events.values()]
|
|
786
|
-
.filter((event) => {
|
|
787
|
-
if (!matchesText(event))
|
|
788
|
-
return false;
|
|
789
|
-
if (!after && !before)
|
|
790
|
-
return true;
|
|
791
|
-
const start = new Date(`${event.start}Z`);
|
|
792
|
-
return (!after || start >= new Date(after)) && (!before || start < new Date(before));
|
|
793
|
-
})
|
|
794
|
-
.map((event) => event.id);
|
|
795
|
-
return {
|
|
796
|
-
accountId,
|
|
797
|
-
queryState: 'q1',
|
|
798
|
-
canCalculateChanges: false,
|
|
799
|
-
position: 0,
|
|
800
|
-
ids: limited(ids),
|
|
801
|
-
};
|
|
802
|
-
}
|
|
803
|
-
#eventGet(args) {
|
|
804
|
-
const accountId = String(args.accountId ?? this.me.accountId);
|
|
805
|
-
const account = this.#account(accountId);
|
|
806
|
-
const ids = (args.ids ?? []);
|
|
807
|
-
const list = [];
|
|
808
|
-
const notFound = [];
|
|
809
|
-
for (const id of ids) {
|
|
810
|
-
const split = splitOccurrenceId(id);
|
|
811
|
-
if (split) {
|
|
812
|
-
const master = account.events.get(split.masterId);
|
|
813
|
-
if (!master || !master.recurrenceRule) {
|
|
814
|
-
notFound.push(id);
|
|
815
|
-
continue;
|
|
816
|
-
}
|
|
817
|
-
list.push(this.#projectOccurrence(master, id, split.iso));
|
|
818
|
-
continue;
|
|
819
|
-
}
|
|
820
|
-
const event = account.events.get(id);
|
|
821
|
-
if (!event) {
|
|
822
|
-
notFound.push(id);
|
|
823
|
-
continue;
|
|
824
|
-
}
|
|
825
|
-
list.push({
|
|
826
|
-
...this.#projectEvent(event),
|
|
827
|
-
// Not part of the shape every caller reads -- only the
|
|
828
|
-
// 'following'-scope cleanup in `calendar-client.ts` asks a master
|
|
829
|
-
// directly for its own overrides, to exclude one a rule truncation
|
|
830
|
-
// just stranded past its new `until`. An occurrence's own get
|
|
831
|
-
// (`#projectOccurrence`, which never reaches this branch) has no
|
|
832
|
-
// business echoing the whole map back.
|
|
833
|
-
...(event.recurrenceOverrides
|
|
834
|
-
? { recurrenceOverrides: { ...event.recurrenceOverrides } }
|
|
835
|
-
: {}),
|
|
836
|
-
});
|
|
837
|
-
}
|
|
838
|
-
return { accountId, state: 'e1', list, notFound };
|
|
839
|
-
}
|
|
840
|
-
#projectEvent(event) {
|
|
841
|
-
return {
|
|
842
|
-
id: event.id,
|
|
843
|
-
calendarIds: { ...event.calendarIds },
|
|
844
|
-
uid: event.uid,
|
|
845
|
-
title: event.title,
|
|
846
|
-
description: event.description ?? null,
|
|
847
|
-
start: event.start,
|
|
848
|
-
timeZone: event.timeZone,
|
|
849
|
-
duration: event.duration,
|
|
850
|
-
// `showWithoutTime`/`locations`, not `isAllDay`/`location`: RFC 8984's
|
|
851
|
-
// own names, which `wire.ts`'s `eventFromWire` parses (its doc comment
|
|
852
|
-
// logs the mismatch with this contract's simpler names as a Finding
|
|
853
|
-
// for MSG-055 to confirm live).
|
|
854
|
-
showWithoutTime: event.isAllDay,
|
|
855
|
-
locations: locationToWireMap(event.location),
|
|
856
|
-
virtualLocations: virtualLocationsToWireMap(event.virtualLocations),
|
|
857
|
-
recurrenceRule: event.recurrenceRule ? { ...event.recurrenceRule } : null,
|
|
858
|
-
participants: event.participants
|
|
859
|
-
? Object.fromEntries(Object.entries(event.participants).map(([id, participant]) => [id, { ...participant }]))
|
|
860
|
-
: null,
|
|
861
|
-
alerts: event.alerts
|
|
862
|
-
? Object.fromEntries(Object.entries(event.alerts).map(([id, alert]) => [id, { ...alert }]))
|
|
863
|
-
: null,
|
|
864
|
-
links: event.links
|
|
865
|
-
? Object.fromEntries(Object.entries(event.links).map(([id, link]) => [id, { ...link }]))
|
|
866
|
-
: null,
|
|
867
|
-
status: event.status,
|
|
868
|
-
mayInviteSelf: event.mayInviteSelf ?? null,
|
|
869
|
-
mayInviteOthers: event.mayInviteOthers ?? null,
|
|
870
|
-
freeBusyStatus: event.freeBusyStatus ?? null,
|
|
871
|
-
sequence: event.sequence,
|
|
872
|
-
// Every event's own get carries this, equal to its own id when the
|
|
873
|
-
// event is not an occurrence -- live-confirmed against Stalwart
|
|
874
|
-
// v0.16.20 (wtfalch/calendar#14; corrects `types.ts`'s
|
|
875
|
-
// `CalendarEvent.baseEventId` doc comment, which had claimed it was
|
|
876
|
-
// absent on a master). `#projectOccurrence` overwrites this with the
|
|
877
|
-
// real master's id for an occurrence.
|
|
878
|
-
baseEventId: event.id,
|
|
879
|
-
};
|
|
880
|
-
}
|
|
881
|
-
/** A synthetic per-occurrence id, distinct from the master's — real
|
|
882
|
-
* Stalwart carries a `baseEventId` back-reference on exactly this shape
|
|
883
|
-
* (#137 "Recurrence"). No `recurrenceRule` on the occurrence itself: only
|
|
884
|
-
* the master carries the rule.
|
|
885
|
-
*
|
|
886
|
-
* Whatever the master's `recurrenceOverrides` says about this occurrence
|
|
887
|
-
* wins over the master's own fields, which is how a one-occurrence edit
|
|
888
|
-
* reads back. Confirmed live for MSG-055. */
|
|
889
|
-
#projectOccurrence(master, id, iso) {
|
|
890
|
-
const override = master.recurrenceOverrides?.[this.#overrideKey(iso)] ?? {};
|
|
891
|
-
const { excluded: _excluded, '@type': _type, ...fields } = override;
|
|
892
|
-
// Both in `start`'s own local, offset-free shape (no milliseconds, no
|
|
893
|
-
// trailing `Z`) -- live-confirmed against Stalwart v0.16.20
|
|
894
|
-
// (wtfalch/calendar#14). `recurrenceId` used to keep `iso`'s raw
|
|
895
|
-
// `Date#toISOString()` form (milliseconds and a trailing `Z`), which
|
|
896
|
-
// disagreed with `start` on the very same occurrence and, worse, wasn't
|
|
897
|
-
// even the shape `truncateSeriesBefore`'s own `until` arithmetic expects
|
|
898
|
-
// for the value it reads back through `getEvent`.
|
|
899
|
-
const local = iso.slice(0, 19);
|
|
900
|
-
return {
|
|
901
|
-
...this.#projectEvent(master),
|
|
902
|
-
id,
|
|
903
|
-
baseEventId: master.id,
|
|
904
|
-
recurrenceId: local,
|
|
905
|
-
start: local,
|
|
906
|
-
recurrenceRule: null,
|
|
907
|
-
...fields,
|
|
908
|
-
};
|
|
909
|
-
}
|
|
910
|
-
/** The key `recurrenceOverrides` is mapped by: a local date-time with no
|
|
911
|
-
* offset and no trailing `Z`, matching what the server returns as an
|
|
912
|
-
* occurrence's `recurrenceId`. */
|
|
913
|
-
#overrideKey(iso) {
|
|
914
|
-
return iso.replace(/Z$/, '').slice(0, 19);
|
|
915
|
-
}
|
|
916
|
-
#overrideFor(master, start) {
|
|
917
|
-
return master.recurrenceOverrides?.[this.#overrideKey(start.toISOString())];
|
|
918
|
-
}
|
|
919
|
-
#eventSet(args) {
|
|
920
|
-
const accountId = String(args.accountId ?? this.me.accountId);
|
|
921
|
-
const account = this.#account(accountId);
|
|
922
|
-
// Opt-in per request, unlike CalDAV's server-wide default — a caller
|
|
923
|
-
// that forgets this sends no invites (types.ts's `SchedulingOptions`;
|
|
924
|
-
// #137 "Scheduling").
|
|
925
|
-
const sendScheduling = args.sendSchedulingMessages === true;
|
|
926
|
-
// What `CalendarEvent/changes` reads back from, once this call finishes
|
|
927
|
-
// (wtfalch/calendar#65) -- every id below names a real, top-level event
|
|
928
|
-
// (a synthetic occurrence id's own touch is logged against its master,
|
|
929
|
-
// since only the master's data actually changed).
|
|
930
|
-
const touched = new Map();
|
|
931
|
-
const touch = (id, op) => touched.set(id, mergeOp(touched.get(id), op));
|
|
932
|
-
const create = (args.create ?? {});
|
|
933
|
-
const created = {};
|
|
934
|
-
for (const [key, draft] of Object.entries(create)) {
|
|
935
|
-
const event = this.#toWireEvent(draft);
|
|
936
|
-
account.events.set(event.id, event);
|
|
937
|
-
created[key] = { id: event.id, uid: event.uid, sequence: event.sequence };
|
|
938
|
-
touch(event.id, 'create');
|
|
939
|
-
if (sendScheduling)
|
|
940
|
-
this.#sendInvites(event);
|
|
941
|
-
}
|
|
942
|
-
const update = (args.update ?? {});
|
|
943
|
-
const updated = {};
|
|
944
|
-
const notUpdated = {};
|
|
945
|
-
for (const [id, patch] of Object.entries(update)) {
|
|
946
|
-
// A synthetic occurrence id is a real target: the server takes the patch
|
|
947
|
-
// and writes it into the master's `recurrenceOverrides` rather than
|
|
948
|
-
// touching the series. Confirmed live against Stalwart v0.16.20 for
|
|
949
|
-
// MSG-055 — `CalendarEvent/set {update: {<occurrenceId>: {…}}}` answers
|
|
950
|
-
// `updated`, and the other occurrences keep their own fields.
|
|
951
|
-
const split = splitOccurrenceId(id);
|
|
952
|
-
if (split) {
|
|
953
|
-
const master = account.events.get(split.masterId);
|
|
954
|
-
if (!master?.recurrenceRule) {
|
|
955
|
-
notUpdated[id] = { type: 'notFound' };
|
|
956
|
-
continue;
|
|
957
|
-
}
|
|
958
|
-
if (replyParticipantId(patch) !== null) {
|
|
959
|
-
// `respond` only ever targets a real event id, never an
|
|
960
|
-
// occurrence's synthetic one -- and a reply against one is refused
|
|
961
|
-
// outright, live-confirmed against Stalwart v0.16.20 for T11
|
|
962
|
-
// (https://github.com/wtfalch/calendar/issues/11). The fake used to
|
|
963
|
-
// silently write a `recurrenceOverrides` entry instead, which no
|
|
964
|
-
// live run ever produced.
|
|
965
|
-
notUpdated[id] = {
|
|
966
|
-
type: 'invalidProperties',
|
|
967
|
-
description: 'Multiple organizers found in iCalendar object',
|
|
968
|
-
properties: ['participants'],
|
|
969
|
-
};
|
|
970
|
-
continue;
|
|
971
|
-
}
|
|
972
|
-
this.#writeOverride(master, split.iso, patch);
|
|
973
|
-
updated[id] = null;
|
|
974
|
-
touch(master.id, 'update');
|
|
975
|
-
continue;
|
|
976
|
-
}
|
|
977
|
-
const event = account.events.get(id);
|
|
978
|
-
if (!event) {
|
|
979
|
-
notUpdated[id] = { type: 'notFound' };
|
|
980
|
-
continue;
|
|
981
|
-
}
|
|
982
|
-
// A reply -- `respond`'s own patch shape -- bumps nothing, on either
|
|
983
|
-
// side, but only when it comes from someone other than this copy's own
|
|
984
|
-
// organiser: T11 live re-capture found the organiser sending this exact
|
|
985
|
-
// shape on her own event is an ordinary organiser edit (`sequence`
|
|
986
|
-
// absent/0 -> 1 on every copy, the whole map mirrored), not a reply.
|
|
987
|
-
const replyId = replyParticipantId(patch);
|
|
988
|
-
this.#applyPatch(event, patch);
|
|
989
|
-
if (replyId !== null && !this.#isOrganiser(accountId, event)) {
|
|
990
|
-
updated[id] = null;
|
|
991
|
-
touch(event.id, 'update');
|
|
992
|
-
if (sendScheduling)
|
|
993
|
-
this.#propagateReply(accountId, event, replyId);
|
|
994
|
-
continue;
|
|
995
|
-
}
|
|
996
|
-
event.sequence += 1;
|
|
997
|
-
updated[id] = null;
|
|
998
|
-
touch(event.id, 'update');
|
|
999
|
-
if (sendScheduling)
|
|
1000
|
-
this.#propagateStatus(accountId, event);
|
|
1001
|
-
}
|
|
1002
|
-
const destroy = (args.destroy ?? []);
|
|
1003
|
-
for (const id of destroy) {
|
|
1004
|
-
// Destroying one occurrence destroys nothing: the server records
|
|
1005
|
-
// `{excluded: true}` against that recurrence id on the master, and the
|
|
1006
|
-
// occurrence drops out of the next expansion. Confirmed live.
|
|
1007
|
-
const split = splitOccurrenceId(id);
|
|
1008
|
-
if (split) {
|
|
1009
|
-
const master = account.events.get(split.masterId);
|
|
1010
|
-
if (master?.recurrenceRule) {
|
|
1011
|
-
this.#writeOverride(master, split.iso, { excluded: true });
|
|
1012
|
-
touch(master.id, 'update');
|
|
1013
|
-
}
|
|
1014
|
-
continue;
|
|
1015
|
-
}
|
|
1016
|
-
account.events.delete(id);
|
|
1017
|
-
touch(id, 'destroy');
|
|
1018
|
-
}
|
|
1019
|
-
this.#bumpEventLog(account, touched);
|
|
1020
|
-
return {
|
|
1021
|
-
accountId,
|
|
1022
|
-
oldState: '1',
|
|
1023
|
-
newState: '2',
|
|
1024
|
-
created,
|
|
1025
|
-
notCreated: null,
|
|
1026
|
-
updated,
|
|
1027
|
-
notUpdated: Object.keys(notUpdated).length > 0 ? notUpdated : null,
|
|
1028
|
-
destroyed: destroy,
|
|
1029
|
-
notDestroyed: null,
|
|
1030
|
-
};
|
|
1031
|
-
}
|
|
1032
|
-
/** Merge a patch into one occurrence's override on the master. The patch
|
|
1033
|
-
* arrives already in wire field names, so it is stored as it came and read
|
|
1034
|
-
* back by `#projectOccurrence`. */
|
|
1035
|
-
#writeOverride(master, iso, patch) {
|
|
1036
|
-
const key = this.#overrideKey(iso);
|
|
1037
|
-
const overrides = master.recurrenceOverrides ?? {};
|
|
1038
|
-
overrides[key] = { '@type': 'Event', ...(overrides[key] ?? {}), ...patch };
|
|
1039
|
-
master.recurrenceOverrides = overrides;
|
|
1040
|
-
}
|
|
1041
|
-
#toWireEvent(draft) {
|
|
1042
|
-
const id = `evt${++this.#counter}`;
|
|
1043
|
-
const calendarId = typeof draft.calendarId === 'string'
|
|
1044
|
-
? draft.calendarId
|
|
1045
|
-
: Object.keys(draft.calendarIds ?? {})[0];
|
|
1046
|
-
return {
|
|
1047
|
-
id,
|
|
1048
|
-
uid: typeof draft.uid === 'string' ? draft.uid : id,
|
|
1049
|
-
calendarIds: calendarId ? { [calendarId]: true } : {},
|
|
1050
|
-
title: typeof draft.title === 'string' ? draft.title : '',
|
|
1051
|
-
description: typeof draft.description === 'string' ? draft.description : undefined,
|
|
1052
|
-
start: typeof draft.start === 'string' ? draft.start : this.#now.toISOString().slice(0, 19),
|
|
1053
|
-
timeZone: draft.timeZone ?? null,
|
|
1054
|
-
duration: typeof draft.duration === 'string' ? draft.duration : 'PT1H',
|
|
1055
|
-
isAllDay: Boolean(draft.showWithoutTime ?? draft.isAllDay),
|
|
1056
|
-
location: firstLocationName(draft.locations) ??
|
|
1057
|
-
(typeof draft.location === 'string' ? draft.location : undefined),
|
|
1058
|
-
virtualLocations: virtualLocationsFromWireMap(draft.virtualLocations),
|
|
1059
|
-
recurrenceRule: draft.recurrenceRule,
|
|
1060
|
-
participants: normalizeParticipants(draft.participants),
|
|
1061
|
-
mayInviteSelf: draft.mayInviteSelf,
|
|
1062
|
-
mayInviteOthers: draft.mayInviteOthers,
|
|
1063
|
-
alerts: draft.alerts,
|
|
1064
|
-
links: draft.links,
|
|
1065
|
-
status: draft.status ?? 'confirmed',
|
|
1066
|
-
freeBusyStatus: draft.freeBusyStatus,
|
|
1067
|
-
sequence: 0,
|
|
1068
|
-
};
|
|
1069
|
-
}
|
|
1070
|
-
/** Land a copy straight in each known invitee's own calendar, unprompted —
|
|
1071
|
-
* exactly what live testing found real Stalwart does, `autoAddInvitations
|
|
1072
|
-
* = false` notwithstanding (#145 amendment). An invitee this fake has
|
|
1073
|
-
* never heard of is silently skipped: it has no calendar to land in, and
|
|
1074
|
-
* that is a gap in the seed data, not a bug worth a fake's own error
|
|
1075
|
-
* path. */
|
|
1076
|
-
#sendInvites(event) {
|
|
1077
|
-
if (!event.participants)
|
|
1078
|
-
return;
|
|
1079
|
-
for (const participant of Object.values(event.participants)) {
|
|
1080
|
-
// The scheme comes off first. A live Stalwart v0.16.20 writes
|
|
1081
|
-
// `mailto:bob@example.org` in `calendarAddress` -- pinned verbatim in
|
|
1082
|
-
// `test/wire-live-transcript.test.ts` -- while this map is keyed on the
|
|
1083
|
-
// bare address. Looking up the raw value found nothing for every
|
|
1084
|
-
// participant the real wire shape produces, so this fake delivered
|
|
1085
|
-
// invites only for addresses written the one way the server never
|
|
1086
|
-
// writes them.
|
|
1087
|
-
const inviteeId = this.#emailToAccountId.get(participant.calendarAddress.replace(/^mailto:/i, '').toLowerCase());
|
|
1088
|
-
if (!inviteeId || inviteeId === this.me.accountId)
|
|
1089
|
-
continue;
|
|
1090
|
-
const account = this.#account(inviteeId);
|
|
1091
|
-
const defaultCalendarId = [...account.calendars.keys()][0];
|
|
1092
|
-
if (!defaultCalendarId)
|
|
1093
|
-
continue;
|
|
1094
|
-
const copyId = `evt${++this.#counter}`;
|
|
1095
|
-
account.events.set(copyId, {
|
|
1096
|
-
...event,
|
|
1097
|
-
id: copyId,
|
|
1098
|
-
calendarIds: { [defaultCalendarId]: true },
|
|
1099
|
-
});
|
|
1100
|
-
this.invitesSent.push({ accountId: inviteeId, eventId: copyId, uid: event.uid });
|
|
1101
|
-
this.#bumpEventLog(account, new Map([[copyId, 'create']]));
|
|
1102
|
-
}
|
|
1103
|
-
}
|
|
1104
|
-
/** Whether `accountId` holds this copy's own `owner` role -- the
|
|
1105
|
-
* distinction between a reply and an organiser edit that merely looks
|
|
1106
|
-
* like one. A `participants/<id>/participationStatus`-shaped patch is a
|
|
1107
|
-
* reply only when it comes from someone other than the organiser:
|
|
1108
|
-
* live re-confirmed for T11
|
|
1109
|
-
* (https://github.com/wtfalch/calendar/issues/11) that the organiser
|
|
1110
|
-
* sending that exact shape on her own event is an ordinary edit --
|
|
1111
|
-
* `sequence` goes from absent/0 to `1` on every copy, and the whole
|
|
1112
|
-
* `participants` map mirrors, the same as any other organiser write. */
|
|
1113
|
-
#isOrganiser(accountId, event) {
|
|
1114
|
-
const owner = Object.values(event.participants ?? {}).find((p) => p.roles?.owner === true);
|
|
1115
|
-
if (!owner)
|
|
1116
|
-
return false;
|
|
1117
|
-
const ownerAccountId = this.#emailToAccountId.get(owner.calendarAddress.replace(/^mailto:/i, '').toLowerCase());
|
|
1118
|
-
return ownerAccountId === accountId;
|
|
1119
|
-
}
|
|
1120
|
-
/** Mirror this copy's whole `participants` map onto every other copy
|
|
1121
|
-
* sharing the same `uid`, in any account — the shared scheduling engine
|
|
1122
|
-
* real Stalwart runs underneath both CalDAV and JMAP (#145: "the reply
|
|
1123
|
-
* reached alice... with no action on her part"). Every organiser edit
|
|
1124
|
-
* takes this path, including one shaped exactly like a reply
|
|
1125
|
-
* (`#isOrganiser` above); `#propagateReply` below is the narrower path an
|
|
1126
|
-
* attendee's own `respond` takes. */
|
|
1127
|
-
#propagateStatus(fromAccountId, event) {
|
|
1128
|
-
for (const [accountId, account] of this.#accounts) {
|
|
1129
|
-
if (accountId === fromAccountId)
|
|
1130
|
-
continue;
|
|
1131
|
-
const touched = new Map();
|
|
1132
|
-
for (const other of account.events.values()) {
|
|
1133
|
-
if (other.uid !== event.uid)
|
|
1134
|
-
continue;
|
|
1135
|
-
other.participants = event.participants;
|
|
1136
|
-
other.sequence += 1;
|
|
1137
|
-
this.repliesSent.push({ accountId, eventId: other.id, uid: event.uid });
|
|
1138
|
-
touched.set(other.id, 'update');
|
|
1139
|
-
}
|
|
1140
|
-
this.#bumpEventLog(account, touched);
|
|
1141
|
-
}
|
|
1142
|
-
}
|
|
1143
|
-
/** A reply — `respond`'s own patch shape — carries only the one
|
|
1144
|
-
* participant's new `participationStatus` to every other copy sharing the
|
|
1145
|
-
* same `uid`, matched by address rather than by map key: a copy's own key
|
|
1146
|
-
* for the same person need not match another's. Two things `#propagateStatus`
|
|
1147
|
-
* above does that this deliberately does not: it never bumps `sequence`,
|
|
1148
|
-
* anywhere, and it never carries `participationComment` along —
|
|
1149
|
-
* live-confirmed for T11, a comment sent alongside a status change never
|
|
1150
|
-
* reached the organiser's own copy, so it must stay this replier's alone. */
|
|
1151
|
-
#propagateReply(fromAccountId, event, participantId) {
|
|
1152
|
-
const mine = event.participants?.[participantId];
|
|
1153
|
-
if (!mine)
|
|
1154
|
-
return;
|
|
1155
|
-
for (const [accountId, account] of this.#accounts) {
|
|
1156
|
-
if (accountId === fromAccountId)
|
|
1157
|
-
continue;
|
|
1158
|
-
const touched = new Map();
|
|
1159
|
-
for (const other of account.events.values()) {
|
|
1160
|
-
if (other.uid !== event.uid || !other.participants)
|
|
1161
|
-
continue;
|
|
1162
|
-
const entry = Object.entries(other.participants).find(([, p]) => p.calendarAddress === mine.calendarAddress);
|
|
1163
|
-
if (!entry)
|
|
1164
|
-
continue;
|
|
1165
|
-
const [otherId, existing] = entry;
|
|
1166
|
-
other.participants = {
|
|
1167
|
-
...other.participants,
|
|
1168
|
-
[otherId]: { ...existing, participationStatus: mine.participationStatus },
|
|
1169
|
-
};
|
|
1170
|
-
this.repliesSent.push({ accountId, eventId: other.id, uid: event.uid });
|
|
1171
|
-
touched.set(other.id, 'update');
|
|
1172
|
-
}
|
|
1173
|
-
this.#bumpEventLog(account, touched);
|
|
1174
|
-
}
|
|
1175
|
-
}
|
|
1176
|
-
#applyPatch(event, patch) {
|
|
1177
|
-
for (const [path, value] of Object.entries(patch)) {
|
|
1178
|
-
if (path.startsWith('participants/')) {
|
|
1179
|
-
const [participantId, field] = path.slice('participants/'.length).split('/');
|
|
1180
|
-
if (!participantId)
|
|
1181
|
-
continue;
|
|
1182
|
-
const participants = { ...(event.participants ?? {}) };
|
|
1183
|
-
if (field) {
|
|
1184
|
-
const existing = participants[participantId] ?? { calendarAddress: '' };
|
|
1185
|
-
participants[participantId] = { ...existing, [field]: value };
|
|
1186
|
-
}
|
|
1187
|
-
else if (value === null) {
|
|
1188
|
-
delete participants[participantId];
|
|
1189
|
-
}
|
|
1190
|
-
else {
|
|
1191
|
-
participants[participantId] = value;
|
|
1192
|
-
}
|
|
1193
|
-
event.participants = participants;
|
|
1194
|
-
}
|
|
1195
|
-
else if (path === 'participants') {
|
|
1196
|
-
event.participants = normalizeParticipants(value);
|
|
1197
|
-
}
|
|
1198
|
-
else if (path === 'mayInviteSelf') {
|
|
1199
|
-
event.mayInviteSelf = value;
|
|
1200
|
-
}
|
|
1201
|
-
else if (path === 'mayInviteOthers') {
|
|
1202
|
-
event.mayInviteOthers = value;
|
|
1203
|
-
}
|
|
1204
|
-
else if (path === 'calendarIds') {
|
|
1205
|
-
const calendarId = Object.keys(value ?? {})[0];
|
|
1206
|
-
if (calendarId)
|
|
1207
|
-
event.calendarIds = { [calendarId]: true };
|
|
1208
|
-
}
|
|
1209
|
-
else if (path === 'uid') {
|
|
1210
|
-
event.uid = String(value);
|
|
1211
|
-
}
|
|
1212
|
-
else if (path === 'title') {
|
|
1213
|
-
event.title = String(value);
|
|
1214
|
-
}
|
|
1215
|
-
else if (path === 'description') {
|
|
1216
|
-
event.description = typeof value === 'string' ? value : undefined;
|
|
1217
|
-
}
|
|
1218
|
-
else if (path === 'start') {
|
|
1219
|
-
event.start = String(value);
|
|
1220
|
-
}
|
|
1221
|
-
else if (path === 'timeZone') {
|
|
1222
|
-
event.timeZone = value;
|
|
1223
|
-
}
|
|
1224
|
-
else if (path === 'location') {
|
|
1225
|
-
event.location = typeof value === 'string' ? value : undefined;
|
|
1226
|
-
}
|
|
1227
|
-
else if (path === 'locations') {
|
|
1228
|
-
event.location = firstLocationName(value);
|
|
1229
|
-
}
|
|
1230
|
-
else if (path === 'virtualLocations') {
|
|
1231
|
-
event.virtualLocations = virtualLocationsFromWireMap(value);
|
|
1232
|
-
}
|
|
1233
|
-
else if (path === 'duration') {
|
|
1234
|
-
event.duration = String(value);
|
|
1235
|
-
}
|
|
1236
|
-
else if (path === 'showWithoutTime') {
|
|
1237
|
-
event.isAllDay = Boolean(value);
|
|
1238
|
-
}
|
|
1239
|
-
else if (path === 'recurrenceRule') {
|
|
1240
|
-
// `wire.ts`'s `patchToWire` sends a real wire `null` for
|
|
1241
|
-
// `recurrenceRule: null` (wtfalch/calendar#45), distinct from the
|
|
1242
|
-
// key being absent entirely -- this fake must unset the rule the
|
|
1243
|
-
// same way a live server does, not store a literal `null` where
|
|
1244
|
-
// every reader (`#projectEvent`, `#eventQuery`, `#periodsForEvent`)
|
|
1245
|
-
// expects either the rule object or `undefined`.
|
|
1246
|
-
event.recurrenceRule = value === null ? undefined : value;
|
|
1247
|
-
}
|
|
1248
|
-
else if (path.startsWith('recurrenceOverrides/')) {
|
|
1249
|
-
// A rule truncation for 'following' scope excludes a stranded future
|
|
1250
|
-
// override in the same write that shortens the rule
|
|
1251
|
-
// (`calendar-client.ts`'s `truncateSeriesBefore`) -- keys are always
|
|
1252
|
-
// a plain `recurrenceId` string, never containing `~` or `/`, so
|
|
1253
|
-
// this needs none of `shareWith`'s RFC 6901 unescaping.
|
|
1254
|
-
const key = path.slice('recurrenceOverrides/'.length);
|
|
1255
|
-
if (value === null) {
|
|
1256
|
-
// `updateSeries`' own re-key on a `start` move (wtfalch/calendar#43)
|
|
1257
|
-
// deletes the stale key in the same write it creates the shifted
|
|
1258
|
-
// one -- the same null-means-remove convention `#calendarSet`
|
|
1259
|
-
// already uses for a revoked `shareWith` grantee, above.
|
|
1260
|
-
if (event.recurrenceOverrides)
|
|
1261
|
-
delete event.recurrenceOverrides[key];
|
|
1262
|
-
}
|
|
1263
|
-
else {
|
|
1264
|
-
this.#writeOverride(event, key, value);
|
|
1265
|
-
}
|
|
1266
|
-
}
|
|
1267
|
-
else if (path === 'alerts') {
|
|
1268
|
-
event.alerts = value;
|
|
1269
|
-
}
|
|
1270
|
-
else if (path === 'links') {
|
|
1271
|
-
event.links = value;
|
|
1272
|
-
}
|
|
1273
|
-
else if (path === 'status') {
|
|
1274
|
-
event.status = value;
|
|
1275
|
-
}
|
|
1276
|
-
else if (path === 'freeBusyStatus') {
|
|
1277
|
-
event.freeBusyStatus = value;
|
|
1278
|
-
}
|
|
1279
|
-
// Anything else is accepted and ignored: this fake supports only the
|
|
1280
|
-
// patch paths this package's own client sends.
|
|
1281
|
-
}
|
|
1282
|
-
}
|
|
1283
|
-
/** Busy periods for the queried principal's calendars, gated by the ACL
|
|
1284
|
-
* share alone — `mayReadItems` is sufficient on its own; no share at all
|
|
1285
|
-
* answers empty (#145 amendment, contradicting #137's original
|
|
1286
|
-
* two-rights claim).
|
|
1287
|
-
*
|
|
1288
|
-
* The principal being asked about is a separate `id` argument, not the
|
|
1289
|
-
* method's own `accountId` — an earlier slice assumed the latter, on the
|
|
1290
|
-
* theory that `Principal/getAvailability` reads a *different* account the
|
|
1291
|
-
* way a shared-mailbox read does. Live testing for issue #13 found the
|
|
1292
|
-
* opposite: `accountId` is the *caller's* own account (this fake only
|
|
1293
|
-
* ever authenticates one session, so it is always `this.me.accountId`
|
|
1294
|
-
* and is not otherwise read here), and the range travels as
|
|
1295
|
-
* `utcStart`/`utcEnd` — `after`/`before` is kept as a fallback only
|
|
1296
|
-
* because nothing yet proves every caller has been updated to the real
|
|
1297
|
-
* names. The response, too, carries no `accountId` at all on the real
|
|
1298
|
-
* server (`test/availability-many.test.ts`'s pinned transcript). */
|
|
1299
|
-
#getAvailability(args) {
|
|
1300
|
-
const callerId = this.me.accountId;
|
|
1301
|
-
const principalId = String(args.id ?? args.accountId ?? '');
|
|
1302
|
-
const after = firstString(args.utcStart, args.after);
|
|
1303
|
-
const before = firstString(args.utcEnd, args.before);
|
|
1304
|
-
const rangeAfter = after ? new Date(after) : new Date(0);
|
|
1305
|
-
const rangeBefore = before ? new Date(before) : new Date(8_640_000_000_000_000);
|
|
1306
|
-
const account = this.#accounts.get(principalId);
|
|
1307
|
-
const periods = [];
|
|
1308
|
-
if (account) {
|
|
1309
|
-
for (const event of account.events.values()) {
|
|
1310
|
-
const calendarId = Object.keys(event.calendarIds)[0];
|
|
1311
|
-
const calendar = calendarId ? account.calendars.get(calendarId) : undefined;
|
|
1312
|
-
if (!calendar?.shareWith[callerId]?.mayReadItems)
|
|
1313
|
-
continue;
|
|
1314
|
-
periods.push(...this.#periodsForEvent(event, rangeAfter, rangeBefore));
|
|
1315
|
-
}
|
|
1316
|
-
}
|
|
1317
|
-
periods.sort((a, b) => (a.utcStart < b.utcStart ? -1 : 1));
|
|
1318
|
-
return { list: periods };
|
|
1319
|
-
}
|
|
1320
|
-
#periodsForEvent(event, rangeAfter, rangeBefore) {
|
|
1321
|
-
// A cancelled event never counted as busy; an event explicitly marked
|
|
1322
|
-
// 'free' (wtfalch/calendar#29) is the same case for a different reason --
|
|
1323
|
-
// its owner said outright that it should never produce a false conflict
|
|
1324
|
-
// in findTime(). Absent reads as 'busy', matching `wire.ts`'s own
|
|
1325
|
-
// `eventFromWire` default.
|
|
1326
|
-
if (event.status === 'cancelled' || event.freeBusyStatus === 'free')
|
|
1327
|
-
return [];
|
|
1328
|
-
const busyStatus = event.status === 'tentative' ? 'tentative' : 'confirmed';
|
|
1329
|
-
const durationMs = minutesFromDuration(event.duration) * 60_000;
|
|
1330
|
-
const starts = event.recurrenceRule
|
|
1331
|
-
? occurrenceStarts(new Date(`${event.start}Z`), event.recurrenceRule, rangeAfter, rangeBefore)
|
|
1332
|
-
: [new Date(`${event.start}Z`)];
|
|
1333
|
-
return starts
|
|
1334
|
-
.filter((start) => start < rangeBefore && new Date(start.getTime() + durationMs) > rangeAfter)
|
|
1335
|
-
.map((start) => ({
|
|
1336
|
-
utcStart: start.toISOString(),
|
|
1337
|
-
utcEnd: new Date(start.getTime() + durationMs).toISOString(),
|
|
1338
|
-
busyStatus,
|
|
1339
|
-
event: null,
|
|
1340
|
-
}));
|
|
1341
|
-
}
|
|
1342
|
-
#resolveRefs(args, done) {
|
|
1343
|
-
const out = {};
|
|
1344
|
-
for (const [key, value] of Object.entries(args)) {
|
|
1345
|
-
if (!key.startsWith('#')) {
|
|
1346
|
-
out[key] = value;
|
|
1347
|
-
continue;
|
|
1348
|
-
}
|
|
1349
|
-
const reference = value;
|
|
1350
|
-
const source = done.find(([, , id]) => id === reference.resultOf)?.[1];
|
|
1351
|
-
out[key.slice(1)] = source ? pointer(source, reference.path) : [];
|
|
1352
|
-
}
|
|
1353
|
-
return out;
|
|
1354
|
-
}
|
|
1355
|
-
/** A `fetch` that answers this calendar universe. Hand it to whatever the
|
|
1356
|
-
* package's client is built on. */
|
|
1357
|
-
fetch = async (input, init) => {
|
|
1358
|
-
if (this.#latency > 0)
|
|
1359
|
-
await new Promise((resolve) => setTimeout(resolve, this.#latency));
|
|
1360
|
-
const url = String(input);
|
|
1361
|
-
const json = (body) => new Response(JSON.stringify(body), {
|
|
1362
|
-
status: 200,
|
|
1363
|
-
headers: { 'Content-Type': 'application/json' },
|
|
1364
|
-
});
|
|
1365
|
-
if (!init || (init.method ?? 'GET') === 'GET') {
|
|
1366
|
-
if (url.includes('/jmap/eventsource')) {
|
|
1367
|
-
// An open stream that never sends: `subscribe` stays connected and
|
|
1368
|
-
// quiet, mirroring `@wtfalch/email/mailbox/fake`.
|
|
1369
|
-
return new Response(new ReadableStream(), {
|
|
1370
|
-
headers: { 'Content-Type': 'text/event-stream' },
|
|
1371
|
-
});
|
|
1372
|
-
}
|
|
1373
|
-
return json(this.session(new URL(url).origin));
|
|
1374
|
-
}
|
|
1375
|
-
const body = JSON.parse(String(init.body));
|
|
1376
|
-
if (body.methodCalls.length > MAX_CALLS_IN_REQUEST) {
|
|
1377
|
-
// The whole request is refused, before a single call in it runs --
|
|
1378
|
-
// measured live for issue #13, pinned as `LIVE_LIMIT_REFUSAL` in
|
|
1379
|
-
// `test/wire-live-transcript.test.ts`. A client that stops chunking
|
|
1380
|
-
// (or chunks to the wrong number) hits this the moment a fake-backed
|
|
1381
|
-
// test asks for more than `MAX_CALLS_IN_REQUEST` principals at once.
|
|
1382
|
-
return new Response(JSON.stringify({
|
|
1383
|
-
type: 'urn:ietf:params:jmap:error:limit',
|
|
1384
|
-
status: 400,
|
|
1385
|
-
detail: 'The request exceeds the maximum number of calls in a single request.',
|
|
1386
|
-
limit: 'maxCallsInRequest',
|
|
1387
|
-
}), { status: 400, headers: { 'Content-Type': 'application/json' } });
|
|
1388
|
-
}
|
|
1389
|
-
const responses = [];
|
|
1390
|
-
for (const [method, callArgs, id] of body.methodCalls) {
|
|
1391
|
-
const resolved = this.#resolveRefs(callArgs, responses);
|
|
1392
|
-
const result = this.call(method, resolved);
|
|
1393
|
-
const isError = typeof result.type === 'string' && ERROR_TYPES.has(result.type);
|
|
1394
|
-
responses.push([isError ? 'error' : method, result, id]);
|
|
1395
|
-
}
|
|
1396
|
-
return json({ methodResponses: responses, sessionState: 'fake-session' });
|
|
1397
|
-
};
|
|
1398
|
-
}
|