@sayedhfatimi/convex-email 0.1.1 → 0.1.3

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 (72) hide show
  1. package/README.md +306 -47
  2. package/dist/adapters/resend/inbound.d.ts.map +1 -1
  3. package/dist/adapters/resend/inbound.js +21 -5
  4. package/dist/adapters/resend/inbound.js.map +1 -1
  5. package/dist/adapters/resend/send.d.ts.map +1 -1
  6. package/dist/adapters/resend/send.js +9 -1
  7. package/dist/adapters/resend/send.js.map +1 -1
  8. package/dist/adapters/ses/inbound.d.ts.map +1 -1
  9. package/dist/adapters/ses/inbound.js +10 -3
  10. package/dist/adapters/ses/inbound.js.map +1 -1
  11. package/dist/adapters/ses/send.d.ts.map +1 -1
  12. package/dist/adapters/ses/send.js +4 -0
  13. package/dist/adapters/ses/send.js.map +1 -1
  14. package/dist/client/index.d.ts +20 -4
  15. package/dist/client/index.d.ts.map +1 -1
  16. package/dist/client/index.js +35 -20
  17. package/dist/client/index.js.map +1 -1
  18. package/dist/component/_generated/component.d.ts +2 -1
  19. package/dist/component/_generated/component.d.ts.map +1 -1
  20. package/dist/component/cleanup.d.ts +7 -0
  21. package/dist/component/cleanup.d.ts.map +1 -1
  22. package/dist/component/cleanup.js +141 -10
  23. package/dist/component/cleanup.js.map +1 -1
  24. package/dist/component/credentials.d.ts +11 -1
  25. package/dist/component/credentials.d.ts.map +1 -1
  26. package/dist/component/credentials.js +38 -3
  27. package/dist/component/credentials.js.map +1 -1
  28. package/dist/component/deliver.d.ts +13 -3
  29. package/dist/component/deliver.d.ts.map +1 -1
  30. package/dist/component/deliver.js +88 -36
  31. package/dist/component/deliver.js.map +1 -1
  32. package/dist/component/events.d.ts +15 -0
  33. package/dist/component/events.d.ts.map +1 -1
  34. package/dist/component/events.js +91 -31
  35. package/dist/component/events.js.map +1 -1
  36. package/dist/component/inbound.js +3 -3
  37. package/dist/component/inbound.js.map +1 -1
  38. package/dist/component/schema.d.ts +18 -4
  39. package/dist/component/schema.d.ts.map +1 -1
  40. package/dist/component/schema.js +22 -4
  41. package/dist/component/schema.js.map +1 -1
  42. package/dist/component/send.d.ts +5 -3
  43. package/dist/component/send.d.ts.map +1 -1
  44. package/dist/component/send.js +33 -15
  45. package/dist/component/send.js.map +1 -1
  46. package/dist/component/unsubscribe.d.ts.map +1 -1
  47. package/dist/component/unsubscribe.js +2 -1
  48. package/dist/component/unsubscribe.js.map +1 -1
  49. package/dist/component/webhooks.d.ts.map +1 -1
  50. package/dist/component/webhooks.js +3 -1
  51. package/dist/component/webhooks.js.map +1 -1
  52. package/dist/shared/readCapped.d.ts +2 -0
  53. package/dist/shared/readCapped.d.ts.map +1 -1
  54. package/dist/shared/readCapped.js +9 -0
  55. package/dist/shared/readCapped.js.map +1 -1
  56. package/package.json +1 -1
  57. package/src/adapters/resend/inbound.ts +20 -5
  58. package/src/adapters/resend/send.ts +10 -1
  59. package/src/adapters/ses/inbound.ts +9 -3
  60. package/src/adapters/ses/send.ts +4 -0
  61. package/src/client/index.ts +42 -21
  62. package/src/component/_generated/component.ts +2 -2
  63. package/src/component/cleanup.ts +158 -11
  64. package/src/component/credentials.ts +39 -5
  65. package/src/component/deliver.ts +104 -35
  66. package/src/component/events.ts +111 -41
  67. package/src/component/inbound.ts +3 -3
  68. package/src/component/schema.ts +22 -4
  69. package/src/component/send.ts +41 -12
  70. package/src/component/unsubscribe.ts +2 -1
  71. package/src/component/webhooks.ts +4 -2
  72. package/src/shared/readCapped.ts +9 -0
package/README.md CHANGED
@@ -1,13 +1,42 @@
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/sayedhfatimi/convex-email/main/docs/brand/convex-email.on-dark.svg">
4
+ <img alt="convex-email, a Valeon project" src="https://raw.githubusercontent.com/sayedhfatimi/convex-email/main/docs/brand/convex-email.svg" width="440">
5
+ </picture>
6
+ </p>
7
+
8
+ <p align="center"><strong>Email for Convex, both ways.</strong></p>
9
+
1
10
  # @sayedhfatimi/convex-email
2
11
 
3
- A provider-neutral email component for [Convex](https://convex.dev). One client class, `Email`, sends and receives mail through Resend or Amazon SES, stores every message and delivery event, and keeps suppressions, unsubscribes and threads in one place, so you can move from one provider to the other without losing any of it.
12
+ Send **and receive** email in [Convex](https://convex.dev), on Resend or Amazon SES, so you can build inboxes, support desks and reply-by-email into your app. One client class, `Email`, stores every message and delivery event and keeps suppressions, unsubscribes and threads in one place, so you can move from one provider to the other without losing any of it.
13
+
14
+ Live demo: [convex-email.dev](https://convex-email.dev) is a public inbox: email it and watch your message arrive, parsed and verified, grouped into tickets by thread. It also sends to Resend's test addresses. Its source is [convex-email-demo](https://github.com/sayedhfatimi/convex-email-demo).
15
+
16
+ Guides: [build a support desk, reply-by-email and a team inbox per tenant](https://github.com/sayedhfatimi/convex-email/blob/main/docs/guides/README.md).
17
+
18
+ ## Why convex-email
19
+
20
+ Receiving, from Resend receiving, an SES receipt rule, or raw MIME you already hold:
4
21
 
5
- - Sending is queued: `mail.send` returns a message id at once and delivery runs in the background with retries.
6
- - Credentials never enter the component. Your app supplies them from a callback, per use.
7
- - Test mode is on by default: only addresses you allowlist are really sent to.
8
- - Delivery events (sent, delivered, bounced, complained, ...) update the message and, for hard bounces and complaints, suppress the address.
9
- - Inbound mail (Resend receiving, SES receipt rules, or raw MIME you hold) is parsed, cleaned, threaded and handed to your `onInbound` function.
10
- - Optional tenants: one deployment can serve several customers, each with their own provider account.
22
+ - **Parsed and cleaned.** The message is parsed (MIME for SES and raw mail, the Receiving API's JSON for Resend), the HTML cleaned with an allow-list (remote images kept but flagged), and bodies and attachments stored in file storage.
23
+ - **Verdicts.** SPF, DKIM and DMARC from the provider, from verdicts you pass with raw MIME, or from an `Authentication-Results` header you trust.
24
+ - **Threading.** A reply joins the thread of the message it answers. When it answers one of yours, `parent` names that message, its tags, and whether the sender was one of its recipients.
25
+ - **De-duplication.** A provider that delivers the same notification twice gets one stored message.
26
+ - **An `onInbound` hook.** Your mutation gets each message, normalized, and returns `{ handled }`. Unhandled and failed mail stays listable and can be retried.
27
+ - **Text for HTML-only mail.** When the sender sent only HTML, `text` is derived from it and flagged `textFromHtml`.
28
+
29
+ Sending:
30
+
31
+ - **An outbox.** `mail.send` returns a message id at once; delivery runs in the background, with retries, on separate transactional and bulk queues.
32
+ - **Suppression.** Hard bounces and complaints suppress the address for later sends.
33
+ - **One-click unsubscribe.** RFC 8058 `List-Unsubscribe` headers with signed links, per category.
34
+ - **Events.** Sent, delivered, bounced, complained and the rest update the message, with an optional `onEvent` hook.
35
+ - **Tenants.** One deployment can serve several customers, each with their own provider account.
36
+ - **Test mode**, on by default: only addresses you allowlist are really sent to.
37
+ - **Resend to SES cutover** (and back) by flipping `sendVia`, keeping suppressions, unsubscribes and threads.
38
+
39
+ Credentials never enter the component: your app supplies them from a callback, per use.
11
40
 
12
41
  Status: released (0.1.x) and tested live against Resend and Amazon SES. What was confirmed, and what is still open, is under [Verified live, and what is not yet](#verified-live-and-what-is-not-yet).
13
42
 
@@ -183,11 +212,212 @@ export default http;
183
212
 
184
213
  The webhook URLs are on your deployment's HTTP actions domain (`https://<deployment>.convex.site/email/webhook/resend`).
185
214
 
215
+ To filter or route requests yourself (for example when the provider account is shared with other apps), call `mail.handleWebhook(ctx, request, provider)` from your own `httpAction`; pass `{ tenant }` as the fourth argument to scope the event to a tenant. `tenant` also selects which webhook secret verifies the request, so it must come from your app (for example from the route), never from the request body or headers. Read the body for your own check with `request.clone()`, because a body can be read only once.
216
+
217
+ ```ts
218
+ /**
219
+ * Mount it with `http.route({ path: "/email/webhook/resend", method: "POST", handler: filteredResendWebhook })`.
220
+ * The body is not verified yet, so use it only to drop requests, never to trust one.
221
+ */
222
+ export const filteredResendWebhook = httpAction(async (ctx, request) => {
223
+ // Read the body for your own check from a clone: a body can be read once.
224
+ // A body that is not JSON, or is `null`, is dropped rather than a 500.
225
+ const event: unknown = await request
226
+ .clone()
227
+ .json()
228
+ .catch(() => null);
229
+ const data = (event as { data?: Record<string, unknown> } | null)?.data;
230
+ // Your sending domains and your `ownDomains` (receiving domains).
231
+ const myDomains = ["example.com"];
232
+ const list = (x: unknown): unknown[] => (Array.isArray(x) ? x : [x]);
233
+ // `Name <a@b>` or `a@b`; the domain must match exactly (not `evil-example.com`).
234
+ const atMyDomain = (a: unknown) => {
235
+ if (typeof a !== "string") return false;
236
+ const addr = (/<([^<>]*)>\s*$/.exec(a)?.[1] ?? a).trim().toLowerCase();
237
+ return myDomains.some((d) => addr.endsWith(`@${d}`));
238
+ };
239
+ // Sent, delivered, bounced and complained events name you in `from`; inbound
240
+ // mail names you in `to`, `cc` or `bcc` (the adapter accepts all three).
241
+ const fields = [
242
+ data?.from,
243
+ data?.to,
244
+ data?.cc,
245
+ data?.bcc,
246
+ data?.received_for,
247
+ ];
248
+ const mine = fields.flatMap(list).some(atMyDomain);
249
+ if (!mine) return new Response("ignored", { status: 200 });
250
+ return await mail.handleWebhook(ctx, request, "resend");
251
+ });
252
+ ```
253
+
254
+ ## Build a mailbox
255
+
256
+ The [guides](https://github.com/sayedhfatimi/convex-email/blob/main/docs/guides/README.md) go further, starting with the [support desk walkthrough](https://github.com/sayedhfatimi/convex-email/blob/main/docs/guides/support-desk.md).
257
+
258
+ With the set-up above, an inbox, a support desk or reply-by-email is a table of your own plus a few functions. Your `onInbound` mutation files each message under its `threadId`; your queries list a thread; replies go out with `inReplyTo`, which puts them in the same thread.
259
+
260
+ The table, and the `onInbound` mutation that fills it (set it as `onInbound` in the `Email` options):
261
+
262
+ ```ts
263
+ /** Your table: add it to `defineSchema` in `convex/schema.ts` as `mailbox`. */
264
+ export const mailbox = defineTable({
265
+ tenant: v.optional(v.string()),
266
+ threadId: v.string(),
267
+ messageId: v.string(), // the component's message id
268
+ direction: v.union(v.literal("inbound"), v.literal("outbound")),
269
+ from: v.string(),
270
+ subject: v.string(),
271
+ text: v.optional(v.string()), // absent when the body came by reference
272
+ attachments: v.array(v.object({ id: v.string(), filename: v.string() })),
273
+ at: v.number(),
274
+ }).index("by_thread", ["tenant", "threadId", "at"]);
275
+
276
+ /** Set as `onInbound`: file each message under its thread. */
277
+ export const fileInbound = internalMutation({
278
+ args: vInboundForApp,
279
+ handler: async (ctx, m): Promise<{ handled: boolean; note?: string }> => {
280
+ if (m.verdicts.dmarc === "fail") {
281
+ // Not handled: it stays in `listUnhandled` for a person to look at.
282
+ return { handled: false, note: "DMARC failed" };
283
+ }
284
+ await ctx.db.insert("mailbox", {
285
+ tenant: m.tenant,
286
+ threadId: m.threadId,
287
+ messageId: m.messageId,
288
+ direction: "inbound",
289
+ from: m.from.address,
290
+ subject: m.subject,
291
+ // HTML-only mail gets `text` derived from its HTML (`textFromHtml`).
292
+ text: m.text,
293
+ attachments: m.attachments.map(({ id, filename }) => ({ id, filename })),
294
+ at: Date.now(),
295
+ });
296
+ return { handled: true };
297
+ },
298
+ });
299
+ ```
300
+
301
+ Returning `{ handled: true }` marks the message handled. Returning `handled: false`, or throwing, keeps it `unhandled`: `mail.listUnhandled` lists it, with the `note` you returned, and `mail.retryInbound` calls `onInbound` again (see [Inbound mail](#inbound-mail)). Only the `onInbound` result sets this flag; keep your own open or answered state in your table.
302
+
303
+ List a thread, and read what a row does not hold:
304
+
305
+ ```ts
306
+ /** Your app's rule for who may read and answer mail: here, anyone signed in. */
307
+ async function requireAgent(ctx: { auth: Auth }): Promise<UserIdentity> {
308
+ const agent = await ctx.auth.getUserIdentity();
309
+ if (!agent) throw new Error("not signed in");
310
+ return agent;
311
+ }
312
+
313
+ /** Your app's rule for tenants: here, a `tenant` claim on the identity. */
314
+ function requireTenant(agent: UserIdentity, tenant: string | undefined): void {
315
+ if (agent.tenant !== tenant) throw new Error("not your tenant");
316
+ }
317
+
318
+ /** One conversation, oldest first. */
319
+ export const thread = query({
320
+ args: { tenant: v.optional(v.string()), threadId: v.string() },
321
+ handler: async (ctx, { tenant, threadId }) => {
322
+ requireTenant(await requireAgent(ctx), tenant);
323
+ return await ctx.db
324
+ .query("mailbox")
325
+ .withIndex("by_thread", (q) =>
326
+ q.eq("tenant", tenant).eq("threadId", threadId),
327
+ )
328
+ .take(200);
329
+ },
330
+ });
331
+
332
+ /** The full body: text and cleaned HTML, read from storage. */
333
+ export const messageBody = action({
334
+ args: { messageId: v.string() },
335
+ handler: async (
336
+ ctx,
337
+ { messageId },
338
+ ): Promise<{ text?: string; html?: string }> => {
339
+ const agent = await requireAgent(ctx);
340
+ const message = await mail.get(ctx, messageId);
341
+ if (!message) throw new Error("no such message");
342
+ requireTenant(agent, message.tenant);
343
+ return await mail.inboundBody(ctx, messageId);
344
+ },
345
+ });
346
+
347
+ /** A download URL for one attachment, which serves it while it is stored. */
348
+ export const attachmentLink = query({
349
+ args: { messageId: v.string(), attachmentId: v.string() },
350
+ handler: async (ctx, { messageId, attachmentId }): Promise<string | null> => {
351
+ const agent = await requireAgent(ctx);
352
+ const message = await mail.get(ctx, messageId);
353
+ if (!message) throw new Error("no such message");
354
+ requireTenant(agent, message.tenant);
355
+ if (!message.attachments.some((a) => a.id === attachmentId)) {
356
+ throw new Error("not an attachment of this message");
357
+ }
358
+ return await mail.attachmentUrl(ctx, attachmentId);
359
+ },
360
+ });
361
+ ```
362
+
363
+ The row keeps `text` for the thread view. `messageBody` reads the text and cleaned HTML from storage (as `get`'s `htmlUrl` and `textUrl` do), which you need when together they are over 256 KiB: `onInbound` then gets `bodyByReference: true` and no `text` or `html`. Show the HTML with remote images blocked by default (`hasRemoteImages` tells you there are some), and open stored bodies and attachment URLs away from your app's own origin (see [Inbound mail](#inbound-mail)).
364
+
365
+ Reply in the thread:
366
+
367
+ ```ts
368
+ /** Answer a message in its thread. */
369
+ export const replyInThread = mutation({
370
+ args: { messageId: v.string(), text: v.string() },
371
+ handler: async (ctx, { messageId, text }): Promise<string> => {
372
+ const agent = await requireAgent(ctx);
373
+ const original = await mail.get(ctx, messageId);
374
+ if (!original) throw new Error("no such message");
375
+ requireTenant(agent, original.tenant);
376
+ const subject = /^re:/i.test(original.subject)
377
+ ? original.subject
378
+ : `Re: ${original.subject}`;
379
+ const id = await mail.send(ctx, {
380
+ from: "Support <support@example.com>",
381
+ to: original.replyTo.length > 0 ? original.replyTo : original.from,
382
+ subject,
383
+ text,
384
+ // Sets In-Reply-To and References, and joins the original's thread.
385
+ inReplyTo: messageId,
386
+ tenant: original.tenant,
387
+ });
388
+ await ctx.db.insert("mailbox", {
389
+ tenant: original.tenant,
390
+ threadId: original.threadId,
391
+ messageId: id,
392
+ direction: "outbound",
393
+ from: "support@example.com",
394
+ subject,
395
+ text,
396
+ attachments: [],
397
+ at: Date.now(),
398
+ });
399
+ return id;
400
+ },
401
+ });
402
+ ```
403
+
404
+ When the customer answers your reply, the answer arrives with the same `threadId` and a `parent` naming your message, so it lands in the same conversation.
405
+
406
+ What your app owns:
407
+
408
+ - **Auth.** `get`, `inboundBody`, `attachmentUrl` and `status` take bare ids, and the component has no notion of users. `requireAgent` and `requireTenant` stand in for your own rules: every public function in this section checks both before it returns a row, a body or a link, or sends. The samples after it that are public (the send and upload ones) call `requireAgent`; the admin ones, and `receiveFromRouter`, are `internal*` functions for you to call from your own authorised code.
409
+ - **Tenants.** The component threads within a tenant, but a thread id is a Message-ID, so two tenants can hold the same one: the table's index starts with the tenant, and `requireTenant` checks that the caller belongs to it. A single-tenant app has no tenant, and the check passes when the identity has no `tenant` claim either.
410
+ - **Retention.** `cleanup` deletes stored bodies and attachment files past its cut-off, and with `purge: true` the messages too (see [Housekeeping](#housekeeping)); keep in your table what you need for longer.
411
+ - **Trust.** Threading follows the `In-Reply-To` and `References` headers the sender wrote, so anyone who quotes a Message-ID joins its thread. Check `verdicts`, and `parent.senderWasRecipient` for a reply to your own mail, before you act on who a message claims to be from.
412
+
186
413
  ## Sending
187
414
 
415
+ The samples from here on leave out the app's own auth, apart from `requireAgent` where a signed-in user calls them: a public function that sends or reads mail must check its caller first, and the `internal*` ones are for your own authorised functions to call.
416
+
188
417
  `mail.send(ctx, input)` works from a mutation or an action and returns the message id. It validates, writes the message row and the bodies, and queues delivery; it does not wait for the provider.
189
418
 
190
419
  ```ts
420
+ /** A reply to a stored message, with a tag the app can read back. */
191
421
  export const sendTicketReply = mutation({
192
422
  args: {
193
423
  to: v.string(),
@@ -195,8 +425,12 @@ export const sendTicketReply = mutation({
195
425
  replyId: v.string(),
196
426
  inReplyTo: v.string(),
197
427
  },
198
- handler: async (ctx, { to, ticketId, replyId, inReplyTo }): Promise<string> =>
199
- await mail.send(ctx, {
428
+ handler: async (
429
+ ctx,
430
+ { to, ticketId, replyId, inReplyTo },
431
+ ): Promise<string> => {
432
+ await requireAgent(ctx);
433
+ return await mail.send(ctx, {
200
434
  from: "Support <support@example.com>",
201
435
  to,
202
436
  subject: "Re: your request",
@@ -205,7 +439,8 @@ export const sendTicketReply = mutation({
205
439
  tags: { ticket: ticketId },
206
440
  // One key per reply: a key per ticket would swallow every later reply.
207
441
  idempotencyKey: `ticket-reply-${replyId}`,
208
- }),
442
+ });
443
+ },
209
444
  });
210
445
  ```
211
446
 
@@ -213,25 +448,28 @@ Fields: `from`, `to`, `cc`, `bcc`, `replyTo` (a string or an array), `subject`,
213
448
 
214
449
  - `inReplyTo` is a component message id or an RFC `Message-ID`. The component sets `In-Reply-To` and `References` and puts the message in the parent's thread.
215
450
  - `stream` is `"transactional"` (default) or `"bulk"`. Each has its own queue, so a newsletter cannot delay a sign-in email. A bulk send can use a second SES configuration set (`configurationSets.bulk`).
216
- - `idempotencyKey` is per tenant: a second `send` with the same key returns the first message's id instead of sending again.
451
+ - `idempotencyKey` is per tenant: a second `send` with the same key returns the first message's id instead of sending again, until `cleanup` with `purge: true` deletes the first message. The replay returns the first message whatever the second call's content: the content is not compared, so use a new key for a different message.
217
452
  - `tags` come back on `onEvent` and, for replies, on `parent.tags` in `onInbound`. Keys match `^[A-Za-z][A-Za-z0-9_-]{0,63}$`, values match `^[A-Za-z0-9_-]{1,256}$`, at most 50 tags, and the `cx_` prefix is reserved.
218
453
  - `headers` are extra headers. You cannot set structural or threading headers (`From`, `To`, `Cc`, `Bcc`, `Sender`, `Reply-To`, `Subject`, `Date`, `Return-Path`, `MIME-Version`, `Message-ID`, `In-Reply-To`, `References`, `List-Unsubscribe`, `List-Unsubscribe-Post`, anything `Content-*`), and each name may appear once (case-insensitive). At most 50 headers, each value up to 998 characters with no control characters. SESv2 accepts at most 15 custom headers: more than that is a permanent error from SES.
219
- - At most 100 recipients across `to`, `cc` and `bcc`. Addresses are lower-cased and de-duplicated. Recipients are sent as bare addresses (display names are not kept) in 0.1.0; the `from` display name is kept (on SES a non-ASCII one is RFC 2047 encoded).
454
+ - At most 100 recipients across `to`, `cc` and `bcc`. Addresses are lower-cased and de-duplicated. An address may not contain `"` or `;` (a send that names one throws `is not a valid address`). Recipients are sent as bare addresses (display names are not kept) in 0.1.0; the `from` display name is kept (on SES a non-ASCII one is RFC 2047 encoded).
220
455
  - When `unsubscribe` is configured, a message with a `category` must have exactly one recipient across `to`, `cc` and `bcc`: the unsubscribe link in it names that address.
221
456
  - The raw size limit is 10 MiB on both adapters (bodies plus attachments). The providers allow about 30 MiB raw (40 MB after base64), but a send holds the whole message in memory in Convex's default runtime, so the component stays well below that; the live probes measure the real ceiling.
222
457
 
223
458
  Sending from an action works the same way:
224
459
 
225
460
  ```ts
461
+ /** `send` works from an action too. */
226
462
  export const sendFromAction = action({
227
463
  args: { to: v.string() },
228
- handler: async (ctx, { to }): Promise<string> =>
229
- await mail.send(ctx, {
464
+ handler: async (ctx, { to }): Promise<string> => {
465
+ await requireAgent(ctx);
466
+ return await mail.send(ctx, {
230
467
  from: "Example <hello@example.com>",
231
468
  to,
232
469
  subject: "Sent from an action",
233
470
  text: "Hello.",
234
- }),
471
+ });
472
+ },
235
473
  });
236
474
  ```
237
475
 
@@ -240,9 +478,11 @@ export const sendFromAction = action({
240
478
  Store the file first, then pass its id. An attachment can be linked to one message only.
241
479
 
242
480
  ```ts
481
+ /** Store a file, then attach it. An attachment links to one message only. */
243
482
  export const sendWithAttachment = mutation({
244
483
  args: { to: v.string(), bytes: v.bytes() },
245
484
  handler: async (ctx, { to, bytes }): Promise<string> => {
485
+ await requireAgent(ctx);
246
486
  const invoice = await mail.storeAttachment(ctx, {
247
487
  bytes,
248
488
  filename: "invoice.pdf",
@@ -262,9 +502,13 @@ export const sendWithAttachment = mutation({
262
502
  For a large file, have the browser upload to a one-time URL instead of passing bytes through a mutation:
263
503
 
264
504
  ```ts
505
+ /** For a large file: the browser uploads to this URL, then registers it. */
265
506
  export const startUpload = mutation({
266
507
  args: {},
267
- handler: async (ctx): Promise<string> => await mail.attachmentUploadUrl(ctx),
508
+ handler: async (ctx): Promise<string> => {
509
+ await requireAgent(ctx);
510
+ return await mail.attachmentUploadUrl(ctx);
511
+ },
268
512
  });
269
513
 
270
514
  export const finishUpload = mutation({
@@ -273,8 +517,10 @@ export const finishUpload = mutation({
273
517
  filename: v.string(),
274
518
  contentType: v.string(),
275
519
  },
276
- handler: async (ctx, args): Promise<string> =>
277
- await mail.registerUpload(ctx, args),
520
+ handler: async (ctx, args): Promise<string> => {
521
+ await requireAgent(ctx);
522
+ return await mail.registerUpload(ctx, args);
523
+ },
278
524
  });
279
525
  ```
280
526
 
@@ -282,14 +528,18 @@ export const finishUpload = mutation({
282
528
 
283
529
  ### Statuses
284
530
 
285
- A message's `status` is one of `queued`, `test`, `suppressed`, `sending`, `sent`, `delivery_delayed`, `delivered`, `bounced`, `complained`, `failed`, `rejected` (and `received` for inbound mail). It only moves forward, so events that arrive out of order cannot undo a later state. `mail.status(ctx, id)` returns it; `mail.get(ctx, id)` returns the message with its attachments, events and short-lived URLs for the stored bodies (`null` once `cleanup` has removed them).
531
+ A message's `status` is one of `queued`, `test`, `suppressed`, `sending`, `sent`, `delivery_delayed`, `delivered`, `bounced`, `complained`, `failed`, `rejected` (and `received` for inbound mail). It only moves forward, so events that arrive out of order cannot undo a later state. `mail.status(ctx, id)` returns it; `mail.get(ctx, id)` returns the message with its attachments, events and URLs that serve the stored bodies while they are stored (`null` once `cleanup` has removed them).
286
532
 
287
- Delivery to the provider is retried when the failure is transient (8 attempts, backing off from 5 s and doubling: about ten minutes in all), and recorded as `failed` with an error text when it is not or when the attempts run out. The error text never contains a credential and is cut to 1000 characters. The transactional queue runs 4 sends at a time, the bulk queue 2.
533
+ Delivery to the provider is retried when the failure is transient (8 attempts, backing off from 5 s and doubling: about ten minutes in all), and recorded as `failed` with an error text when it is not or when the attempts run out. A provider 5xx counts as a possible acceptance: the message is marked `deliveryAmbiguous` (and is still retried). Resend's daily or monthly quota error fails at once, without retries. The error text never contains a credential and is cut to 1000 characters. The transactional queue runs 4 sends at a time, the bulk queue 2.
288
534
 
289
- `mail.retrySend(ctx, messageId)` queues a `failed` message again (status back to `queued`, error cleared, on its own stream's queue). It re-runs the suppression and unsubscribe checks first, so a recipient who bounced, complained or unsubscribed since is dropped into `suppressedRecipients`; if no `To` recipient is left the message becomes `suppressed` and is not queued. It returns the resulting status (`queued` or `suppressed`). It throws for any other status, and for a failure the provider reported after accepting the message (send that one anew). When an attempt ended without an answer from the provider (a network error or a timeout), the message is marked `deliveryAmbiguous` (readable from `get`): the provider may already have delivered it. `retrySend` then refuses unless you pass `{ force: true }`. Resend drops a resend of the same message within its idempotency window (the key is the component message id); SES has no idempotency key, so a forced retry on SES can deliver twice.
535
+ `mail.retrySend(ctx, messageId)` queues a `failed` message again (status back to `queued`, error cleared, on its own stream's queue). It re-runs the suppression and unsubscribe checks first, so a recipient who bounced, complained or unsubscribed since is dropped into `suppressedRecipients`; if no `To` recipient is left the message becomes `suppressed` and is not queued. Test mode is applied again from the config stored by the last send or webhook, not the app's current options, so a deploy that turns test mode on reaches retries only once a send or webhook has stored it. It returns the resulting status (`queued`, `suppressed`, or `test` when test mode is on and a recipient is not in `testAllowlist`, in which case nothing is sent). A retry that queues clears `deliveryAmbiguous`. It throws for any other status, and for a failure the provider reported after accepting the message (send that one anew). When an attempt ended without an answer from the provider (a network error, a timeout or a provider 5xx), the message is marked `deliveryAmbiguous` (readable from `get`): the provider may already have delivered it. `retrySend` then refuses unless you pass `{ force: true }`. Resend drops a resend of the same message within its idempotency window (the key is the component message id); SES has no idempotency key, so a forced retry on SES can deliver twice.
290
536
 
291
537
  ```ts
292
- export const retryFailedSend = mutation({
538
+ /**
539
+ * Queue a failed message again; `force` only after checking it never arrived.
540
+ * Internal: call it from your own authorised admin function.
541
+ */
542
+ export const retryFailedSend = internalMutation({
293
543
  args: { id: v.string(), force: v.optional(v.boolean()) },
294
544
  handler: async (ctx, { id, force }): Promise<void> => {
295
545
  await mail.retrySend(ctx, id, { force });
@@ -297,7 +547,7 @@ export const retryFailedSend = mutation({
297
547
  });
298
548
  ```
299
549
 
300
- Delivery is at-least-once in one narrow window: if the process dies between the provider accepting a message and the component recording it, the retry sends again. Resend drops the duplicate through the `Idempotency-Key` header (the component message id); SES has no idempotency key, so on SES that window can produce a duplicate.
550
+ Delivery is at-least-once in one narrow window: if the process dies between the provider accepting a message and the component recording it, the retry sends again. Resend drops the duplicate through the `Idempotency-Key` header (the component message id); SES has no idempotency key, so on SES that window can produce a duplicate. If the job cannot record the provider's acceptance, Workpool's completion step records it. A result with no recordable provider id ends the message `failed` and `deliveryAmbiguous` (error text: "the provider may have accepted this message, but its result could not be recorded"). Only a deterministic bug in the completion step itself, failing both inline and on Workpool's retry, could leave a message in `sending`.
301
551
 
302
552
  ## Credentials and the security model
303
553
 
@@ -379,7 +629,7 @@ Other rules the component keeps for you: it never reads `process.env`, never rea
379
629
 
380
630
  ## Test mode
381
631
 
382
- `testMode` defaults to `true`. In test mode, a message is only sent when every remaining recipient (to, cc and bcc) is in `testAllowlist`; otherwise it is stored with status `test` and nothing leaves. Set `testMode: false` (the example uses `EMAIL_LIVE=true`) when you are ready for real recipients. Suppressed and unsubscribed recipients are dropped before the test-mode check.
632
+ `testMode` defaults to `true`. In test mode, a message is only sent when every remaining recipient (to, cc and bcc) is in `testAllowlist`; otherwise it is stored with status `test` and nothing leaves. Set `testMode: false` (the example uses `EMAIL_LIVE=true`) when you are ready for real recipients. Suppressed and unsubscribed recipients are dropped before the test-mode check. `retrySend` applies test mode too, using the stored config.
383
633
 
384
634
  ## Tenants
385
635
 
@@ -401,9 +651,9 @@ Two consequences to plan for:
401
651
 
402
652
  ## Delivery events
403
653
 
404
- Each webhook is verified, parsed into normalized events and appended to the message's event log: `sent`, `delivered`, `delivery_delayed`, `bounced` (with `bounceType`: `hard`, `soft` or `undetermined`), `complained`, `failed`, `rejected`. Duplicates (providers redeliver) are ignored. An event for a message this component did not send, for example from another product on a shared Resend account, is stored as an orphan and otherwise ignored. Orphan events accumulate: `cleanup` does not prune them yet.
654
+ Each webhook is verified, parsed into normalized events and appended to the message's event log: `sent`, `delivered`, `delivery_delayed`, `bounced` (with `bounceType`: `hard`, `soft` or `undetermined`), `complained`, `failed`, `rejected`. Duplicates (providers redeliver) are ignored. An event for a message this component did not send, for example from another product on a shared Resend account, is stored as an orphan and otherwise ignored. An event that arrives before the send is recorded (a fast provider can report one before the component stores its provider id) is held the same way and applied once the send is recorded, from the tenant's own route or an account-level one. Orphan events stay until `cleanup` runs with `purge: true`, which removes those older than its cut-off. Use a cut-off of hours or more, not minutes: an early event waits as an orphan until its send is recorded, and a short cut-off could purge it first.
405
655
 
406
- `onEvent` is called through a queue for each event that matched a message (not for orphans), so a slow handler never blocks the webhook:
656
+ `onEvent` is called through a queue for each event that matched a message (not for orphans; for an early event, once it is applied), so a slow handler never blocks the webhook:
407
657
 
408
658
  ```ts
409
659
  export const onEvent = internalMutation({
@@ -417,13 +667,14 @@ export const onEvent = internalMutation({
417
667
  A hard bounce or a complaint adds a suppression for the addresses the message went to. Soft and undetermined bounces do not. A suppressed address is dropped from later sends (listed in the message's `suppressedRecipients`); if every recipient is dropped, or every `to` recipient is (no message goes out without a `To`), the message is `suppressed`. Addresses are lower-cased and trimmed, never plus-stripped.
418
668
 
419
669
  ```ts
420
- export const suppressed = query({
670
+ /** Internal: call it from your own authorised admin function. */
671
+ export const suppressed = internalQuery({
421
672
  args: { paginationOpts: paginationOptsValidator },
422
673
  handler: async (ctx, { paginationOpts }) =>
423
674
  await mail.suppressions.list(ctx, { paginationOpts }),
424
675
  });
425
676
 
426
- export const unsuppress = mutation({
677
+ export const unsuppress = internalMutation({
427
678
  args: { address: v.string() },
428
679
  handler: async (ctx, { address }): Promise<void> => {
429
680
  await mail.suppressions.remove(ctx, { address });
@@ -438,17 +689,20 @@ export const unsuppress = mutation({
438
689
  Send with a `category` and, if you configured `unsubscribe: { url, mailto? }`, the message carries `List-Unsubscribe` (your URL with a signed token `t`, plus a `mailto:` when set) and `List-Unsubscribe-Post: List-Unsubscribe=One-Click`. The token is signed with the `unsubscribeSecret` from your credentials callback, which is asked with `{ provider: null, tenant, purpose: "unsubscribe" }` both when signing and when checking a link, so links survive a provider cutover. The token names the tenant, address and category. The URL and `mailto` are those configured when the message was sent. A bulk send with a category and no `unsubscribe` option is rejected; on the transactional stream the header is simply left off.
439
690
 
440
691
  ```ts
692
+ /** A newsletter: its own lane, with an unsubscribe link for the category. */
441
693
  export const sendNewsletter = mutation({
442
694
  args: { to: v.string() },
443
- handler: async (ctx, { to }): Promise<string> =>
444
- await mail.send(ctx, {
695
+ handler: async (ctx, { to }): Promise<string> => {
696
+ await requireAgent(ctx);
697
+ return await mail.send(ctx, {
445
698
  from: "News <news@example.com>",
446
699
  to,
447
700
  subject: "This month",
448
701
  html: "<p>News.</p>",
449
702
  stream: "bulk",
450
703
  category: "newsletter",
451
- }),
704
+ });
705
+ },
452
706
  });
453
707
  ```
454
708
 
@@ -460,13 +714,14 @@ How `unsubscribeHandler` behaves:
460
714
  Read and change a person's choices from your own preferences screen:
461
715
 
462
716
  ```ts
463
- export const preferences = query({
717
+ /** Internal: your function checks that `address` is the signed-in user's own. */
718
+ export const preferences = internalQuery({
464
719
  args: { address: v.string() },
465
720
  handler: async (ctx, { address }) =>
466
721
  await mail.unsubscribes.list(ctx, { address }),
467
722
  });
468
723
 
469
- export const resubscribe = mutation({
724
+ export const resubscribe = internalMutation({
470
725
  args: { address: v.string() },
471
726
  handler: async (ctx, { address }): Promise<void> => {
472
727
  await mail.unsubscribes.set(ctx, {
@@ -508,9 +763,9 @@ export const routeInbound = internalMutation({
508
763
 
509
764
  What the handler receives (`InboundForApp`): `messageId`, `tenant`, `provider` (`"resend"`, `"ses"` or `"raw"`), `from`, `to`, `cc`, `subject`, `text`, `textFromHtml`, cleaned `html`, `bodyByReference`, `hasRemoteImages`, `attachments` (`id`, `filename`, `contentType`, `size`), `verdicts` (`spf`, `dkim`, `dmarc`), `threadId`, `parent`, `truncated`, `tenantAdopted`, and the stored `headers`. The `note` you return is kept on the inbound row (`appNote` in `listUnhandled`), handled or not.
510
765
 
511
- - **Bodies.** Text plus HTML over 256 KiB are not passed inline (`bodyByReference: true`); read them in an action with `mail.inboundBody(ctx, messageId)`. Attachment bytes: `mail.attachmentUrl(ctx, attachmentId)` returns a short-lived URL.
766
+ - **Bodies.** Text plus HTML over 256 KiB are not passed inline (`bodyByReference: true`); read them in an action with `mail.inboundBody(ctx, messageId)`. Attachment bytes: `mail.attachmentUrl(ctx, attachmentId)` returns a URL that serves the file while it is stored. Treat these URLs, and `get`'s body URLs, as secrets: anyone with one can fetch the file until `cleanup` deletes it, so hand them only to authorised users.
512
767
  - **Text.** `text` is present whenever the message had any body. When the sender sent no text part (absent, empty or only whitespace) but did send HTML (common for automated senders), the component derives `text` from the HTML (read before cleaning, so `<title>`, `<noscript>`, `<template>`, `<svg>`, `hidden` and `display:none` content such as preheaders is left out) and sets `textFromHtml: true` on the `onInbound` message and on the `get` view. Blocks and `<br>` become line breaks, list items get `- `, a link reads `text [url]` (just the text when it equals the URL), entities are decoded, and images, styles, scripts, zero-width padding and tracking pixels are dropped. A real text part is kept verbatim and `textFromHtml` is absent. A message with no readable content in either part has no `text`. Derived text is cut at 1 MiB (and the message marked `truncated`), and the HTML it is read from at 2 MiB.
513
- - **HTML** is cleaned with an allow-list. Remote images are kept but flagged (`hasRemoteImages`, and each one carries `data-remote-image`) so you can block or allow them; block them by default. Inline raster `data:` images (png, jpeg, gif, webp; base64 only) are kept and not flagged, since Resend's Receiving API may inline `cid:` images as data URIs; every other `data:` source is dropped. Bodies and attachments served by short-lived URLs come from the deployment's storage origin with the sender's content type: never open them on a sensitive origin (one that holds your session).
768
+ - **HTML** is cleaned with an allow-list. Remote images are kept but flagged (`hasRemoteImages`, and each one carries `data-remote-image`) so you can block or allow them; block them by default. Inline raster `data:` images (png, jpeg, gif, webp; base64 only) are kept and not flagged, since Resend's Receiving API may inline `cid:` images as data URIs; every other `data:` source is dropped. Bodies and attachments served by these URLs come from the deployment's storage origin with the sender's content type: never open them on a sensitive origin (one that holds your session).
514
769
  - **Parent.** When the message answers one of ours, `parent` has the outbound message id and its `tags`. `senderWasRecipient` is `true` only when the inbound `From` was one of that message's recipients; check it before trusting `parent.tags` (ticket ids, say), because anyone can quote our Message-ID.
515
770
  - **Adopted tenant.** `tenantAdopted: true` (also readable from `get`) means the message arrived with no tenant (an account-level route) and took `tenant` from the outbound message it answers, because its `From` was one of that message's recipients. `From` is not authenticated by itself: check `verdicts` (DMARC) before acting on an adopted tenant.
516
771
  - **Message-IDs** are stored in `<…>` form whatever the provider hands over, so replies thread to your outbound mail on every adapter.
@@ -527,13 +782,16 @@ export const readBody = internalAction({
527
782
  await mail.inboundBody(ctx, id),
528
783
  });
529
784
 
530
- /** A support screen: unhandled and failed inbound mail, and a retry. */
531
- export const unhandled = query({
785
+ /**
786
+ * A support screen: unhandled and failed inbound mail, and a retry. Internal:
787
+ * call them from your own functions, after checking who is asking.
788
+ */
789
+ export const unhandled = internalQuery({
532
790
  args: {},
533
791
  handler: async (ctx) => await mail.listUnhandled(ctx, { limit: 50 }),
534
792
  });
535
793
 
536
- export const retry = action({
794
+ export const retry = internalAction({
537
795
  args: { id: v.string() },
538
796
  handler: async (ctx, { id }) => await mail.retryInbound(ctx, id),
539
797
  });
@@ -544,19 +802,18 @@ export const retry = action({
544
802
  If you already hold the raw message (for example your own mail router), hand it in; it runs the same pipeline:
545
803
 
546
804
  ```ts
547
- export const receiveFromRouter = action({
805
+ export const receiveFromRouter = internalAction({
548
806
  args: { mime: v.bytes() },
549
807
  handler: async (ctx, { mime }): Promise<string> =>
550
- await mail.receiveRaw(ctx, {
551
- mime,
552
- source: "console-router",
553
- // Omit `verdicts` to fall back to a trusted Authentication-Results header.
554
- verdicts: { spf: "pass", dkim: "pass", dmarc: "pass" },
555
- }),
808
+ // Call this from your own authenticated route or function, the one that
809
+ // actually receives the raw message. `verdicts` is omitted on purpose: the
810
+ // component then reads a trusted Authentication-Results header, or records
811
+ // no verdict. Pass `verdicts` only if your own router computed them.
812
+ await mail.receiveRaw(ctx, { mime, source: "console-router" }),
556
813
  });
557
814
  ```
558
815
 
559
- Verdicts you pass are recorded with `source` as their origin, never as the provider's, and are authoritative: no header is read, even when you pass `{}`. The `keepRawMime` option applies to `receiveRaw` only: the raw bytes are stored for it and deleted after parsing unless `keepRawMime` is `true`. Provider-delivered mail is never kept raw by the component.
816
+ Without `verdicts`, the component reads a trusted Authentication-Results header (see `trustedAuthServIds`) and otherwise records none. Verdicts you pass are recorded with `source` as their origin, never as the provider's, and are authoritative: no header is read, even when you pass `{}`. The `keepRawMime` option applies to `receiveRaw` only: the raw bytes are stored for it and deleted after parsing unless `keepRawMime` is `true`. Provider-delivered mail is never kept raw by the component.
560
817
 
561
818
  ## Resend set-up
562
819
 
@@ -647,7 +904,9 @@ Every message records the provider that sent or received it, and an old message'
647
904
 
648
905
  ## Housekeeping
649
906
 
650
- `cleanup({ olderThanMs })` deletes stored bodies, attachment rows and files, and the kept raw MIME of handled inbound mail, for messages older than the cut-off. It keeps message rows and events, so history and threading survive. It never touches `queued` or `sending` messages, or inbound mail that is unhandled or failed. It is global (not per tenant) and bounded per call: when it returns `more: true`, call it again. A duplicate inbound row never purges the message it points at; only the row that stored that message does. Orphan events are not pruned yet.
907
+ `cleanup({ olderThanMs })` deletes stored bodies, attachment rows and files, and the kept raw MIME of handled inbound mail, for messages older than the cut-off. It keeps message rows and events, so history and threading survive. It never touches `queued` or `sending` messages, or inbound mail that is unhandled or failed. It is global (not per tenant) and bounded per call: when it returns `more: true`, call it again. A duplicate inbound row never purges the message it points at; only the row that stored that message does.
908
+
909
+ `cleanup({ olderThanMs, purge: true })` does the same and then deletes the rows as well: outbound messages in a final status (`test`, `suppressed`, `sent`, `delivery_delayed`, `delivered`, `bounced`, `complained`, `failed`, `rejected`) not updated since the cut-off, with their events and attachments; handled inbound rows older than the cut-off, with the message each one stored and its raw MIME (a duplicate row deletes only itself); and orphan events older than the cut-off. A message is kept when its status (or its Message-ID) changed after the cut-off; an event that changes neither, such as a second recipient's `delivered`, does not extend its life, and the purge deletes that event with the message. A delivery still delayed after the cut-off counts as final. It never touches `queued` or `sending` messages, inbound mail that is received, fetched, unhandled or failed, suppressions or unsubscribes. It is global and bounded the same way: call it again while it returns `more: true`. Deleting the rows has costs. A reply to a purged message no longer joins its thread: `inReplyTo` with the purged message's Message-ID starts a new thread from that id, and with its component id it throws. An inbound reply to a purged message gets no `parent` and does not adopt its tenant. A `send` with a purged message's `idempotencyKey` sends again. A late event for a purged message is stored as an orphan, which a later purge removes. A provider that redelivers a purged inbound notification has it processed again, because the row that de-duplicated it is gone. A suppression keeps the id of a message that may be gone.
651
910
 
652
911
  ```ts
653
912
  /** Runs `cleanup` again while it reports `more`. */
@@ -1 +1 @@
1
- {"version":3,"file":"inbound.d.ts","sourceRoot":"","sources":["../../../src/adapters/resend/inbound.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAEV,mBAAmB,EAEnB,aAAa,EACd,MAAM,uBAAuB,CAAC;AAoK/B,wBAAsB,kBAAkB,CACtC,KAAK,EAAE;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,EACzB,CAAC,EAAE,mBAAmB,GACrB,OAAO,CAAC,aAAa,CAAC,CAqExB"}
1
+ {"version":3,"file":"inbound.d.ts","sourceRoot":"","sources":["../../../src/adapters/resend/inbound.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAEV,mBAAmB,EAEnB,aAAa,EACd,MAAM,uBAAuB,CAAC;AAmL/B,wBAAsB,kBAAkB,CACtC,KAAK,EAAE;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,EACzB,CAAC,EAAE,mBAAmB,GACrB,OAAO,CAAC,aAAa,CAAC,CAqExB"}
@@ -1,6 +1,6 @@
1
1
  import { parseAddressList } from "../../shared/address.js";
2
2
  import { toVerdict } from "../../shared/authResults.js";
3
- import { readCapped } from "../../shared/readCapped.js";
3
+ import { discardBody, readCapped } from "../../shared/readCapped.js";
4
4
  import { RESEND_API, RESEND_MAX_BYTES } from "./send.js";
5
5
  const MAX_ATTACHMENTS = 100;
6
6
  const isObject = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
@@ -16,9 +16,17 @@ async function getJson(apiKey, path) {
16
16
  catch {
17
17
  throw new Error("Resend receiving fetch failed");
18
18
  }
19
- if (!res.ok)
19
+ if (!res.ok) {
20
+ await discardBody(res);
20
21
  throw new Error(`Resend receiving fetch failed (${res.status})`);
21
- const json = await res.json();
22
+ }
23
+ let json;
24
+ try {
25
+ json = await res.json();
26
+ }
27
+ catch {
28
+ throw new Error("Resend receiving fetch failed");
29
+ }
22
30
  if (!isObject(json))
23
31
  throw new Error("Resend receiving fetch failed");
24
32
  return json;
@@ -58,7 +66,7 @@ function stripAngles(id) {
58
66
  function sizeOf(x) {
59
67
  const n = typeof x === "number"
60
68
  ? x
61
- : typeof x === "string" && x.trim()
69
+ : typeof x === "string" && /^\d+$/.test(x.trim())
62
70
  ? Number(x)
63
71
  : NaN;
64
72
  return Number.isFinite(n) && n >= 0 ? n : undefined;
@@ -118,12 +126,20 @@ async function fetchAttachment(apiKey, emailId, meta, limit) {
118
126
  }
119
127
  if (res.type === "opaqueredirect" ||
120
128
  (res.status >= 300 && res.status < 400)) {
129
+ await discardBody(res);
121
130
  throw new Error("Resend attachment download was redirected");
122
131
  }
123
132
  if (!res.ok) {
133
+ await discardBody(res);
124
134
  throw new Error(`Resend attachment download failed (${res.status})`);
125
135
  }
126
- const content = await readCapped(res, limit);
136
+ let content;
137
+ try {
138
+ content = await readCapped(res, limit);
139
+ }
140
+ catch {
141
+ throw new Error("Resend attachment download failed");
142
+ }
127
143
  if (!content)
128
144
  return null;
129
145
  const source = { ...detail, ...meta };