@c9up/rover 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +1 -1
  2. package/dist/BaseMail.d.ts +41 -1
  3. package/dist/BaseMail.d.ts.map +1 -1
  4. package/dist/BaseMail.js +48 -1
  5. package/dist/BaseMail.js.map +1 -1
  6. package/dist/Mail.d.ts +90 -24
  7. package/dist/Mail.d.ts.map +1 -1
  8. package/dist/Mail.js +123 -40
  9. package/dist/Mail.js.map +1 -1
  10. package/dist/MessageBuilder.d.ts +296 -8
  11. package/dist/MessageBuilder.d.ts.map +1 -1
  12. package/dist/MessageBuilder.js +537 -8
  13. package/dist/MessageBuilder.js.map +1 -1
  14. package/dist/config.d.ts +38 -0
  15. package/dist/config.d.ts.map +1 -1
  16. package/dist/config.js +34 -0
  17. package/dist/config.js.map +1 -1
  18. package/dist/format.d.ts +10 -0
  19. package/dist/format.d.ts.map +1 -1
  20. package/dist/format.js +28 -1
  21. package/dist/format.js.map +1 -1
  22. package/dist/index.d.ts +19 -3
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +16 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/testing/FakeMail.d.ts +33 -0
  27. package/dist/testing/FakeMail.d.ts.map +1 -1
  28. package/dist/testing/FakeMail.js +28 -0
  29. package/dist/testing/FakeMail.js.map +1 -1
  30. package/dist/transports/BrevoTransport.d.ts.map +1 -1
  31. package/dist/transports/BrevoTransport.js +7 -5
  32. package/dist/transports/BrevoTransport.js.map +1 -1
  33. package/dist/transports/MailgunTransport.d.ts.map +1 -1
  34. package/dist/transports/MailgunTransport.js +5 -3
  35. package/dist/transports/MailgunTransport.js.map +1 -1
  36. package/dist/transports/ResendTransport.d.ts.map +1 -1
  37. package/dist/transports/ResendTransport.js +7 -5
  38. package/dist/transports/ResendTransport.js.map +1 -1
  39. package/dist/transports/SendGridTransport.d.ts.map +1 -1
  40. package/dist/transports/SendGridTransport.js +10 -6
  41. package/dist/transports/SendGridTransport.js.map +1 -1
  42. package/dist/transports/SesTransport.d.ts.map +1 -1
  43. package/dist/transports/SesTransport.js +16 -7
  44. package/dist/transports/SesTransport.js.map +1 -1
  45. package/dist/transports/SparkPostTransport.d.ts.map +1 -1
  46. package/dist/transports/SparkPostTransport.js +7 -5
  47. package/dist/transports/SparkPostTransport.js.map +1 -1
  48. package/dist/transports/fetchError.d.ts +10 -0
  49. package/dist/transports/fetchError.d.ts.map +1 -1
  50. package/dist/transports/fetchError.js +30 -0
  51. package/dist/transports/fetchError.js.map +1 -1
  52. package/index.darwin-arm64.node +0 -0
  53. package/index.darwin-x64.node +0 -0
  54. package/index.linux-arm64-gnu.node +0 -0
  55. package/index.linux-x64-gnu.node +0 -0
  56. package/index.win32-x64-msvc.node +0 -0
  57. package/package.json +6 -1
  58. package/src/BaseMail.ts +59 -2
  59. package/src/Mail.ts +194 -65
  60. package/src/MessageBuilder.ts +756 -12
  61. package/src/config.ts +46 -0
  62. package/src/format.ts +33 -1
  63. package/src/index.ts +31 -2
  64. package/src/testing/FakeMail.ts +46 -0
  65. package/src/transports/BrevoTransport.ts +7 -5
  66. package/src/transports/MailgunTransport.ts +5 -3
  67. package/src/transports/ResendTransport.ts +7 -5
  68. package/src/transports/SendGridTransport.ts +10 -6
  69. package/src/transports/SesTransport.ts +16 -7
  70. package/src/transports/SparkPostTransport.ts +17 -11
  71. package/src/transports/fetchError.ts +39 -0
@@ -1,6 +1,37 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { basename } from "node:path";
3
+ import { fileURLToPath } from "node:url";
1
4
  import { formatAddress } from "./format.js";
5
+ import { RoverError } from "./RoverError.js";
2
6
  import { renderFile as renderTemplateFile } from "./templating/SimpleTemplate.js";
3
7
 
8
+ /**
9
+ * A header nodemailer must pass through untouched (`{ prepared: true }`).
10
+ *
11
+ * Normal headers get re-encoded — folded, MIME-encoded when non-ASCII. A value
12
+ * that is already exactly what must go on the wire (a signature, a
13
+ * pre-encoded id) has to say so, or the encoding corrupts it.
14
+ */
15
+ export interface PreparedHeader {
16
+ prepared: true;
17
+ value: string;
18
+ }
19
+
20
+ /**
21
+ * A header value as a plain string, for the HTTP-API transports.
22
+ *
23
+ * "Prepared" is a nodemailer notion — it tells its MIME encoder to leave the
24
+ * value alone. A provider REST API takes a JSON string and does no MIME
25
+ * encoding, so the flag has nothing to say there; sending the wrapper object
26
+ * would put `[object Object]` on the wire.
27
+ */
28
+ export function headerValue(
29
+ value: string | string[] | PreparedHeader,
30
+ ): string | string[] {
31
+ if (Array.isArray(value) || typeof value === "string") return value;
32
+ return value.value;
33
+ }
34
+
4
35
  export interface MailMessage {
5
36
  from: string;
6
37
  to: string[];
@@ -10,8 +41,13 @@ export interface MailMessage {
10
41
  subject: string;
11
42
  html?: string;
12
43
  text?: string;
44
+ /**
45
+ * The Apple Watch body (nodemailer `watchHtml`). A stripped-down HTML part
46
+ * a watch renders instead of the full one.
47
+ */
48
+ watchHtml?: string;
13
49
  attachments: MailAttachment[];
14
- headers: Record<string, string | string[]>;
50
+ headers: Record<string, string | string[] | PreparedHeader>;
15
51
  /** Email priority hint (nodemailer `priority`). */
16
52
  priority?: "low" | "normal" | "high";
17
53
  /** Custom `Message-ID` header (threading / idempotency). */
@@ -20,14 +56,83 @@ export interface MailMessage {
20
56
  inReplyTo?: string;
21
57
  /** `References` header — the thread's message ids. */
22
58
  references?: string[];
59
+ /** SMTP envelope, when it differs from the visible From/To headers. */
60
+ envelope?: MailEnvelope;
61
+ /** Body transfer encoding (nodemailer `encoding`). SMTP only. */
62
+ encoding?: string;
63
+ /** RFC 2369 `List-*` headers, keyed WITHOUT the `List-` prefix. */
64
+ list?: Record<string, ListHeader | ListHeader[] | ListHeader[][]>;
65
+ /** A calendar invitation carried as `text/calendar` (nodemailer `icalEvent`). */
66
+ icalEvent?: CalendarEvent;
67
+ }
68
+
69
+ /**
70
+ * One `List-*` header value: a bare URL, or a URL with a human comment.
71
+ *
72
+ * `comment` is REQUIRED in the object form, as it is in nodemailer and
73
+ * AdonisJS — a URL without a comment is the bare string form.
74
+ */
75
+ export type ListHeader = string | { url: string; comment: string };
76
+
77
+ /** How the receiving client should treat the invitation (RFC 5546). */
78
+ export type CalendarEventMethod =
79
+ | "PUBLISH"
80
+ | "REQUEST"
81
+ | "REPLY"
82
+ | "ADD"
83
+ | "CANCEL"
84
+ | "REFRESH"
85
+ | "COUNTER"
86
+ | "DECLINECOUNTER";
87
+
88
+ /** Options shared by the three `icalEvent*` forms (AdonisJS `CalendarEventOptions`). */
89
+ export interface CalendarEventOptions {
90
+ method?: CalendarEventMethod;
91
+ filename?: string;
92
+ encoding?: string;
93
+ }
94
+
95
+ /**
96
+ * A calendar invitation. Exactly one source: inline `content`, a `path` read at
97
+ * {@link MessageBuilder.build} time, or an `href` the provider fetches.
98
+ */
99
+ export interface CalendarEvent extends CalendarEventOptions {
100
+ content?: string;
101
+ path?: string;
102
+ href?: string;
103
+ }
104
+
105
+ /** The addresses the mail SERVERS use, as distinct from the visible headers. */
106
+ export interface MailEnvelope {
107
+ from?: string;
108
+ to?: string | string[];
109
+ cc?: string | string[];
110
+ bcc?: string | string[];
23
111
  }
24
112
 
25
113
  export interface MailAttachment {
26
114
  filename: string;
27
115
  content: Buffer | string;
28
116
  contentType?: string;
29
- /** Content-ID for inline (CID) embedding — set via `embedData()`. */
117
+ /** Content-ID for inline (CID) embedding — set via `embed()` / `embedData()`. */
30
118
  cid?: string;
119
+ /** Source path, kept so `hasAttachment(file)` can answer by path. */
120
+ path?: string;
121
+ /** `Content-Disposition`, when it is not the default for the form used. */
122
+ contentDisposition?: "attachment" | "inline";
123
+ /** `Content-Transfer-Encoding` for this part. */
124
+ encoding?: string;
125
+ /** Extra part headers. */
126
+ headers?: Record<string, string | string[]>;
127
+ }
128
+
129
+ /** What the `attach*` / `embed*` methods accept (AdonisJS `AttachmentOptions`). */
130
+ export interface AttachmentOptions {
131
+ filename?: string;
132
+ contentType?: string;
133
+ contentDisposition?: "attachment" | "inline";
134
+ encoding?: string;
135
+ headers?: Record<string, string | string[]>;
31
136
  }
32
137
 
33
138
  /**
@@ -41,6 +146,121 @@ export interface RecipientObject {
41
146
 
42
147
  export type Recipient = string | RecipientObject;
43
148
 
149
+ /** Whether `list` holds `address`, or anything at all when it is omitted. */
150
+ function contains(
151
+ list: readonly string[],
152
+ address?: string,
153
+ name?: string,
154
+ ): boolean {
155
+ if (address === undefined) return list.length > 0;
156
+ // With a name, both halves must match — the entry was stored through
157
+ // `formatAddress`, so rebuilding it is the exact comparison (AdonisJS
158
+ // checks address AND name the same way).
159
+ if (name !== undefined) {
160
+ const formatted = formatAddress(address, name);
161
+ return list.some((entry) => entry === formatted);
162
+ }
163
+ // Addresses are stored formatted (`"Name" <a@b.c>`), so an assertion on the
164
+ // bare address has to match inside the display form too.
165
+ return list.some(
166
+ (entry) => entry === address || entry.includes(`<${address}>`),
167
+ );
168
+ }
169
+
170
+ /**
171
+ * The parts a transport with no calendar field must send: the declared
172
+ * attachments, plus the invitation rendered as a `text/calendar` part.
173
+ *
174
+ * Only nodemailer has a native `icalEvent`; the provider HTTP APIs carry an
175
+ * invitation the way every mail client reads it anyway — as an attachment with
176
+ * the right media type and `method` parameter.
177
+ */
178
+ export function attachmentsFor(message: MailMessage): MailAttachment[] {
179
+ const ical = message.icalEvent;
180
+ if (ical === undefined) return message.attachments;
181
+ if (ical.content === undefined) {
182
+ // `icalEventFromUrl` leaves only an href, which nodemailer fetches for
183
+ // SMTP. An HTTP provider takes the bytes, and silently dropping the
184
+ // invitation would be worse than saying so.
185
+ throw new RoverError(
186
+ "ICAL_HREF_UNSUPPORTED",
187
+ "icalEventFromUrl() is only supported by the SMTP transport, which fetches the URL itself.",
188
+ {
189
+ hint: "Fetch the ICS yourself and pass it to icalEvent(contents), or use icalEventFromFile().",
190
+ },
191
+ );
192
+ }
193
+ const method = ical.method ?? "PUBLISH";
194
+ return [
195
+ ...message.attachments,
196
+ {
197
+ filename: ical.filename ?? "invite.ics",
198
+ content: ical.content,
199
+ contentType: `text/calendar; charset=utf-8; method=${method}`,
200
+ encoding: ical.encoding,
201
+ },
202
+ ];
203
+ }
204
+
205
+ /** Read a file declared by `attach()` / `embed()` / `icalEventFromFile()`. */
206
+ async function readAttachment(path: string, label: string): Promise<Buffer> {
207
+ try {
208
+ return await readFile(path);
209
+ } catch (err) {
210
+ throw new RoverError(
211
+ "ATTACHMENT_UNREADABLE",
212
+ `Could not read ${label} from "${path}": ${err instanceof Error ? err.message : String(err)}`,
213
+ {
214
+ hint: "Give an absolute path, or attach the bytes with attachData() / embedData().",
215
+ },
216
+ );
217
+ }
218
+ }
219
+
220
+ /** Every URL inside a `List-*` value, whatever nesting form it was written in. */
221
+ function listUrls(value: ListHeader | ListHeader[] | ListHeader[][]): string[] {
222
+ if (typeof value === "string") return [value];
223
+ if (Array.isArray(value)) return value.flatMap((entry) => listUrls(entry));
224
+ return [value.url];
225
+ }
226
+
227
+ /** `unsubscribe` → `Unsubscribe`, `unsubscribe-post` → `Unsubscribe-Post`. */
228
+ function titleCaseKey(key: string): string {
229
+ return key
230
+ .split("-")
231
+ .map((part) => (part ? part[0].toUpperCase() + part.slice(1) : part))
232
+ .join("-");
233
+ }
234
+
235
+ /** Render one `List-*` value the way RFC 2369 writes it: `<url> (comment)`. */
236
+ function renderListHeader(
237
+ value: ListHeader | ListHeader[] | ListHeader[][],
238
+ ): string {
239
+ if (typeof value === "string") return `<${value}>`;
240
+ if (Array.isArray(value)) {
241
+ return value.map((entry) => renderListHeader(entry)).join(", ");
242
+ }
243
+ return value.comment ? `<${value.url}> (${value.comment})` : `<${value.url}>`;
244
+ }
245
+
246
+ function expect(passed: boolean, expectation: string, actual: unknown): void {
247
+ if (passed) return;
248
+ throw new RoverError(
249
+ "ASSERTION_FAILED",
250
+ `Expected the message ${expectation}, got ${JSON.stringify(actual)}`,
251
+ );
252
+ }
253
+
254
+ /**
255
+ * Which templates a message was rendered from — AdonisJS
256
+ * `MessageBodyTemplates`, carried on every mail lifecycle event.
257
+ */
258
+ export interface MessageBodyTemplates {
259
+ html?: { template: string; data: Record<string, unknown> };
260
+ text?: { template: string; data: Record<string, unknown> };
261
+ watch?: { template: string; data: Record<string, unknown> };
262
+ }
263
+
44
264
  export class MessageBuilder {
45
265
  #msg: MailMessage = {
46
266
  from: "",
@@ -52,6 +272,256 @@ export class MessageBuilder {
52
272
  headers: {},
53
273
  };
54
274
  #pendingView: { path: string; data: Record<string, unknown> } | null = null;
275
+ /**
276
+ * The templates {@link build} actually rendered. Recorded because `build()`
277
+ * clears the pending views once they are rendered, and the lifecycle events
278
+ * carry them (AdonisJS `views`, the third field of every mail event) — an
279
+ * app logging a send wants to know which template produced it.
280
+ */
281
+ #renderedViews: MessageBodyTemplates = {};
282
+ #pendingWatchView: { path: string; data: Record<string, unknown> } | null =
283
+ null;
284
+ #pendingTextView: { path: string; data: Record<string, unknown> } | null =
285
+ null;
286
+
287
+ /**
288
+ * Render a template as the PLAIN-TEXT body (AdonisJS `textView`).
289
+ *
290
+ * The counterpart of `htmlView`. A message with only an HTML part scores
291
+ * worse with spam filters and is unreadable in a text-only client, which is
292
+ * why upstream offers both.
293
+ */
294
+ textView(path: string, data: Record<string, unknown> = {}): this {
295
+ this.#pendingTextView = { path, data };
296
+ return this;
297
+ }
298
+
299
+ /**
300
+ * Override the SMTP envelope — who the message is really from and to, as
301
+ * far as the mail servers are concerned (AdonisJS `envelope`).
302
+ *
303
+ * Distinct from the `From`/`To` HEADERS: a bounce goes to the envelope
304
+ * sender, which is how VERP and mailing lists route failures away from the
305
+ * visible author.
306
+ */
307
+ envelope(envelope: MailEnvelope): this {
308
+ this.#msg.envelope = envelope;
309
+ return this;
310
+ }
311
+
312
+ /**
313
+ * The message as built so far — what the `has*` / `assert*` helpers read.
314
+ *
315
+ * Exposed because a test asserts against a mail it never sent, and the
316
+ * alternative is rebuilding the message just to look at it.
317
+ */
318
+ toObject(): Readonly<MailMessage> {
319
+ return this.#msg;
320
+ }
321
+
322
+ toJSON(): Readonly<MailMessage> {
323
+ return this.toObject();
324
+ }
325
+
326
+ // ── Inspection ────────────────────────────────────────────────────────
327
+ // `has*` answers, `assert*` throws. Both exist because a test reads better
328
+ // as an assertion and a conditional reads better as a question.
329
+
330
+ hasTo(address?: string, name?: string): boolean {
331
+ return contains(this.#msg.to, address, name);
332
+ }
333
+ hasCc(address?: string, name?: string): boolean {
334
+ return contains(this.#msg.cc, address, name);
335
+ }
336
+ hasBcc(address?: string, name?: string): boolean {
337
+ return contains(this.#msg.bcc, address, name);
338
+ }
339
+ hasFrom(address?: string, name?: string): boolean {
340
+ return contains(this.#msg.from ? [this.#msg.from] : [], address, name);
341
+ }
342
+ hasReplyTo(address?: string, name?: string): boolean {
343
+ return contains(
344
+ this.#msg.replyTo ? [this.#msg.replyTo] : [],
345
+ address,
346
+ name,
347
+ );
348
+ }
349
+ hasSubject(subject?: string): boolean {
350
+ if (subject === undefined) return this.#msg.subject !== "";
351
+ return this.#msg.subject === subject;
352
+ }
353
+ /**
354
+ * Whether the message carries an attachment — any at all, one with this
355
+ * filename or source path, or one a predicate accepts (AdonisJS
356
+ * `hasAttachment`, whose overloads are the same three).
357
+ */
358
+ hasAttachment(
359
+ match?: string | URL | ((attachment: MailAttachment) => boolean),
360
+ ): boolean {
361
+ if (match === undefined) return this.#msg.attachments.length > 0;
362
+ if (typeof match === "function") return this.#msg.attachments.some(match);
363
+ const needle = match instanceof URL ? fileURLToPath(match) : match;
364
+ return this.#msg.attachments.some(
365
+ (a) => a.filename === needle || a.path === needle,
366
+ );
367
+ }
368
+
369
+ /**
370
+ * Whether `address` appears in ONE named field (AdonisJS `hasRecipient`).
371
+ *
372
+ * The field comes first, as upstream: `hasRecipient('to', 'a@b.c')`. It used
373
+ * to take the address alone and search every field, so a migrated
374
+ * `hasRecipient('to', addr)` asked whether `'to'` was a recipient and quietly
375
+ * answered false — the worst possible outcome inside a test assertion.
376
+ * {@link hasAnyRecipient} is the any-field question under a name that says so.
377
+ */
378
+ hasRecipient(
379
+ property: "to" | "cc" | "bcc" | "replyTo",
380
+ address: string,
381
+ name?: string,
382
+ ): boolean {
383
+ switch (property) {
384
+ case "to":
385
+ return this.hasTo(address, name);
386
+ case "cc":
387
+ return this.hasCc(address, name);
388
+ case "bcc":
389
+ return this.hasBcc(address, name);
390
+ case "replyTo":
391
+ return this.hasReplyTo(address, name);
392
+ }
393
+ }
394
+
395
+ /**
396
+ * Whether `address` is a recipient in any of `to` / `cc` / `bcc`. Without
397
+ * one, whether the message has a recipient at all. Ream's own, since
398
+ * "does this reach them" is the question an assertion usually asks.
399
+ */
400
+ hasAnyRecipient(address?: string, name?: string): boolean {
401
+ return (
402
+ this.hasTo(address, name) ||
403
+ this.hasCc(address, name) ||
404
+ this.hasBcc(address, name)
405
+ );
406
+ }
407
+
408
+ /**
409
+ * Whether the given text appears in the HTML body or the plain-text one
410
+ * (AdonisJS `hasContent`). The field-specific assertions are
411
+ * {@link assertHtmlIncludes} and {@link assertTextIncludes}.
412
+ */
413
+ hasContent(needle: string): boolean {
414
+ return (
415
+ (this.#msg.html?.includes(needle) ?? false) ||
416
+ (this.#msg.text?.includes(needle) ?? false)
417
+ );
418
+ }
419
+
420
+ /** Whether a `List-<key>` header was defined. */
421
+ hasListHeader(key: string, url?: string): boolean {
422
+ const value = this.#msg.list?.[key];
423
+ if (value === undefined) return false;
424
+ if (url === undefined) return true;
425
+ return listUrls(value).includes(url);
426
+ }
427
+ hasHeader(name: string, value?: string): boolean {
428
+ const found = this.#msg.headers[name];
429
+ if (found === undefined) return false;
430
+ if (value === undefined) return true;
431
+ return Array.isArray(found) ? found.includes(value) : found === value;
432
+ }
433
+
434
+ assertTo(address: string): void {
435
+ expect(this.hasTo(address), `to include "${address}"`, this.#msg.to);
436
+ }
437
+ assertFrom(address: string): void {
438
+ expect(this.hasFrom(address), `from to be "${address}"`, this.#msg.from);
439
+ }
440
+ assertCc(address: string): void {
441
+ expect(this.hasCc(address), `cc to include "${address}"`, this.#msg.cc);
442
+ }
443
+ assertBcc(address: string): void {
444
+ expect(this.hasBcc(address), `bcc to include "${address}"`, this.#msg.bcc);
445
+ }
446
+ assertReplyTo(address: string): void {
447
+ expect(
448
+ this.hasReplyTo(address),
449
+ `replyTo to be "${address}"`,
450
+ this.#msg.replyTo,
451
+ );
452
+ }
453
+ assertSubject(subject: string): void {
454
+ expect(
455
+ this.hasSubject(subject),
456
+ `subject to be "${subject}"`,
457
+ this.#msg.subject,
458
+ );
459
+ }
460
+ assertAttachment(
461
+ match: string | URL | ((attachment: MailAttachment) => boolean),
462
+ ): void {
463
+ expect(
464
+ this.hasAttachment(match),
465
+ typeof match === "function"
466
+ ? "an attachment matching the predicate"
467
+ : `an attachment named "${String(match)}"`,
468
+ this.#msg.attachments.map((a) => a.path ?? a.filename),
469
+ );
470
+ }
471
+
472
+ /** `address` is a recipient in some field (AdonisJS `assertRecipient`). */
473
+ assertRecipient(address: string): void {
474
+ expect(this.hasAnyRecipient(address), `to reach "${address}"`, {
475
+ to: this.#msg.to,
476
+ cc: this.#msg.cc,
477
+ bcc: this.#msg.bcc,
478
+ });
479
+ }
480
+
481
+ /** The text appears in the HTML or the plain-text body (AdonisJS `assertContent`). */
482
+ assertContent(needle: string): void {
483
+ expect(this.hasContent(needle), `to contain "${needle}"`, {
484
+ html: this.#msg.html,
485
+ text: this.#msg.text,
486
+ });
487
+ }
488
+ assertHeader(name: string, value?: string): void {
489
+ expect(
490
+ this.hasHeader(name, value),
491
+ value === undefined ? `a "${name}" header` : `${name}: ${value}`,
492
+ this.#msg.headers[name],
493
+ );
494
+ }
495
+ assertHtmlIncludes(substring: string): void {
496
+ expect(
497
+ (this.#msg.html ?? "").includes(substring),
498
+ `html to include "${substring}"`,
499
+ this.#msg.html,
500
+ );
501
+ }
502
+ assertTextIncludes(substring: string): void {
503
+ expect(
504
+ (this.#msg.text ?? "").includes(substring),
505
+ `text to include "${substring}"`,
506
+ this.#msg.text,
507
+ );
508
+ }
509
+
510
+ /**
511
+ * The Apple Watch body contains `substring` (AdonisJS
512
+ * `assertWatchIncludes`).
513
+ *
514
+ * Takes a RegExp as well as a string, as upstream does — a rendered body
515
+ * rarely matches a fixed substring exactly.
516
+ */
517
+ assertWatchIncludes(substring: string | RegExp): void {
518
+ const body = this.#msg.watchHtml ?? "";
519
+ const hit =
520
+ typeof substring === "string"
521
+ ? body.includes(substring)
522
+ : substring.test(body);
523
+ expect(hit, `watch body to include "${String(substring)}"`, body);
524
+ }
55
525
 
56
526
  from(address: string, name?: string): this {
57
527
  this.#msg.from = formatAddress(address, name);
@@ -92,6 +562,35 @@ export class MessageBuilder {
92
562
  this.#msg.html = content;
93
563
  return this;
94
564
  }
565
+
566
+ /**
567
+ * The Apple Watch body (AdonisJS `watch`).
568
+ *
569
+ * NAMED DEVIATION — this writes nodemailer's `watchHtml`. AdonisJS writes a
570
+ * bare `watch` field, which nodemailer's mail composer never reads
571
+ * (lib/mail-composer/index.js only looks at `watchHtml`), so upstream's
572
+ * watch body never reaches the wire. {@link watchHtml} is the same method
573
+ * under the field's own name.
574
+ */
575
+ watch(content: string): this {
576
+ return this.watchHtml(content);
577
+ }
578
+
579
+ watchHtml(content: string): this {
580
+ this.#msg.watchHtml = content;
581
+ return this;
582
+ }
583
+
584
+ /**
585
+ * Render a template as the Apple Watch body (AdonisJS `watchView`).
586
+ *
587
+ * The counterpart of {@link htmlView} and {@link textView}: the render
588
+ * happens lazily at `build()` time so the fluent chain stays synchronous.
589
+ */
590
+ watchView(viewPath: string, data?: Record<string, unknown>): this {
591
+ this.#pendingWatchView = { path: viewPath, data: data ?? {} };
592
+ return this;
593
+ }
95
594
  text(content: string): this {
96
595
  this.#msg.text = content;
97
596
  return this;
@@ -121,23 +620,85 @@ export class MessageBuilder {
121
620
  return this;
122
621
  }
123
622
 
124
- attach(
125
- filename: string,
623
+ /**
624
+ * Attach a FILE by path or `file://` URL (AdonisJS `attach`). The bytes are
625
+ * read at {@link build} time, so the fluent chain stays synchronous.
626
+ *
627
+ * The filename defaults to the file's own basename. For bytes you already
628
+ * hold, use {@link attachData}.
629
+ */
630
+ attach(file: string | URL, options?: AttachmentOptions): this {
631
+ const path = file instanceof URL ? fileURLToPath(file) : file;
632
+ this.#msg.attachments.push({
633
+ filename: options?.filename ?? basename(path),
634
+ // Filled in by `build()`; an unread attachment must never ship as an
635
+ // empty part, so `build()` failing to read is an error, not a warning.
636
+ content: "",
637
+ path,
638
+ contentType: options?.contentType,
639
+ contentDisposition: options?.contentDisposition,
640
+ encoding: options?.encoding,
641
+ headers: options?.headers,
642
+ });
643
+ return this;
644
+ }
645
+
646
+ /**
647
+ * Attach bytes you already hold (AdonisJS `attachData`). `filename` is
648
+ * required — there is no path to take it from.
649
+ */
650
+ attachData(
126
651
  content: Buffer | string,
127
- contentType?: string,
652
+ options: AttachmentOptions & { filename: string },
128
653
  ): this {
129
- this.#msg.attachments.push({ filename, content, contentType });
654
+ this.#msg.attachments.push({
655
+ filename: options.filename,
656
+ content,
657
+ contentType: options.contentType,
658
+ contentDisposition: options.contentDisposition,
659
+ encoding: options.encoding,
660
+ headers: options.headers,
661
+ });
130
662
  return this;
131
663
  }
132
664
 
133
665
  /**
134
- * Embed inline content referenced by a Content-ID. Use `cid:<cid>` inside the
135
- * HTML body to reference it. Content-based (rover is agnostic / no-fs): the
136
- * path-based `embed(file, cid)` form from `@adonisjs/mail` is a deliberate
137
- * divergence — pass the bytes directly instead.
666
+ * Embed a FILE inline, referenced by `cid:<cid>` in the HTML body (AdonisJS
667
+ * `embed`). Read at {@link build} time, like {@link attach}.
138
668
  */
139
- embedData(content: Buffer | string, cid: string, contentType?: string): this {
140
- this.#msg.attachments.push({ filename: cid, content, contentType, cid });
669
+ embed(file: string | URL, cid: string, options?: AttachmentOptions): this {
670
+ const path = file instanceof URL ? fileURLToPath(file) : file;
671
+ this.#msg.attachments.push({
672
+ filename: options?.filename ?? basename(path),
673
+ content: "",
674
+ path,
675
+ cid,
676
+ contentType: options?.contentType,
677
+ contentDisposition: options?.contentDisposition ?? "inline",
678
+ encoding: options?.encoding,
679
+ headers: options?.headers,
680
+ });
681
+ return this;
682
+ }
683
+
684
+ /**
685
+ * Embed bytes you already hold, referenced by `cid:<cid>` in the HTML body
686
+ * (AdonisJS `embedData`).
687
+ */
688
+ embedData(
689
+ content: Buffer | string,
690
+ cid: string,
691
+ options?: AttachmentOptions,
692
+ ): this {
693
+ this.#msg.attachments.push({
694
+ filename: options?.filename ?? cid,
695
+ content,
696
+ cid,
697
+ contentType: options?.contentType,
698
+ contentDisposition: options?.contentDisposition ?? "inline",
699
+ encoding: options?.encoding,
700
+ headers: options?.headers,
701
+ });
141
702
  return this;
142
703
  }
143
704
 
@@ -146,6 +707,116 @@ export class MessageBuilder {
146
707
  return this;
147
708
  }
148
709
 
710
+ /**
711
+ * A header nodemailer passes through untouched (AdonisJS `preparedHeader`).
712
+ *
713
+ * Use it when the value IS what must appear on the wire and re-encoding
714
+ * would corrupt it — a signature, an already-encoded message id.
715
+ */
716
+ preparedHeader(key: string, value: string): this {
717
+ this.#msg.headers[key] = { prepared: true, value };
718
+ return this;
719
+ }
720
+
721
+ /**
722
+ * Body transfer encoding (AdonisJS `encoding`) — `7bit`, `base64`,
723
+ * `quoted-printable`… SMTP only: the provider HTTP APIs encode the payload
724
+ * themselves and expose no equivalent.
725
+ */
726
+ encoding(encoding: string): this {
727
+ this.#msg.encoding = encoding;
728
+ return this;
729
+ }
730
+
731
+ // ── RFC 2369 List-* headers ───────────────────────────────────────────
732
+
733
+ /**
734
+ * Define a `List-<key>` header (AdonisJS `addListHeader`). `key` carries no
735
+ * `List-` prefix — `addListHeader('archive', url)` emits `List-Archive`.
736
+ * Calling it again for the same key replaces the value.
737
+ */
738
+ addListHeader(
739
+ key: string,
740
+ value: ListHeader | ListHeader[] | ListHeader[][],
741
+ ): this {
742
+ this.#msg.list ??= {};
743
+ this.#msg.list[key] = value;
744
+ return this;
745
+ }
746
+
747
+ /**
748
+ * `List-Unsubscribe` (AdonisJS `listUnsubscribe`).
749
+ *
750
+ * `{ oneClick: true }` also emits the RFC 8058 `List-Unsubscribe-Post`
751
+ * header. Gmail and Yahoo require BOTH for bulk senders, and only a `https:`
752
+ * URL is a valid one-click target — a `mailto:` cannot answer a POST, so
753
+ * pairing them is refused rather than silently shipped.
754
+ */
755
+ listUnsubscribe(
756
+ value: ListHeader | ListHeader[] | ListHeader[][],
757
+ options?: { oneClick?: boolean },
758
+ ): this {
759
+ if (options?.oneClick === true) {
760
+ for (const url of listUrls(value)) {
761
+ if (!url.toLowerCase().startsWith("http")) {
762
+ throw new RoverError(
763
+ "INVALID_LIST_HEADER",
764
+ `listUnsubscribe({ oneClick: true }) needs an https URL that can answer a POST, got "${url}".`,
765
+ {
766
+ hint: "Keep the mailto: form without oneClick, or add an https endpoint alongside it.",
767
+ },
768
+ );
769
+ }
770
+ }
771
+ // A RAW header, not a `List-*` entry: nodemailer wraps every list value
772
+ // in angle brackets, and `<List-Unsubscribe=One-Click>` is not what
773
+ // RFC 8058 specifies — receivers would ignore it.
774
+ this.#msg.headers["List-Unsubscribe-Post"] = "List-Unsubscribe=One-Click";
775
+ }
776
+ return this.addListHeader("unsubscribe", value);
777
+ }
778
+
779
+ /** `List-Subscribe` (AdonisJS `listSubscribe`). */
780
+ listSubscribe(value: ListHeader | ListHeader[] | ListHeader[][]): this {
781
+ return this.addListHeader("subscribe", value);
782
+ }
783
+
784
+ /** `List-Help` (AdonisJS `listHelp`). */
785
+ listHelp(value: ListHeader | ListHeader[] | ListHeader[][]): this {
786
+ return this.addListHeader("help", value);
787
+ }
788
+
789
+ // ── Calendar invitations ──────────────────────────────────────────────
790
+
791
+ /**
792
+ * Attach a calendar invitation from an ICS string (AdonisJS `icalEvent`).
793
+ *
794
+ * Named deviation: upstream also accepts a `(calendar: ICalCalendar) => void`
795
+ * builder, which is `ical-generator`'s API. rover carries no such
796
+ * dependency, so it takes the ICS text — produced by whichever generator you
797
+ * prefer. {@link icalEventFromFile} and {@link icalEventFromUrl} are the
798
+ * other two upstream forms, unchanged.
799
+ */
800
+ icalEvent(contents: string, options?: CalendarEventOptions): this {
801
+ this.#msg.icalEvent = { ...options, content: contents };
802
+ return this;
803
+ }
804
+
805
+ /** Calendar invitation read from a file at {@link build} time (AdonisJS `icalEventFromFile`). */
806
+ icalEventFromFile(file: string | URL, options?: CalendarEventOptions): this {
807
+ this.#msg.icalEvent = {
808
+ ...options,
809
+ path: file instanceof URL ? fileURLToPath(file) : file,
810
+ };
811
+ return this;
812
+ }
813
+
814
+ /** Calendar invitation the transport fetches from a URL (AdonisJS `icalEventFromUrl`). */
815
+ icalEventFromUrl(url: string, options?: CalendarEventOptions): this {
816
+ this.#msg.icalEvent = { ...options, href: url };
817
+ return this;
818
+ }
819
+
149
820
  /**
150
821
  * Queue an HTML template render. The render happens lazily at `build()` time
151
822
  * so the fluent chain stays synchronous; `build()` is async and awaits the
@@ -156,6 +827,26 @@ export class MessageBuilder {
156
827
  return this;
157
828
  }
158
829
 
830
+ /** The templates {@link build} rendered, for the lifecycle events. */
831
+ get views(): MessageBodyTemplates {
832
+ return { ...this.#renderedViews };
833
+ }
834
+
835
+ /** AdonisJS' name for {@link views}. */
836
+ get contentViews(): MessageBodyTemplates {
837
+ return this.views;
838
+ }
839
+
840
+ /**
841
+ * The message as a plain object (AdonisJS `nodeMailerMessage`).
842
+ *
843
+ * A live reference, as upstream's is — this is the object the transports
844
+ * read, not a snapshot. {@link build} is what finalises it.
845
+ */
846
+ get nodeMailerMessage(): MailMessage {
847
+ return this.#msg;
848
+ }
849
+
159
850
  /**
160
851
  * Finalise the message. `viewsRoot`, when provided by the owning `Mail`,
161
852
  * scopes template resolution to that instance's configured root instead of
@@ -164,6 +855,10 @@ export class MessageBuilder {
164
855
  */
165
856
  async build(viewsRoot?: string): Promise<MailMessage> {
166
857
  if (this.#pendingView !== null) {
858
+ this.#renderedViews.html = {
859
+ template: this.#pendingView.path,
860
+ data: this.#pendingView.data,
861
+ };
167
862
  this.#msg.html = await renderTemplateFile(
168
863
  this.#pendingView.path,
169
864
  this.#pendingView.data,
@@ -172,6 +867,55 @@ export class MessageBuilder {
172
867
  );
173
868
  this.#pendingView = null;
174
869
  }
870
+ if (this.#pendingWatchView !== null) {
871
+ this.#renderedViews.watch = {
872
+ template: this.#pendingWatchView.path,
873
+ data: this.#pendingWatchView.data,
874
+ };
875
+ this.#msg.watchHtml = await renderTemplateFile(
876
+ this.#pendingWatchView.path,
877
+ this.#pendingWatchView.data,
878
+ undefined,
879
+ viewsRoot,
880
+ );
881
+ this.#pendingWatchView = null;
882
+ }
883
+ if (this.#pendingTextView !== null) {
884
+ this.#renderedViews.text = {
885
+ template: this.#pendingTextView.path,
886
+ data: this.#pendingTextView.data,
887
+ };
888
+ this.#msg.text = await renderTemplateFile(
889
+ this.#pendingTextView.path,
890
+ this.#pendingTextView.data,
891
+ undefined,
892
+ viewsRoot,
893
+ );
894
+ this.#pendingTextView = null;
895
+ }
896
+ // Path-based attachments and invitations are read here, not when they were
897
+ // declared, so the fluent chain stays synchronous. A read failure raises:
898
+ // an attachment the recipient expects must never ship as an empty part.
899
+ for (const attachment of this.#msg.attachments) {
900
+ if (attachment.path === undefined) continue;
901
+ attachment.content = await readAttachment(
902
+ attachment.path,
903
+ attachment.filename,
904
+ );
905
+ }
906
+ const ical = this.#msg.icalEvent;
907
+ if (ical?.path !== undefined && ical.content === undefined) {
908
+ ical.content = (
909
+ await readAttachment(ical.path, "the calendar event")
910
+ ).toString("utf8");
911
+ }
912
+ // `List-*` headers are rendered here, once, rather than in each transport:
913
+ // every transport already forwards `headers`, and only nodemailer has a
914
+ // structured `list` field. `#msg.list` stays as the structured record the
915
+ // `hasListHeader` inspection reads.
916
+ for (const [key, value] of Object.entries(this.#msg.list ?? {})) {
917
+ this.#msg.headers[`List-${titleCaseKey(key)}`] = renderListHeader(value);
918
+ }
175
919
  return this.#msg;
176
920
  }
177
921
  }