@wtfalch/email 0.14.0 → 0.15.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.
@@ -0,0 +1,116 @@
1
+ import ICAL from 'ical.js';
2
+ /**
3
+ * An `ICAL.Time` as a `Date`, the instant it names.
4
+ *
5
+ * **A floating time is read as UTC, not the machine's own zone.** `ical.js`
6
+ * defaults an unzoned time to `ICAL.Timezone.localTimezone`, and its own
7
+ * `toJSDate()` then builds the `Date` from wall-clock numbers read as
8
+ * *local* time -- which would make parsing the same message answer
9
+ * differently depending on where the code runs. RFC 5545 §3.3.5 gives a
10
+ * floating time no zone at all; UTC is this module's own choice of how to
11
+ * anchor it deterministically, not a rule the RFC states. A `TZID` that
12
+ * *did* resolve -- against the message's own `VTIMEZONE`, which is how
13
+ * `ical.js` hydrates one (`Component.getTimeZoneByID` walks up to the
14
+ * `VCALENDAR` and matches on the embedded component, no registration
15
+ * needed) -- carries a real zone other than `localTimezone`, so it still
16
+ * goes through `toJSDate()` on the line below.
17
+ */
18
+ function toDate(time) {
19
+ if (time.zone === ICAL.Timezone.localTimezone) {
20
+ return new Date(Date.UTC(time.year, time.month - 1, time.day, time.hour, time.minute, time.second));
21
+ }
22
+ return time.toJSDate();
23
+ }
24
+ /** `ORGANIZER`/`ATTENDEE`: the `mailto:` URI as a plain address, with `CN`
25
+ * when the property carried one. `null` for anything that is not a
26
+ * string value -- a cal-address ical.js could not make sense of. */
27
+ function person(property) {
28
+ const value = property?.getFirstValue();
29
+ if (typeof value !== 'string')
30
+ return null;
31
+ const email = value.replace(/^mailto:/i, '').trim();
32
+ if (!email)
33
+ return null;
34
+ const name = property?.getFirstParameter('cn');
35
+ return typeof name === 'string' && name ? { email, name } : { email };
36
+ }
37
+ function text(value) {
38
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
39
+ }
40
+ /**
41
+ * Read an iTIP `COUNTER` or `DECLINECOUNTER` out of its `VCALENDAR` text.
42
+ *
43
+ * **Never throws.** Malformed text, a `VCALENDAR` with no `VEVENT`, an
44
+ * event missing a property this module requires, or any other method --
45
+ * `REQUEST`, `REPLY`, `CANCEL`, all of them the server's own iTIP engine
46
+ * owns (#97) -- all answer `null` rather than raise, since this reads mail
47
+ * nobody here wrote.
48
+ */
49
+ export function parseImip(ics) {
50
+ try {
51
+ return read(ics);
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ }
57
+ function read(ics) {
58
+ const vcalendar = new ICAL.Component(ICAL.parse(ics));
59
+ if (vcalendar.name !== 'vcalendar')
60
+ return null;
61
+ const method = String(vcalendar.getFirstPropertyValue('method') ?? '').toUpperCase();
62
+ if (method !== 'COUNTER' && method !== 'DECLINECOUNTER')
63
+ return null;
64
+ const vevent = vcalendar.getFirstSubcomponent('vevent');
65
+ if (!vevent)
66
+ return null;
67
+ const uid = text(vevent.getFirstPropertyValue('uid'));
68
+ const sequenceValue = vevent.getFirstPropertyValue('sequence');
69
+ const dtstamp = vevent.getFirstPropertyValue('dtstamp');
70
+ const organizer = person(vevent.getFirstProperty('organizer'));
71
+ const attendee = person(vevent.getFirstProperty('attendee'));
72
+ if (uid === undefined ||
73
+ typeof sequenceValue !== 'number' ||
74
+ !(dtstamp instanceof ICAL.Time) ||
75
+ !organizer ||
76
+ !attendee) {
77
+ return null;
78
+ }
79
+ const recurrenceIdValue = vevent.getFirstPropertyValue('recurrence-id');
80
+ const recurrenceId = recurrenceIdValue instanceof ICAL.Time ? toDate(recurrenceIdValue) : undefined;
81
+ const comment = text(vevent.getFirstPropertyValue('comment'));
82
+ const stamp = toDate(dtstamp);
83
+ if (method === 'DECLINECOUNTER') {
84
+ return {
85
+ method,
86
+ uid,
87
+ sequence: sequenceValue,
88
+ organizer,
89
+ attendee,
90
+ ...(recurrenceId ? { recurrenceId } : {}),
91
+ ...(comment ? { comment } : {}),
92
+ stamp,
93
+ };
94
+ }
95
+ const summary = text(vevent.getFirstPropertyValue('summary'));
96
+ const startValue = vevent.getFirstPropertyValue('dtstart');
97
+ const endValue = vevent.getFirstPropertyValue('dtend');
98
+ if (summary === undefined ||
99
+ !(startValue instanceof ICAL.Time) ||
100
+ !(endValue instanceof ICAL.Time)) {
101
+ return null;
102
+ }
103
+ return {
104
+ method,
105
+ uid,
106
+ sequence: sequenceValue,
107
+ summary,
108
+ organizer,
109
+ attendee,
110
+ start: toDate(startValue),
111
+ end: toDate(endValue),
112
+ ...(recurrenceId ? { recurrenceId } : {}),
113
+ ...(comment ? { comment } : {}),
114
+ stamp,
115
+ };
116
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The shapes `@wtfalch/email/imip` composes, parses and hands back.
3
+ *
4
+ * Plain fields in, a typed union out (#102): this module takes no
5
+ * dependency on `@wtfalch/calendar` or any other calendar model, and every
6
+ * type here is data a caller can build or read without `ical.js` --
7
+ * `ical.js` itself stays behind `compose.ts` and `parse.ts`.
8
+ */
9
+ /** One person on a proposal: the organizer of the event, or the attendee
10
+ * proposing a new time for it. */
11
+ export type ImipPerson = {
12
+ email: string;
13
+ name?: string;
14
+ };
15
+ /** What an attendee sends to propose a new time for an event they are not
16
+ * organizing. One `VEVENT`, RFC 5546 §3.2.7: the original `UID` and
17
+ * `SEQUENCE` echoed back, so the organizer can tell which event and which
18
+ * version of it this answers, and the slot being proposed. */
19
+ export type CounterInput = {
20
+ uid: string;
21
+ /** Echoed from the event being countered, not incremented -- RFC 5546
22
+ * §3.2.7 requires a `COUNTER` to carry the organizer's own `SEQUENCE`. */
23
+ sequence: number;
24
+ /** Set only when the proposal is for one instance of a recurring event,
25
+ * never the series. */
26
+ recurrenceId?: Date;
27
+ summary: string;
28
+ organizer: ImipPerson;
29
+ /** The person proposing the new time -- never the organizer. */
30
+ attendee: ImipPerson;
31
+ /** The proposed start of the slot, compared to the event's current one. */
32
+ start: Date;
33
+ end: Date;
34
+ comment?: string;
35
+ };
36
+ /** What an organizer sends back to refuse a `CounterInput`, RFC 5546 §3.2.8.
37
+ * It proposes nothing, so it carries none of the fields that would: no
38
+ * `summary`, no slot. */
39
+ export type DeclineCounterInput = Omit<CounterInput, 'start' | 'end' | 'summary'>;
40
+ /** A composed iTIP message, ready to ride as a `text/calendar` body part
41
+ * whose `Content-Type` carries `method=<method>` (see the PR for why the
42
+ * JMAP `type` field is where that parameter goes). */
43
+ export type CalendarPart = {
44
+ method: 'COUNTER' | 'DECLINECOUNTER';
45
+ ics: string;
46
+ };
47
+ /** A parsed iTIP message: the input that built it, tagged with its method
48
+ * and the `DTSTAMP` every iTIP message carries (RFC 5546 §3.2.7/§3.2.8). */
49
+ export type Imip = ({
50
+ method: 'COUNTER';
51
+ } & CounterInput & {
52
+ stamp: Date;
53
+ }) | ({
54
+ method: 'DECLINECOUNTER';
55
+ } & DeclineCounterInput & {
56
+ stamp: Date;
57
+ });
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The shapes `@wtfalch/email/imip` composes, parses and hands back.
3
+ *
4
+ * Plain fields in, a typed union out (#102): this module takes no
5
+ * dependency on `@wtfalch/calendar` or any other calendar model, and every
6
+ * type here is data a caller can build or read without `ical.js` --
7
+ * `ical.js` itself stays behind `compose.ts` and `parse.ts`.
8
+ */
9
+ export {};
@@ -2,6 +2,12 @@ import { JamClient } from 'jmap-jam';
2
2
  import type { MailAccount, MailSession } from './types.ts';
3
3
  export declare const MAIL_CAPABILITY = "urn:ietf:params:jmap:mail";
4
4
  export declare const SUBMISSION_CAPABILITY = "urn:ietf:params:jmap:submission";
5
+ /** RFC 9661, "JMAP for Sieve Scripts". `jmap-jam` does not know this
6
+ * capability (its `knownCapabilities` table stops at RFC 8621), so
7
+ * `sieve.ts` supplies it by hand through `RequestOptions.using` on every
8
+ * call, the same thing `submit.ts`'s `send()` does for the mail capability
9
+ * alongside `EmailSubmission/set`. */
10
+ export declare const SIEVE_CAPABILITY = "urn:ietf:params:jmap:sieve";
5
11
  /** The parts of the JMAP session document this package uses. */
6
12
  type SessionDocument = {
7
13
  username: string;
@@ -3,6 +3,12 @@ import { MailError, guard } from "./errors.js";
3
3
  import { expandTemplate } from "./uri.js";
4
4
  export const MAIL_CAPABILITY = 'urn:ietf:params:jmap:mail';
5
5
  export const SUBMISSION_CAPABILITY = 'urn:ietf:params:jmap:submission';
6
+ /** RFC 9661, "JMAP for Sieve Scripts". `jmap-jam` does not know this
7
+ * capability (its `knownCapabilities` table stops at RFC 8621), so
8
+ * `sieve.ts` supplies it by hand through `RequestOptions.using` on every
9
+ * call, the same thing `submit.ts`'s `send()` does for the mail capability
10
+ * alongside `EmailSubmission/set`. */
11
+ export const SIEVE_CAPABILITY = 'urn:ietf:params:jmap:sieve';
6
12
  /** A size limit, or `null` for anything that is not a usable one. */
7
13
  function positive(value) {
8
14
  return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : null;
@@ -76,6 +76,30 @@ export class FakeMailbox {
76
76
  /** Every blob uploaded, for a test that asserts the bytes reached the
77
77
  * server rather than only the composer. */
78
78
  uploads = [];
79
+ /** RFC 8621 §8's singleton, `id: 'singleton'` always -- there is no create
80
+ * or destroy for it, only the one object every account starts with, off
81
+ * and empty. */
82
+ #vacation = {
83
+ isEnabled: false,
84
+ fromDate: null,
85
+ toDate: null,
86
+ subject: null,
87
+ textBody: null,
88
+ htmlBody: null,
89
+ };
90
+ /** An uploaded blob's actual bytes, as text, keyed by the id `uploads`
91
+ * also records. Nothing else in this fake stores content -- an
92
+ * attachment's synthetic blobId (`add()`, above) is never a key here, so
93
+ * `/jmap/download/` falls back to its fixed stub for those, unchanged.
94
+ * Sieve scripts read back what was uploaded, and a body part derived
95
+ * from a `bodyStructure` create (`#deriveBodyParts`) stores its bytes
96
+ * here too, so an iMIP part downloads as what was sent. */
97
+ #blobContents = new Map();
98
+ /** `SieveScript` objects: `{id, name, blobId}` triples, `isActive` derived
99
+ * from `#activeSieveScriptId` -- the same shape `SieveProperty` has on the
100
+ * real server (`jmap-proto/src/object/sieve.rs:19-24`). */
101
+ #sieveScripts = [];
102
+ #activeSieveScriptId = null;
79
103
  constructor(options = {}) {
80
104
  this.me = options.me ?? { name: 'Ada Lovelace', email: 'ada@example.com' };
81
105
  this.#now = options.now ?? new Date('2026-09-07T12:00:00Z');
@@ -216,6 +240,8 @@ export class FakeMailbox {
216
240
  'urn:ietf:params:jmap:core': { maxSizeUpload: this.#maxSizeUpload },
217
241
  'urn:ietf:params:jmap:mail': {},
218
242
  'urn:ietf:params:jmap:submission': {},
243
+ 'urn:ietf:params:jmap:vacationresponse': {},
244
+ 'urn:ietf:params:jmap:sieve': {},
219
245
  },
220
246
  accounts: {
221
247
  [ACCOUNT]: {
@@ -225,6 +251,8 @@ export class FakeMailbox {
225
251
  accountCapabilities: {
226
252
  'urn:ietf:params:jmap:mail': { maxSizeAttachmentsPerEmail: STALWART_MAX_SIZE },
227
253
  'urn:ietf:params:jmap:submission': {},
254
+ 'urn:ietf:params:jmap:vacationresponse': {},
255
+ 'urn:ietf:params:jmap:sieve': {},
228
256
  },
229
257
  },
230
258
  },
@@ -402,6 +430,70 @@ export class FakeMailbox {
402
430
  ],
403
431
  notFound: [],
404
432
  };
433
+ case 'VacationResponse/get':
434
+ return {
435
+ accountId: ACCOUNT,
436
+ state: 'vr1',
437
+ list: [{ id: 'singleton', ...this.#vacation }],
438
+ notFound: [],
439
+ };
440
+ case 'VacationResponse/set': {
441
+ // Neither created nor destroyed: RFC 8621 §8.1 fixes the object's id
442
+ // at `singleton` from the start, so the only legal write is an
443
+ // update of that one id.
444
+ const create = (args.create ?? {});
445
+ const notCreated = {};
446
+ for (const key of Object.keys(create)) {
447
+ notCreated[key] = {
448
+ type: 'forbidden',
449
+ description: 'the vacation response is a singleton; update "singleton" instead',
450
+ };
451
+ }
452
+ const destroy = (args.destroy ?? []);
453
+ const notDestroyed = {};
454
+ for (const id of destroy) {
455
+ notDestroyed[id] = {
456
+ type: 'forbidden',
457
+ description: 'the vacation response cannot be destroyed',
458
+ };
459
+ }
460
+ const update = (args.update ?? {});
461
+ const updated = {};
462
+ const notUpdated = {};
463
+ for (const [id, patch] of Object.entries(update)) {
464
+ if (id !== 'singleton') {
465
+ notUpdated[id] = {
466
+ type: 'notFound',
467
+ description: 'the vacation response id is "singleton"',
468
+ };
469
+ continue;
470
+ }
471
+ let refused;
472
+ for (const [key, value] of Object.entries(patch)) {
473
+ if (!(key in this.#vacation)) {
474
+ refused = { type: 'invalidPatch', description: `cannot patch ${key}` };
475
+ break;
476
+ }
477
+ this.#vacation[key] = value;
478
+ }
479
+ if (refused) {
480
+ notUpdated[id] = refused;
481
+ continue;
482
+ }
483
+ updated[id] = null;
484
+ }
485
+ return {
486
+ accountId: ACCOUNT,
487
+ oldState: 'vr1',
488
+ newState: 'vr2',
489
+ created: null,
490
+ notCreated: Object.keys(notCreated).length > 0 ? notCreated : null,
491
+ updated: Object.keys(updated).length > 0 ? updated : null,
492
+ notUpdated: Object.keys(notUpdated).length > 0 ? notUpdated : null,
493
+ destroyed: null,
494
+ notDestroyed: Object.keys(notDestroyed).length > 0 ? notDestroyed : null,
495
+ };
496
+ }
405
497
  case 'Email/query': {
406
498
  const filter = (args.filter ?? {});
407
499
  let matching = this.#emails.filter((email) => this.#matches(email, filter));
@@ -459,8 +551,20 @@ export class FakeMailbox {
459
551
  for (const [key, draft] of Object.entries(create)) {
460
552
  const id = `e${++this.#counter}`;
461
553
  const threadId = `t${++this.#counter}`;
554
+ // `textBody`/`htmlBody`/`attachments` are always server-derived
555
+ // from `bodyStructure` (RFC 8621 §4.1.4), never echoed from what
556
+ // the client sent -- and `thread()` asks for exactly those, never
557
+ // `bodyStructure` itself. A create that used the flat
558
+ // `textBody`/`htmlBody`/`attachments` form instead (everything
559
+ // but a calendar-bearing draft) already has them, so there is
560
+ // nothing to derive.
561
+ const bodyStructure = draft.bodyStructure;
562
+ const derived = bodyStructure
563
+ ? this.#deriveBodyParts(id, bodyStructure, (draft.bodyValues ?? {}))
564
+ : {};
462
565
  this.#emails.push({
463
566
  ...draft,
567
+ ...derived,
464
568
  id,
465
569
  blobId: `blob-${id}`,
466
570
  threadId,
@@ -695,6 +799,176 @@ export class FakeMailbox {
695
799
  notFound: ids.filter((id) => !this.#submissionState.has(id)),
696
800
  };
697
801
  }
802
+ case 'SieveScript/get': {
803
+ const ids = (args.ids ?? null);
804
+ const found = ids
805
+ ? this.#sieveScripts.filter((script) => ids.includes(script.id))
806
+ : this.#sieveScripts;
807
+ return {
808
+ accountId: ACCOUNT,
809
+ state: 'sieve1',
810
+ list: found.map((script) => ({
811
+ id: script.id,
812
+ name: script.name,
813
+ blobId: script.blobId,
814
+ isActive: script.id === this.#activeSieveScriptId,
815
+ })),
816
+ notFound: (ids ?? []).filter((id) => !this.#sieveScripts.some((script) => script.id === id)),
817
+ };
818
+ }
819
+ case 'SieveScript/validate': {
820
+ const blobId = args.blobId;
821
+ const text = blobId === undefined ? undefined : this.#blobContents.get(blobId);
822
+ if (text === undefined) {
823
+ return {
824
+ accountId: ACCOUNT,
825
+ error: { type: 'blobNotFound', description: 'Blob does not exist.' },
826
+ };
827
+ }
828
+ if (!this.#compilesAsSieve(text)) {
829
+ return {
830
+ accountId: ACCOUNT,
831
+ error: { type: 'invalidScript', description: 'unbalanced braces' },
832
+ };
833
+ }
834
+ return { accountId: ACCOUNT, error: null };
835
+ }
836
+ case 'SieveScript/set': {
837
+ const create = (args.create ?? {});
838
+ const created = {};
839
+ const notCreated = {};
840
+ for (const [key, item] of Object.entries(create)) {
841
+ if (!item.blobId) {
842
+ notCreated[key] = {
843
+ type: 'invalidProperties',
844
+ properties: ['blobId'],
845
+ description: 'Missing blobId.',
846
+ };
847
+ continue;
848
+ }
849
+ const text = this.#blobContents.get(item.blobId);
850
+ if (text === undefined) {
851
+ notCreated[key] = { type: 'blobNotFound', description: 'Blob does not exist.' };
852
+ continue;
853
+ }
854
+ if (!this.#compilesAsSieve(text)) {
855
+ notCreated[key] = { type: 'invalidScript', description: 'unbalanced braces' };
856
+ continue;
857
+ }
858
+ const name = item.name?.trim();
859
+ if (!name) {
860
+ notCreated[key] = {
861
+ type: 'invalidProperties',
862
+ properties: ['name'],
863
+ description: 'a sieve script needs a name',
864
+ };
865
+ continue;
866
+ }
867
+ if (this.#sieveScripts.some((script) => script.name === name)) {
868
+ notCreated[key] = {
869
+ type: 'alreadyExists',
870
+ description: `A sieve script with name '${name}' already exists.`,
871
+ };
872
+ continue;
873
+ }
874
+ const id = `sieve${++this.#counter}`;
875
+ this.#sieveScripts.push({ id, name, blobId: item.blobId });
876
+ created[key] = { id, blobId: item.blobId };
877
+ }
878
+ const update = (args.update ?? {});
879
+ const updated = {};
880
+ const notUpdated = {};
881
+ for (const [id, patch] of Object.entries(update)) {
882
+ const script = this.#sieveScripts.find((existing) => existing.id === id);
883
+ if (!script) {
884
+ notUpdated[id] = { type: 'notFound' };
885
+ continue;
886
+ }
887
+ if (patch.blobId !== undefined) {
888
+ const text = this.#blobContents.get(patch.blobId);
889
+ if (text === undefined) {
890
+ notUpdated[id] = { type: 'blobNotFound', description: 'Blob does not exist.' };
891
+ continue;
892
+ }
893
+ if (!this.#compilesAsSieve(text)) {
894
+ notUpdated[id] = { type: 'invalidScript', description: 'unbalanced braces' };
895
+ continue;
896
+ }
897
+ script.blobId = patch.blobId;
898
+ }
899
+ if (patch.name !== undefined) {
900
+ const name = patch.name.trim();
901
+ if (!name) {
902
+ notUpdated[id] = {
903
+ type: 'invalidProperties',
904
+ properties: ['name'],
905
+ description: 'a sieve script needs a name',
906
+ };
907
+ continue;
908
+ }
909
+ if (this.#sieveScripts.some((existing) => existing.id !== id && existing.name === name)) {
910
+ notUpdated[id] = {
911
+ type: 'alreadyExists',
912
+ description: `A sieve script with name '${name}' already exists.`,
913
+ };
914
+ continue;
915
+ }
916
+ script.name = name;
917
+ }
918
+ updated[id] = null;
919
+ }
920
+ // RFC 8621 §2's own refusal for a mailbox with a role, restated here
921
+ // for the one script that is active: Stalwart requires it deactivated
922
+ // first (`crates/jmap/src/sieve/set.rs:341-346`).
923
+ const destroy = (args.destroy ?? []);
924
+ const destroyed = [];
925
+ const notDestroyed = {};
926
+ for (const id of destroy) {
927
+ if (!this.#sieveScripts.some((script) => script.id === id)) {
928
+ notDestroyed[id] = { type: 'notFound' };
929
+ continue;
930
+ }
931
+ if (id === this.#activeSieveScriptId) {
932
+ notDestroyed[id] = {
933
+ type: 'scriptIsActive',
934
+ description: 'Deactivate Sieve script before deletion.',
935
+ };
936
+ continue;
937
+ }
938
+ this.#sieveScripts = this.#sieveScripts.filter((script) => script.id !== id);
939
+ destroyed.push(id);
940
+ }
941
+ // Activation/deactivation, RFC 9661's non-standard set arguments.
942
+ // Only applied when nothing above failed, mirroring Stalwart
943
+ // (`set.rs:371-376`); a bad id in `onSuccessActivateScript` is
944
+ // silently ignored here too (`set.rs:96-101`), which is exactly why
945
+ // `activateSieveScript` never sends one without a same-id `update`
946
+ // whose own `notFound` can be seen above.
947
+ const noFailures = Object.keys(notCreated).length === 0 &&
948
+ Object.keys(notUpdated).length === 0 &&
949
+ Object.keys(notDestroyed).length === 0;
950
+ if (noFailures) {
951
+ const activate = args.onSuccessActivateScript;
952
+ if (activate !== undefined &&
953
+ this.#sieveScripts.some((script) => script.id === activate)) {
954
+ this.#activeSieveScriptId = activate;
955
+ }
956
+ else if (args.onSuccessDeactivateScript === true) {
957
+ this.#activeSieveScriptId = null;
958
+ }
959
+ }
960
+ return {
961
+ accountId: ACCOUNT,
962
+ oldState: 'sieve1',
963
+ newState: 'sieve2',
964
+ created,
965
+ notCreated: Object.keys(notCreated).length > 0 ? notCreated : null,
966
+ updated,
967
+ notUpdated: Object.keys(notUpdated).length > 0 ? notUpdated : null,
968
+ destroyed,
969
+ notDestroyed: Object.keys(notDestroyed).length > 0 ? notDestroyed : null,
970
+ };
971
+ }
698
972
  default:
699
973
  return {
700
974
  type: 'unknownMethod',
@@ -702,6 +976,44 @@ export class FakeMailbox {
702
976
  };
703
977
  }
704
978
  }
979
+ /**
980
+ * What a real server computes from a `bodyStructure` create: `textBody`,
981
+ * `htmlBody` and `attachments`, RFC 8621 §4.1.4's derived properties.
982
+ * Handles only the shape `draftToEmail` sends for a calendar part -- one
983
+ * `multipart/alternative` with flat leaf subParts, never nested further --
984
+ * since that is the only caller that reaches for `bodyStructure` at all.
985
+ *
986
+ * Also records each leaf's bytes under its synthetic blob id, so the
987
+ * download route below can answer with what was actually sent rather than
988
+ * the fixed placeholder every other attachment gets.
989
+ */
990
+ #deriveBodyParts(id, bodyStructure, bodyValues) {
991
+ const parts = (bodyStructure.subParts ?? []).map((leaf) => {
992
+ const partId = leaf.partId ?? '';
993
+ // The bare media type: a real server strips `method=` (and every
994
+ // other parameter) from what `Email/get`'s `type` reports, the same
995
+ // way it already strips `charset` -- see the PR's citation of
996
+ // `crates/email/src/message/body.rs:77-82`.
997
+ const type = (leaf.type ?? 'text/plain').split(';')[0]?.trim().toLowerCase() || 'text/plain';
998
+ const blobId = `blob-${id}-${partId}`;
999
+ this.#blobContents.set(blobId, bodyValues[partId]?.value ?? '');
1000
+ return {
1001
+ partId,
1002
+ blobId,
1003
+ size: bodyValues[partId]?.value.length ?? 0,
1004
+ name: null,
1005
+ type,
1006
+ charset: type.startsWith('text/') ? 'UTF-8' : null,
1007
+ disposition: null,
1008
+ cid: null,
1009
+ };
1010
+ });
1011
+ const textBody = parts.filter((part) => part.type === 'text/plain');
1012
+ const htmlBody = parts.filter((part) => part.type === 'text/html');
1013
+ const inBody = new Set([...textBody, ...htmlBody].map((part) => part.partId));
1014
+ const attachments = parts.filter((part) => !inBody.has(part.partId));
1015
+ return { textBody, htmlBody, attachments, hasAttachment: attachments.length > 0 };
1016
+ }
705
1017
  /** RFC 4865's send-delay SMTP parameter, read the way Stalwart reads it:
706
1018
  * case-insensitively, since the server uppercases every `mailFrom`
707
1019
  * parameter key before matching. `undefined` means no `holdFor` was
@@ -748,6 +1060,26 @@ export class FakeMailbox {
748
1060
  return false;
749
1061
  return true;
750
1062
  }
1063
+ /** A stand-in for the real compiler `SieveScript/set` and `/validate` both
1064
+ * run server-side (`crates/jmap/src/sieve/set.rs:541`) -- not a Sieve
1065
+ * parser, just enough to make a genuine syntax error (unbalanced `{}`, or
1066
+ * nothing at all) refused deterministically, the way `#holdForSeconds`
1067
+ * above stands in for Stalwart's own delay validation without being one. */
1068
+ #compilesAsSieve(text) {
1069
+ if (text.trim().length === 0)
1070
+ return false;
1071
+ let depth = 0;
1072
+ for (const char of text) {
1073
+ if (char === '{')
1074
+ depth += 1;
1075
+ else if (char === '}') {
1076
+ depth -= 1;
1077
+ if (depth < 0)
1078
+ return false;
1079
+ }
1080
+ }
1081
+ return depth === 0;
1082
+ }
751
1083
  /** Return only what was asked for, the way a server does -- so a component
752
1084
  * reading a property the query never requested fails here as it would
753
1085
  * there. */
@@ -774,8 +1106,14 @@ export class FakeMailbox {
774
1106
  headers: { 'Content-Type': 'application/json' },
775
1107
  });
776
1108
  if (!init || (init.method ?? 'GET') === 'GET') {
777
- if (url.includes('/jmap/download/'))
778
- return new Response('fake attachment bytes');
1109
+ if (url.includes('/jmap/download/')) {
1110
+ // `{accountId}/{blobId}/{name}` -- only a blob this fake actually
1111
+ // stored content for (an upload, never an attachment's synthetic
1112
+ // blobId from `add()`) reads back as anything but the fixed stub.
1113
+ const blobId = url.split('/jmap/download/')[1]?.split('/')[1];
1114
+ const stored = blobId ? this.#blobContents.get(decodeURIComponent(blobId)) : undefined;
1115
+ return new Response(stored ?? 'fake attachment bytes');
1116
+ }
779
1117
  if (url.includes('/eventsource')) {
780
1118
  // An open stream that never sends: `push` stays connected and quiet.
781
1119
  return new Response(new ReadableStream(), {
@@ -802,6 +1140,7 @@ export class FakeMailbox {
802
1140
  const type = new Headers(init.headers).get('Content-Type') ?? 'application/octet-stream';
803
1141
  const blob = { blobId: `upload-${this.uploads.length + 1}`, type, size };
804
1142
  this.uploads.push(blob);
1143
+ this.#blobContents.set(blob.blobId, await bodyText(init.body));
805
1144
  return json({ accountId: ACCOUNT, ...blob });
806
1145
  }
807
1146
  const body = JSON.parse(String(init.body));
@@ -844,6 +1183,27 @@ async function measure(body) {
844
1183
  return body.byteLength;
845
1184
  return (await new Response(body).arrayBuffer()).byteLength;
846
1185
  }
1186
+ /** An upload body's bytes, as text -- what `SieveScript/set` and
1187
+ * `/validate` need back to answer honestly, unlike an attachment whose
1188
+ * content nothing here ever reads again. Mirrors `measure`'s type handling
1189
+ * above so a `Blob` is read by its own `.text()` rather than by `instanceof`
1190
+ * (a page can hold more than one realm's `Blob`), and neither call consumes
1191
+ * the other's read: everything `client.upload` actually sends -- a string,
1192
+ * an `ArrayBuffer`/typed array, or a `Blob` -- supports being read twice. */
1193
+ async function bodyText(body) {
1194
+ if (body === null || body === undefined)
1195
+ return '';
1196
+ if (typeof body === 'string')
1197
+ return body;
1198
+ if (body instanceof ArrayBuffer)
1199
+ return new TextDecoder().decode(body);
1200
+ if (ArrayBuffer.isView(body))
1201
+ return new TextDecoder().decode(body);
1202
+ if (typeof body === 'object' && 'text' in body && typeof body.text === 'function') {
1203
+ return body.text();
1204
+ }
1205
+ return new Response(body).text();
1206
+ }
847
1207
  /** RFC 6901 §3 in reverse: one patch-key segment, unescaped. A mailbox id is
848
1208
  * the server's to choose, so a key built from one may carry `~0` or `~1`. */
849
1209
  function unpointer(segment) {