@wtfalch/calendar 0.2.0 → 0.3.1

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.
@@ -81,6 +81,20 @@ const ALL_RIGHTS = Object.fromEntries(RIGHTS.map((right) => [right, true]));
81
81
  function fullRightsEcho(rights) {
82
82
  return Object.fromEntries(RIGHTS.map((right) => [right, rights[right] === true]));
83
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
+ }
84
98
  const OCCURRENCE_SEPARATOR = '~';
85
99
  const MAX_OCCURRENCES = 1_000;
86
100
  /** The shared campaign Stalwart's own `urn:ietf:params:jmap:core.
@@ -286,7 +300,7 @@ function pointer(value, path) {
286
300
  }
287
301
  return current;
288
302
  }
289
- const ERROR_TYPES = new Set(['invalidArguments', 'unknownMethod']);
303
+ const ERROR_TYPES = new Set(['invalidArguments', 'unknownMethod', 'cannotCalculateChanges']);
290
304
  export class FakeCalendarStore {
291
305
  me;
292
306
  #now;
@@ -313,7 +327,14 @@ export class FakeCalendarStore {
313
327
  }
314
328
  }
315
329
  #seed(principal) {
316
- const bucket = { calendars: new Map(), events: new Map() };
330
+ const bucket = {
331
+ calendars: new Map(),
332
+ events: new Map(),
333
+ eventState: 0,
334
+ eventLog: [],
335
+ calendarState: 0,
336
+ calendarLog: [],
337
+ };
317
338
  for (const seedCalendar of principal.calendars) {
318
339
  bucket.calendars.set(seedCalendar.id, {
319
340
  id: seedCalendar.id,
@@ -355,14 +376,168 @@ export class FakeCalendarStore {
355
376
  #account(accountId) {
356
377
  let bucket = this.#accounts.get(accountId);
357
378
  if (!bucket) {
358
- bucket = { calendars: new Map(), events: new Map() };
379
+ bucket = {
380
+ calendars: new Map(),
381
+ events: new Map(),
382
+ eventState: 0,
383
+ eventLog: [],
384
+ calendarState: 0,
385
+ calendarLog: [],
386
+ };
359
387
  this.#accounts.set(accountId, bucket);
360
388
  }
361
389
  return bucket;
362
390
  }
363
- /** The session document, as Stalwart writes it. */
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
+ */
364
527
  session(origin) {
365
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
+ }
366
541
  return {
367
542
  capabilities: {
368
543
  'urn:ietf:params:jmap:core': { maxCallsInRequest: MAX_CALLS_IN_REQUEST },
@@ -377,17 +552,7 @@ export class FakeCalendarStore {
377
552
  },
378
553
  'urn:ietf:params:jmap:calendars:parse': {},
379
554
  },
380
- accounts: {
381
- [meId]: {
382
- name: this.me.email,
383
- isPersonal: true,
384
- isReadOnly: false,
385
- accountCapabilities: {
386
- 'urn:ietf:params:jmap:calendars': {},
387
- 'urn:ietf:params:jmap:calendars:parse': {},
388
- },
389
- },
390
- },
555
+ accounts,
391
556
  primaryAccounts: {
392
557
  'urn:ietf:params:jmap:calendars': meId,
393
558
  'urn:ietf:params:jmap:calendars:parse': meId,
@@ -416,6 +581,10 @@ export class FakeCalendarStore {
416
581
  return this.#eventGet(args);
417
582
  case 'CalendarEvent/set':
418
583
  return this.#eventSet(args);
584
+ case 'CalendarEvent/changes':
585
+ return this.#eventChanges(args);
586
+ case 'Calendar/changes':
587
+ return this.#calendarChanges(args);
419
588
  case 'Principal/getAvailability':
420
589
  return this.#getAvailability(args);
421
590
  case 'Principal/query':
@@ -502,6 +671,7 @@ export class FakeCalendarStore {
502
671
  const update = (args.update ?? {});
503
672
  const updated = {};
504
673
  const notUpdated = {};
674
+ const touched = new Map();
505
675
  for (const [id, patch] of Object.entries(update)) {
506
676
  const calendar = account.calendars.get(id);
507
677
  if (!calendar) {
@@ -540,9 +710,12 @@ export class FakeCalendarStore {
540
710
  notUpdated[id] = { type: 'invalidPatch', description: `cannot patch ${path}` };
541
711
  }
542
712
  }
543
- if (!notUpdated[id])
713
+ if (!notUpdated[id]) {
544
714
  updated[id] = null;
715
+ touched.set(id, 'update');
716
+ }
545
717
  }
718
+ this.#bumpCalendarLog(account, touched);
546
719
  return {
547
720
  accountId,
548
721
  oldState: '1',
@@ -692,6 +865,8 @@ export class FakeCalendarStore {
692
865
  ? Object.fromEntries(Object.entries(event.links).map(([id, link]) => [id, { ...link }]))
693
866
  : null,
694
867
  status: event.status,
868
+ mayInviteSelf: event.mayInviteSelf ?? null,
869
+ mayInviteOthers: event.mayInviteOthers ?? null,
695
870
  freeBusyStatus: event.freeBusyStatus ?? null,
696
871
  sequence: event.sequence,
697
872
  // Every event's own get carries this, equal to its own id when the
@@ -748,12 +923,19 @@ export class FakeCalendarStore {
748
923
  // that forgets this sends no invites (types.ts's `SchedulingOptions`;
749
924
  // #137 "Scheduling").
750
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));
751
932
  const create = (args.create ?? {});
752
933
  const created = {};
753
934
  for (const [key, draft] of Object.entries(create)) {
754
935
  const event = this.#toWireEvent(draft);
755
936
  account.events.set(event.id, event);
756
937
  created[key] = { id: event.id, uid: event.uid, sequence: event.sequence };
938
+ touch(event.id, 'create');
757
939
  if (sendScheduling)
758
940
  this.#sendInvites(event);
759
941
  }
@@ -789,6 +971,7 @@ export class FakeCalendarStore {
789
971
  }
790
972
  this.#writeOverride(master, split.iso, patch);
791
973
  updated[id] = null;
974
+ touch(master.id, 'update');
792
975
  continue;
793
976
  }
794
977
  const event = account.events.get(id);
@@ -805,12 +988,14 @@ export class FakeCalendarStore {
805
988
  this.#applyPatch(event, patch);
806
989
  if (replyId !== null && !this.#isOrganiser(accountId, event)) {
807
990
  updated[id] = null;
991
+ touch(event.id, 'update');
808
992
  if (sendScheduling)
809
993
  this.#propagateReply(accountId, event, replyId);
810
994
  continue;
811
995
  }
812
996
  event.sequence += 1;
813
997
  updated[id] = null;
998
+ touch(event.id, 'update');
814
999
  if (sendScheduling)
815
1000
  this.#propagateStatus(accountId, event);
816
1001
  }
@@ -822,12 +1007,16 @@ export class FakeCalendarStore {
822
1007
  const split = splitOccurrenceId(id);
823
1008
  if (split) {
824
1009
  const master = account.events.get(split.masterId);
825
- if (master?.recurrenceRule)
1010
+ if (master?.recurrenceRule) {
826
1011
  this.#writeOverride(master, split.iso, { excluded: true });
1012
+ touch(master.id, 'update');
1013
+ }
827
1014
  continue;
828
1015
  }
829
1016
  account.events.delete(id);
1017
+ touch(id, 'destroy');
830
1018
  }
1019
+ this.#bumpEventLog(account, touched);
831
1020
  return {
832
1021
  accountId,
833
1022
  oldState: '1',
@@ -869,6 +1058,8 @@ export class FakeCalendarStore {
869
1058
  virtualLocations: virtualLocationsFromWireMap(draft.virtualLocations),
870
1059
  recurrenceRule: draft.recurrenceRule,
871
1060
  participants: normalizeParticipants(draft.participants),
1061
+ mayInviteSelf: draft.mayInviteSelf,
1062
+ mayInviteOthers: draft.mayInviteOthers,
872
1063
  alerts: draft.alerts,
873
1064
  links: draft.links,
874
1065
  status: draft.status ?? 'confirmed',
@@ -907,6 +1098,7 @@ export class FakeCalendarStore {
907
1098
  calendarIds: { [defaultCalendarId]: true },
908
1099
  });
909
1100
  this.invitesSent.push({ accountId: inviteeId, eventId: copyId, uid: event.uid });
1101
+ this.#bumpEventLog(account, new Map([[copyId, 'create']]));
910
1102
  }
911
1103
  }
912
1104
  /** Whether `accountId` holds this copy's own `owner` role -- the
@@ -936,13 +1128,16 @@ export class FakeCalendarStore {
936
1128
  for (const [accountId, account] of this.#accounts) {
937
1129
  if (accountId === fromAccountId)
938
1130
  continue;
1131
+ const touched = new Map();
939
1132
  for (const other of account.events.values()) {
940
1133
  if (other.uid !== event.uid)
941
1134
  continue;
942
1135
  other.participants = event.participants;
943
1136
  other.sequence += 1;
944
1137
  this.repliesSent.push({ accountId, eventId: other.id, uid: event.uid });
1138
+ touched.set(other.id, 'update');
945
1139
  }
1140
+ this.#bumpEventLog(account, touched);
946
1141
  }
947
1142
  }
948
1143
  /** A reply — `respond`'s own patch shape — carries only the one
@@ -960,6 +1155,7 @@ export class FakeCalendarStore {
960
1155
  for (const [accountId, account] of this.#accounts) {
961
1156
  if (accountId === fromAccountId)
962
1157
  continue;
1158
+ const touched = new Map();
963
1159
  for (const other of account.events.values()) {
964
1160
  if (other.uid !== event.uid || !other.participants)
965
1161
  continue;
@@ -972,7 +1168,9 @@ export class FakeCalendarStore {
972
1168
  [otherId]: { ...existing, participationStatus: mine.participationStatus },
973
1169
  };
974
1170
  this.repliesSent.push({ accountId, eventId: other.id, uid: event.uid });
1171
+ touched.set(other.id, 'update');
975
1172
  }
1173
+ this.#bumpEventLog(account, touched);
976
1174
  }
977
1175
  }
978
1176
  #applyPatch(event, patch) {
@@ -997,6 +1195,12 @@ export class FakeCalendarStore {
997
1195
  else if (path === 'participants') {
998
1196
  event.participants = normalizeParticipants(value);
999
1197
  }
1198
+ else if (path === 'mayInviteSelf') {
1199
+ event.mayInviteSelf = value;
1200
+ }
1201
+ else if (path === 'mayInviteOthers') {
1202
+ event.mayInviteOthers = value;
1203
+ }
1000
1204
  else if (path === 'calendarIds') {
1001
1205
  const calendarId = Object.keys(value ?? {})[0];
1002
1206
  if (calendarId)
@@ -1033,7 +1237,13 @@ export class FakeCalendarStore {
1033
1237
  event.isAllDay = Boolean(value);
1034
1238
  }
1035
1239
  else if (path === 'recurrenceRule') {
1036
- event.recurrenceRule = value;
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;
1037
1247
  }
1038
1248
  else if (path.startsWith('recurrenceOverrides/')) {
1039
1249
  // A rule truncation for 'following' scope excludes a stranded future
@@ -1041,7 +1251,18 @@ export class FakeCalendarStore {
1041
1251
  // (`calendar-client.ts`'s `truncateSeriesBefore`) -- keys are always
1042
1252
  // a plain `recurrenceId` string, never containing `~` or `/`, so
1043
1253
  // this needs none of `shareWith`'s RFC 6901 unescaping.
1044
- this.#writeOverride(event, path.slice('recurrenceOverrides/'.length), value);
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
+ }
1045
1266
  }
1046
1267
  else if (path === 'alerts') {
1047
1268
  event.alerts = value;
@@ -1,9 +1,12 @@
1
1
  /**
2
2
  * Export a `CalendarEvent` (or several) as an RFC 5545 `.ics` document
3
- * (wtfalch/calendar#28). Read-only feeds and `.ics` import are the other
4
- * half of this gap, tracked separately (agora#159,
5
- * https://github.com/wtfalch/agora/issues/159) and deferred with a named
6
- * home (`PRODUCT.md`); this file is export only.
3
+ * (wtfalch/calendar#28), and `icsToEventDrafts` to import one back
4
+ * (wtfalch/calendar#41, the other half of agora#159,
5
+ * https://github.com/wtfalch/agora/issues/159). Read-only subscription feeds
6
+ * are still a separate, deferred gap (`PRODUCT.md`) -- `icsToEventDrafts` is
7
+ * a one-time parse, not a poller, and has no opinion on where its output
8
+ * ends up (`CalendarClient.importIcs`, `types.ts`, calls `createEvent` once
9
+ * per draft).
7
10
  *
8
11
  * **Every date-time is written in UTC (`Z`-suffixed), naively.** `start` is
9
12
  * a local date-time with no offset, and `timeZone` says which zone it is
@@ -30,7 +33,7 @@
30
33
  * (`EventDetail.tsx` has no export control at all, not "an export control
31
34
  * that drops one field"), so adding them is left to a later ticket.
32
35
  */
33
- import type { CalendarEvent } from './types.ts';
36
+ import type { CalendarEvent, CalendarEventDraft, ImportIcsSkippedEvent } from './types.ts';
34
37
  export type IcsExportOptions = {
35
38
  /** The `DTSTAMP` moment. Injectable so a caller (or a test) does not have
36
39
  * to accept the real wall clock, mirroring `EventEditor`'s/`Calendar`'s
@@ -45,3 +48,26 @@ export declare function eventsToIcs(events: readonly CalendarEvent[], options?:
45
48
  /** A single event's own `.ics` document -- `EventDetail`'s "Download .ics"
46
49
  * control (wtfalch/calendar#28) is this, one event at a time. */
47
50
  export declare function eventToIcs(event: CalendarEvent, options?: IcsExportOptions): string;
51
+ /**
52
+ * One `CalendarEventDraft` per `VEVENT` in an RFC 5545 `.ics` document --
53
+ * the inverse of `eventsToIcs` (wtfalch/calendar#41). `calendarId` on each
54
+ * draft is a placeholder empty string: this function only ever sees the
55
+ * document, never the calendar it is being imported into, so
56
+ * `CalendarClient.importIcs` (`calendar-client.ts`) overwrites it before
57
+ * calling `createEvent`.
58
+ *
59
+ * A `VEVENT` outside a `BEGIN:VCALENDAR`/`END:VCALENDAR` pair, or with no
60
+ * matching `END:VEVENT`, is silently not collected -- the same tolerance a
61
+ * hand-written or partially-truncated `.ics` file needs, since this is a
62
+ * one-time import rather than a validator.
63
+ *
64
+ * A `VEVENT` that parses structurally but that `veventToDraft` cannot turn
65
+ * into a draft (no `DTSTART`, an `RRULE` `FREQ` this package does not
66
+ * recognise) is caught per event and reported in `skipped` rather than
67
+ * thrown -- one malformed `VEVENT` used to abort the whole document and
68
+ * discard every other, otherwise-valid one in it (wtfalch/calendar#46).
69
+ */
70
+ export declare function icsToEventDrafts(ics: string): {
71
+ readonly drafts: readonly CalendarEventDraft[];
72
+ readonly skipped: readonly ImportIcsSkippedEvent[];
73
+ };