@nxgt/mail-resend 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,8 +33,9 @@ bun add @nxgt/mail-resend @nxgt/mail
33
33
 
34
34
  Peers, all required:
35
35
 
36
- - `@nxgt/mail` — the port and the errors. One copy in your tree, so
37
- `error instanceof MailFailure` holds.
36
+ - `@nxgt/mail` — the port, the errors and the checks: `^0.3`, the version
37
+ with attachments and `idempotencyKey`. One copy in your tree, so `error instanceof MailFailure`
38
+ holds.
38
39
  - `typescript` (6). Bundler resolution (`"moduleResolution": "bundler"`) is
39
40
  what is supported and tested; `nodenext` is out of contract.
40
41
 
@@ -84,12 +85,67 @@ await mailer.send({
84
85
  comma or an angle bracket in it never names another recipient.
85
86
  - `messageId` is Resend's `id`, or `null` when the answer carries none.
86
87
 
88
+ ### Attachments
89
+
90
+ `attachments` on the message are sent in Resend's `attachments`, each file's
91
+ bytes encoded as base64 — with no Node built-in, so it still runs on an edge
92
+ runtime:
93
+
94
+ ```ts
95
+ const pdf = new Uint8Array(await (await fetch('https://files.acme.test/invoices/42.pdf')).arrayBuffer());
96
+
97
+ await mailer.send({
98
+ to: 'ada@example.com',
99
+ subject: 'Your invoice',
100
+ html: '<p>Your invoice is attached.</p>',
101
+ text: 'Your invoice is attached.',
102
+ attachments: [{ filename: 'invoice-42.pdf', content: pdf, contentType: 'application/pdf' }],
103
+ });
104
+ ```
105
+
106
+ Resend's `path` (a URL it would fetch) is never used: an attachment is bytes
107
+ your code already holds. Resend takes at most **40 MB per e-mail, after
108
+ base64** — a third larger than the files — and refuses more (`MailRefused`).
109
+ **A large or sensitive file is a signed link in the template**, not an
110
+ attachment. See [Setting up — what a message becomes](docs/guide/setup.md#what-a-message-becomes).
111
+
112
+ ### Idempotency — a retry that delivers once
113
+
114
+ A message's `idempotencyKey` is sent as Resend's `Idempotency-Key` header.
115
+ Resend keeps a key for **24 hours**: a retry within them answers the first
116
+ send's id, and delivers nothing more.
117
+
118
+ ```ts
119
+ import { MailFailure } from '@nxgt/mail';
120
+
121
+ const receipt = {
122
+ to: 'ada@example.com',
123
+ subject: 'Your receipt',
124
+ html: '<p>Thank you for your order.</p>',
125
+ text: 'Thank you for your order.',
126
+ idempotencyKey: 'order-42/receipt', // from what the e-mail is about, never the time or a random value
127
+ };
128
+
129
+ const sent = await mailer.send(receipt).catch(async (error: unknown) => {
130
+ if (!(error instanceof MailFailure)) throw error;
131
+ return mailer.send(receipt); // a timeout may have delivered it: the key keeps it to one e-mail
132
+ });
133
+ ```
134
+
135
+ The same key with a **different** message is refused by Resend
136
+ (`409 invalid_idempotent_request`, a `MailRefused`): a key names one e-mail.
137
+ The same key while its first send is **still in progress**
138
+ (`409 concurrent_idempotent_requests`) is a `MailFailure`: retry later. Past
139
+ 24 hours, the key is forgotten and a retry delivers again. The key never
140
+ reaches the e-mail. See
141
+ [Setting up — the idempotency key](docs/guide/setup.md#the-idempotency-key).
142
+
87
143
  ### Errors — a refusal or a failure
88
144
 
89
145
  | When | Throws | `cause` |
90
146
  | --- | --- | --- |
91
- | `400`, `422` — Resend refuses the message | `MailRefused` — `send: Resend refused the message` | an `Error` with `status`, `errorName` and Resend's `detail` |
92
- | `401`, `403`, `429`, `5xx`, any other status | `MailFailure` — `send: Resend could not take the message` | the same |
147
+ | `400`, `422` — Resend refuses the message, an attachment over the size limit included; `413` — a request too large for what sits in front of the API; `409 invalid_idempotent_request` — the `idempotencyKey` already used for a different message | `MailRefused` — `send: Resend refused the message` | an `Error` with `status`, `errorName` and Resend's `detail` |
148
+ | `401`, `403`, `429`, `5xx`, `409 concurrent_idempotent_requests` — the same key's first send still in progress — any other status | `MailFailure` — `send: Resend could not take the message` | the same |
93
149
  | A network error | `MailFailure` — `send: Resend could not be reached` | the `fetch` error |
94
150
  | No answer within `timeoutMs` | `MailFailure` — `send: Resend did not answer within <timeoutMs> ms` | the `TimeoutError` |
95
151
  | No sender, on the message or as a default | `MailRefused` — `send: from is missing — give the message a from, or createResendMailer a default one` | — |
@@ -130,6 +186,11 @@ the first send.
130
186
  **A key read from a file keeps its line break.** A key holding whitespace is
131
187
  refused at wiring; trim it.
132
188
 
189
+ **Attachments count against Resend's 40 MB after base64.** A 30 MB file
190
+ is at it once encoded, before the rest of the body; Resend answers `422`
191
+ `invalid_attachment`. The whole request is also held in memory while it is
192
+ sent; past a few megabytes, send a signed link.
193
+
133
194
  **A `403` is a failure, not a refusal.** An invalid key or an unverified
134
195
  sending domain refuses every message alike: it is the wiring that is wrong.
135
196
 
@@ -138,7 +199,8 @@ The transport does not wait and retry for you.
138
199
 
139
200
  **A timeout does not mean nothing was sent.** After `timeoutMs`, or a
140
201
  connection dropped mid-request, Resend may have accepted the e-mail: a retry
141
- can send it twice. Weigh that before retrying.
202
+ without a key can send it twice. Set `idempotencyKey: 'order-42/receipt'`,
203
+ and retry within Resend's 24 hours.
142
204
 
143
205
  ## Type safety, counted
144
206
 
package/dist/index.d.ts CHANGED
@@ -12,7 +12,9 @@
12
12
  * ```
13
13
  *
14
14
  * **A failure throws** the `MailFailure` or `MailRefused` of the `@nxgt/mail`
15
- * peer, what Resend answered as the `cause`. Nothing is retried.
15
+ * peer, what Resend answered as the `cause`. Nothing is retried; a message's
16
+ * `idempotencyKey` is sent as Resend's `Idempotency-Key`, so a retry the
17
+ * caller makes delivers once.
16
18
  */
17
19
  import { type Address, type Mailer } from '@nxgt/mail';
18
20
  export interface ResendMailerOptions {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EACN,KAAK,OAAO,EAEZ,KAAK,MAAM,EAKX,MAAM,YAAY,CAAC;AAEpB,MAAM,WAAW,mBAAmB;IACnC,2BAA2B;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,sFAAsF;IACtF,QAAQ,CAAC,IAA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CHANGED
@@ -32,6 +32,34 @@ async function readAnswer(response, signal) {
32
32
  const body = await beforeAbort(response.json(), signal).then((value) => value, () => null);
33
33
  return typeof body === "object" && body !== null ? body : {};
34
34
  }
35
+ function base64Of(bytes) {
36
+ let binary = "";
37
+ for (let start = 0;start < bytes.length; start += 32768) {
38
+ binary += String.fromCharCode(...bytes.subarray(start, start + 32768));
39
+ }
40
+ return btoa(binary);
41
+ }
42
+ function bodyOf(message, sender) {
43
+ const to = Array.isArray(message.to) ? message.to : [message.to];
44
+ return {
45
+ from: formatAddress(sender),
46
+ to: to.map(formatAddress),
47
+ subject: message.subject,
48
+ html: message.html,
49
+ text: message.text,
50
+ ...message.replyTo === undefined ? {} : {
51
+ reply_to: formatAddress(message.replyTo)
52
+ },
53
+ ...message.headers === undefined || Object.keys(message.headers).length === 0 ? {} : { headers: message.headers },
54
+ ...message.attachments === undefined || message.attachments.length === 0 ? {} : {
55
+ attachments: message.attachments.map((attachment) => ({
56
+ filename: attachment.filename,
57
+ content: base64Of(attachment.content),
58
+ content_type: attachment.contentType
59
+ }))
60
+ }
61
+ };
62
+ }
35
63
  var MAX_TIMEOUT_MS = 2147483647;
36
64
  var text = (value) => typeof value === "string" && value !== "" ? value : null;
37
65
  function checkOptions(options) {
@@ -76,18 +104,7 @@ function createResendMailer(options) {
76
104
  if (sender === undefined) {
77
105
  throw new MailRefused("send: from is missing — give the message a from, or createResendMailer a default one");
78
106
  }
79
- const to = Array.isArray(message.to) ? message.to : [message.to];
80
- const body = {
81
- from: formatAddress(sender),
82
- to: to.map(formatAddress),
83
- subject: message.subject,
84
- html: message.html,
85
- text: message.text,
86
- ...message.replyTo === undefined ? {} : {
87
- reply_to: formatAddress(message.replyTo)
88
- },
89
- ...message.headers === undefined ? {} : { headers: message.headers }
90
- };
107
+ const body = bodyOf(message, sender);
91
108
  const signal = AbortSignal.timeout(timeoutMs);
92
109
  let response;
93
110
  try {
@@ -95,7 +112,8 @@ function createResendMailer(options) {
95
112
  method: "POST",
96
113
  headers: {
97
114
  authorization: `Bearer ${options.apiKey}`,
98
- "content-type": "application/json"
115
+ "content-type": "application/json",
116
+ ...message.idempotencyKey === undefined ? {} : { "idempotency-key": message.idempotencyKey }
99
117
  },
100
118
  body: JSON.stringify(body),
101
119
  signal
@@ -112,7 +130,7 @@ function createResendMailer(options) {
112
130
  if (response.ok)
113
131
  return { messageId: text(answer.id) };
114
132
  const cause = resendAnswer(response.status, text(answer.name), text(answer.message));
115
- if (response.status === 400 || response.status === 422) {
133
+ if (response.status === 400 || response.status === 413 || response.status === 422 || response.status === 409 && cause.errorName === "invalid_idempotent_request") {
116
134
  throw new MailRefused("send: Resend refused the message", { cause });
117
135
  }
118
136
  throw new MailFailure("send: Resend could not take the message", {
@@ -126,5 +144,5 @@ export {
126
144
  formatAddress
127
145
  };
128
146
 
129
- //# debugId=900CD1C929776F6D64756E2164756E21
147
+ //# debugId=BC85082B780FD90964756E2164756E21
130
148
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
4
  "sourcesContent": [
5
- "/**\n * `@nxgt/mail-resend` — a Resend transport for `@nxgt/mail`, over `fetch`,\n * with no SDK.\n *\n * ```ts\n * import { createResendMailer } from '@nxgt/mail-resend';\n *\n * const mailer = createResendMailer({\n * apiKey: process.env.RESEND_API_KEY ?? '',\n * from: { name: 'Acme', address: 'noreply@acme.test' },\n * });\n * ```\n *\n * **A failure throws** the `MailFailure` or `MailRefused` of the `@nxgt/mail`\n * peer, what Resend answered as the `cause`. Nothing is retried.\n */\n\nimport {\n\ttype Address,\n\tcheckMessage,\n\ttype Mailer,\n\tMailFailure,\n\ttype MailMessage,\n\tMailRefused,\n\ttype SentMail,\n} from '@nxgt/mail';\n\nexport interface ResendMailerOptions {\n\t/** The API key, `re_…`. */\n\treadonly apiKey: string;\n\t/** The sender of a message that names none. Without it, such a message is refused. */\n\treadonly from?: Address;\n\t/** Default `https://api.resend.com`. */\n\treadonly baseUrl?: string;\n\t/** Default the global `fetch`. For a proxy, or a test. */\n\treadonly fetch?: (url: string, init: RequestInit) => Promise<Response>;\n\t/** How long a send may take before it fails. Default `30000`. */\n\treadonly timeoutMs?: number;\n}\n\n/**\n * An address as Resend reads it: bare, or `\"name\" <address>` — the name a\n * quoted string, so a comma or an angle bracket in it names no one else.\n */\nexport function formatAddress(address: Address): string {\n\tif (typeof address === 'string') return address;\n\tconst name = address.name.replace(/[\\\\\"]/g, (char) => `\\\\${char}`);\n\treturn `\"${name}\" <${address.address}>`;\n}\n\n/**\n * What Resend answered, kept as the `cause`: a plain `Error` — a transport\n * defines no error class of its own — with the status, Resend's error name\n * (`validation_error`, `rate_limit_exceeded`…) and its message as `detail`.\n * Its own message holds the status and the name only: Resend's message can\n * quote an address, and a message reports a shape, never a value.\n */\nfunction resendAnswer(\n\tstatus: number,\n\terrorName: string | null,\n\tdetail: string | null,\n): Error & {\n\treadonly status: number;\n\treadonly errorName: string | null;\n\treadonly detail: string | null;\n} {\n\treturn Object.assign(\n\t\tnew Error(\n\t\t\t`Resend answered ${status}${errorName === null ? '' : ` ${errorName}`}`,\n\t\t),\n\t\t{ status, errorName, detail },\n\t);\n}\n\n/**\n * Settles with `work`, or rejects with the signal's reason once it aborts —\n * so the timeout holds even with an injected `fetch` that ignores the signal.\n */\nfunction beforeAbort<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst abort = () => reject(signal.reason);\n\t\tif (signal.aborted) return abort();\n\t\tsignal.addEventListener('abort', abort, { once: true });\n\t\twork.then(\n\t\t\t(value) => {\n\t\t\t\tsignal.removeEventListener('abort', abort);\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tsignal.removeEventListener('abort', abort);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\n/** The JSON body of an answer, or `{}` when it is not JSON or never ends. */\nasync function readAnswer(\n\tresponse: Response,\n\tsignal: AbortSignal,\n): Promise<Record<string, unknown>> {\n\tconst body: unknown = await beforeAbort(response.json(), signal).then(\n\t\t(value: unknown) => value,\n\t\t() => null,\n\t);\n\treturn typeof body === 'object' && body !== null\n\t\t? (body as Record<string, unknown>)\n\t\t: {};\n}\n\n/** The largest delay a timer takes, 2³¹ − 1 ms — about 24.8 days. */\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n\nconst text = (value: unknown) =>\n\ttypeof value === 'string' && value !== '' ? value : null;\n\nfunction checkOptions(options: ResendMailerOptions): void {\n\tif (typeof options !== 'object' || options === null) {\n\t\tthrow new TypeError(\n\t\t\t'createResendMailer: options must be an object, as { apiKey }',\n\t\t);\n\t}\n\tif (typeof options.apiKey !== 'string' || options.apiKey.trim() === '') {\n\t\tthrow new TypeError(\n\t\t\t'createResendMailer: apiKey must be a Resend API key — is the environment variable set?',\n\t\t);\n\t}\n\tif (/\\s/.test(options.apiKey)) {\n\t\t// A key read from a file often keeps its final line break; `fetch`\n\t\t// would then refuse the header at every send, as an outage.\n\t\tthrow new TypeError(\n\t\t\t'createResendMailer: apiKey holds whitespace — trim the value it was read from',\n\t\t);\n\t}\n\tif (\n\t\toptions.baseUrl !== undefined &&\n\t\t(typeof options.baseUrl !== 'string' ||\n\t\t\t!/^https?:\\/\\/[^/]/.test(options.baseUrl))\n\t) {\n\t\tthrow new TypeError(\n\t\t\t'createResendMailer: baseUrl must be an http: or https: URL',\n\t\t);\n\t}\n\tif (options.fetch !== undefined && typeof options.fetch !== 'function') {\n\t\tthrow new TypeError('createResendMailer: fetch must be a function');\n\t}\n\tif (\n\t\toptions.timeoutMs !== undefined &&\n\t\t!(Number.isInteger(options.timeoutMs) && options.timeoutMs > 0)\n\t) {\n\t\tthrow new TypeError(\n\t\t\t'createResendMailer: timeoutMs must be a positive integer',\n\t\t);\n\t}\n\tif (options.timeoutMs !== undefined && options.timeoutMs > MAX_TIMEOUT_MS) {\n\t\t// A timer's delay is a signed 32-bit integer: above it, the runtime\n\t\t// fires at once, and every send would time out.\n\t\tthrow new TypeError(\n\t\t\t`createResendMailer: timeoutMs must be at most ${MAX_TIMEOUT_MS} — a longer timer fires at once`,\n\t\t);\n\t}\n\tif (options.from !== undefined) {\n\t\ttry {\n\t\t\tcheckMessage({ to: options.from, subject: '', html: '', text: '' });\n\t\t} catch {\n\t\t\tthrow new TypeError(\n\t\t\t\t'createResendMailer: from must be an e-mail address, as noreply@example.com or { name, address }',\n\t\t\t);\n\t\t}\n\t}\n}\n\n/** Creates a {@link Mailer} that sends each message through Resend's API. */\nexport function createResendMailer(options: ResendMailerOptions): Mailer {\n\tcheckOptions(options);\n\tconst endpoint = `${(options.baseUrl ?? 'https://api.resend.com').replace(/\\/+$/, '')}/emails`;\n\tconst post =\n\t\toptions.fetch ??\n\t\t((url: string, init: RequestInit) => globalThis.fetch(url, init));\n\tconst timeoutMs = options.timeoutMs ?? 30_000;\n\n\treturn {\n\t\tasync send(message: MailMessage): Promise<SentMail> {\n\t\t\tcheckMessage(message);\n\t\t\tconst sender = message.from ?? options.from;\n\t\t\tif (sender === undefined) {\n\t\t\t\tthrow new MailRefused(\n\t\t\t\t\t'send: from is missing — give the message a from, or createResendMailer a default one',\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst to = Array.isArray(message.to) ? message.to : [message.to];\n\t\t\tconst body = {\n\t\t\t\tfrom: formatAddress(sender),\n\t\t\t\tto: to.map(formatAddress),\n\t\t\t\tsubject: message.subject,\n\t\t\t\thtml: message.html,\n\t\t\t\ttext: message.text,\n\t\t\t\t...(message.replyTo === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\t// biome-ignore lint/style/useNamingConvention: Resend's wire format names the field, not us.\n\t\t\t\t\t\t\treply_to: formatAddress(message.replyTo),\n\t\t\t\t\t\t}),\n\t\t\t\t...(message.headers === undefined ? {} : { headers: message.headers }),\n\t\t\t};\n\n\t\t\tconst signal = AbortSignal.timeout(timeoutMs);\n\t\t\tlet response: Response;\n\t\t\ttry {\n\t\t\t\tresponse = await beforeAbort(\n\t\t\t\t\tpost(endpoint, {\n\t\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\tauthorization: `Bearer ${options.apiKey}`,\n\t\t\t\t\t\t\t'content-type': 'application/json',\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t}),\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof DOMException && error.name === 'TimeoutError') {\n\t\t\t\t\tthrow new MailFailure(\n\t\t\t\t\t\t`send: Resend did not answer within ${timeoutMs} ms`,\n\t\t\t\t\t\t{ cause: error },\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new MailFailure('send: Resend could not be reached', {\n\t\t\t\t\tcause: error,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst answer = await readAnswer(response, signal);\n\t\t\tif (response.ok) return { messageId: text(answer.id) };\n\n\t\t\tconst cause = resendAnswer(\n\t\t\t\tresponse.status,\n\t\t\t\ttext(answer.name),\n\t\t\t\ttext(answer.message),\n\t\t\t);\n\t\t\t// 400 and 422 are Resend refusing the message; anything else — a key\n\t\t\t// refused, a rate limit, an outage — is Resend failing to take it.\n\t\t\tif (response.status === 400 || response.status === 422) {\n\t\t\t\tthrow new MailRefused('send: Resend refused the message', { cause });\n\t\t\t}\n\t\t\tthrow new MailFailure('send: Resend could not take the message', {\n\t\t\t\tcause,\n\t\t\t});\n\t\t},\n\t};\n}\n"
5
+ "/**\n * `@nxgt/mail-resend` — a Resend transport for `@nxgt/mail`, over `fetch`,\n * with no SDK.\n *\n * ```ts\n * import { createResendMailer } from '@nxgt/mail-resend';\n *\n * const mailer = createResendMailer({\n * apiKey: process.env.RESEND_API_KEY ?? '',\n * from: { name: 'Acme', address: 'noreply@acme.test' },\n * });\n * ```\n *\n * **A failure throws** the `MailFailure` or `MailRefused` of the `@nxgt/mail`\n * peer, what Resend answered as the `cause`. Nothing is retried; a message's\n * `idempotencyKey` is sent as Resend's `Idempotency-Key`, so a retry the\n * caller makes delivers once.\n */\n\nimport {\n\ttype Address,\n\tcheckMessage,\n\ttype Mailer,\n\tMailFailure,\n\ttype MailMessage,\n\tMailRefused,\n\ttype SentMail,\n} from '@nxgt/mail';\n\nexport interface ResendMailerOptions {\n\t/** The API key, `re_…`. */\n\treadonly apiKey: string;\n\t/** The sender of a message that names none. Without it, such a message is refused. */\n\treadonly from?: Address;\n\t/** Default `https://api.resend.com`. */\n\treadonly baseUrl?: string;\n\t/** Default the global `fetch`. For a proxy, or a test. */\n\treadonly fetch?: (url: string, init: RequestInit) => Promise<Response>;\n\t/** How long a send may take before it fails. Default `30000`. */\n\treadonly timeoutMs?: number;\n}\n\n/**\n * An address as Resend reads it: bare, or `\"name\" <address>` — the name a\n * quoted string, so a comma or an angle bracket in it names no one else.\n */\nexport function formatAddress(address: Address): string {\n\tif (typeof address === 'string') return address;\n\tconst name = address.name.replace(/[\\\\\"]/g, (char) => `\\\\${char}`);\n\treturn `\"${name}\" <${address.address}>`;\n}\n\n/**\n * What Resend answered, kept as the `cause`: a plain `Error` — a transport\n * defines no error class of its own — with the status, Resend's error name\n * (`validation_error`, `rate_limit_exceeded`…) and its message as `detail`.\n * Its own message holds the status and the name only: Resend's message can\n * quote an address, and a message reports a shape, never a value.\n */\nfunction resendAnswer(\n\tstatus: number,\n\terrorName: string | null,\n\tdetail: string | null,\n): Error & {\n\treadonly status: number;\n\treadonly errorName: string | null;\n\treadonly detail: string | null;\n} {\n\treturn Object.assign(\n\t\tnew Error(\n\t\t\t`Resend answered ${status}${errorName === null ? '' : ` ${errorName}`}`,\n\t\t),\n\t\t{ status, errorName, detail },\n\t);\n}\n\n/**\n * Settles with `work`, or rejects with the signal's reason once it aborts —\n * so the timeout holds even with an injected `fetch` that ignores the signal.\n */\nfunction beforeAbort<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst abort = () => reject(signal.reason);\n\t\tif (signal.aborted) return abort();\n\t\tsignal.addEventListener('abort', abort, { once: true });\n\t\twork.then(\n\t\t\t(value) => {\n\t\t\t\tsignal.removeEventListener('abort', abort);\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tsignal.removeEventListener('abort', abort);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\n/** The JSON body of an answer, or `{}` when it is not JSON or never ends. */\nasync function readAnswer(\n\tresponse: Response,\n\tsignal: AbortSignal,\n): Promise<Record<string, unknown>> {\n\tconst body: unknown = await beforeAbort(response.json(), signal).then(\n\t\t(value: unknown) => value,\n\t\t() => null,\n\t);\n\treturn typeof body === 'object' && body !== null\n\t\t? (body as Record<string, unknown>)\n\t\t: {};\n}\n\n/**\n * `bytes` as base64, as Resend takes an attachment's `content` — with no Node\n * built-in, so it runs on an edge runtime. Read in slices, so a large file\n * never spreads more arguments than a call takes.\n */\nfunction base64Of(bytes: Uint8Array): string {\n\tlet binary = '';\n\tfor (let start = 0; start < bytes.length; start += 0x8000) {\n\t\tbinary += String.fromCharCode(...bytes.subarray(start, start + 0x8000));\n\t}\n\treturn btoa(binary);\n}\n\n/** The JSON body of `POST /emails`: `message` in Resend's field names. */\nfunction bodyOf(\n\tmessage: MailMessage,\n\tsender: Address,\n): Record<string, unknown> {\n\tconst to = Array.isArray(message.to) ? message.to : [message.to];\n\treturn {\n\t\tfrom: formatAddress(sender),\n\t\tto: to.map(formatAddress),\n\t\tsubject: message.subject,\n\t\thtml: message.html,\n\t\ttext: message.text,\n\t\t...(message.replyTo === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\t// biome-ignore lint/style/useNamingConvention: Resend's wire format names the field, not us.\n\t\t\t\t\treply_to: formatAddress(message.replyTo),\n\t\t\t\t}),\n\t\t...(message.headers === undefined ||\n\t\tObject.keys(message.headers).length === 0\n\t\t\t? {}\n\t\t\t: { headers: message.headers }),\n\t\t...(message.attachments === undefined || message.attachments.length === 0\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tattachments: message.attachments.map((attachment) => ({\n\t\t\t\t\t\tfilename: attachment.filename,\n\t\t\t\t\t\tcontent: base64Of(attachment.content),\n\t\t\t\t\t\t// biome-ignore lint/style/useNamingConvention: Resend's wire format names the field, not us.\n\t\t\t\t\t\tcontent_type: attachment.contentType,\n\t\t\t\t\t})),\n\t\t\t\t}),\n\t};\n}\n\n/** The largest delay a timer takes, 2³¹ − 1 ms — about 24.8 days. */\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n\nconst text = (value: unknown) =>\n\ttypeof value === 'string' && value !== '' ? value : null;\n\nfunction checkOptions(options: ResendMailerOptions): void {\n\tif (typeof options !== 'object' || options === null) {\n\t\tthrow new TypeError(\n\t\t\t'createResendMailer: options must be an object, as { apiKey }',\n\t\t);\n\t}\n\tif (typeof options.apiKey !== 'string' || options.apiKey.trim() === '') {\n\t\tthrow new TypeError(\n\t\t\t'createResendMailer: apiKey must be a Resend API key — is the environment variable set?',\n\t\t);\n\t}\n\tif (/\\s/.test(options.apiKey)) {\n\t\t// A key read from a file often keeps its final line break; `fetch`\n\t\t// would then refuse the header at every send, as an outage.\n\t\tthrow new TypeError(\n\t\t\t'createResendMailer: apiKey holds whitespace — trim the value it was read from',\n\t\t);\n\t}\n\tif (\n\t\toptions.baseUrl !== undefined &&\n\t\t(typeof options.baseUrl !== 'string' ||\n\t\t\t!/^https?:\\/\\/[^/]/.test(options.baseUrl))\n\t) {\n\t\tthrow new TypeError(\n\t\t\t'createResendMailer: baseUrl must be an http: or https: URL',\n\t\t);\n\t}\n\tif (options.fetch !== undefined && typeof options.fetch !== 'function') {\n\t\tthrow new TypeError('createResendMailer: fetch must be a function');\n\t}\n\tif (\n\t\toptions.timeoutMs !== undefined &&\n\t\t!(Number.isInteger(options.timeoutMs) && options.timeoutMs > 0)\n\t) {\n\t\tthrow new TypeError(\n\t\t\t'createResendMailer: timeoutMs must be a positive integer',\n\t\t);\n\t}\n\tif (options.timeoutMs !== undefined && options.timeoutMs > MAX_TIMEOUT_MS) {\n\t\t// A timer's delay is a signed 32-bit integer: above it, the runtime\n\t\t// fires at once, and every send would time out.\n\t\tthrow new TypeError(\n\t\t\t`createResendMailer: timeoutMs must be at most ${MAX_TIMEOUT_MS} — a longer timer fires at once`,\n\t\t);\n\t}\n\tif (options.from !== undefined) {\n\t\ttry {\n\t\t\tcheckMessage({ to: options.from, subject: '', html: '', text: '' });\n\t\t} catch {\n\t\t\tthrow new TypeError(\n\t\t\t\t'createResendMailer: from must be an e-mail address, as noreply@example.com or { name, address }',\n\t\t\t);\n\t\t}\n\t}\n}\n\n/** Creates a {@link Mailer} that sends each message through Resend's API. */\nexport function createResendMailer(options: ResendMailerOptions): Mailer {\n\tcheckOptions(options);\n\tconst endpoint = `${(options.baseUrl ?? 'https://api.resend.com').replace(/\\/+$/, '')}/emails`;\n\tconst post =\n\t\toptions.fetch ??\n\t\t((url: string, init: RequestInit) => globalThis.fetch(url, init));\n\tconst timeoutMs = options.timeoutMs ?? 30_000;\n\n\treturn {\n\t\tasync send(message: MailMessage): Promise<SentMail> {\n\t\t\tcheckMessage(message);\n\t\t\tconst sender = message.from ?? options.from;\n\t\t\tif (sender === undefined) {\n\t\t\t\tthrow new MailRefused(\n\t\t\t\t\t'send: from is missing — give the message a from, or createResendMailer a default one',\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst body = bodyOf(message, sender);\n\n\t\t\tconst signal = AbortSignal.timeout(timeoutMs);\n\t\t\tlet response: Response;\n\t\t\ttry {\n\t\t\t\tresponse = await beforeAbort(\n\t\t\t\t\tpost(endpoint, {\n\t\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\tauthorization: `Bearer ${options.apiKey}`,\n\t\t\t\t\t\t\t'content-type': 'application/json',\n\t\t\t\t\t\t\t...(message.idempotencyKey === undefined\n\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t: { 'idempotency-key': message.idempotencyKey }),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t}),\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof DOMException && error.name === 'TimeoutError') {\n\t\t\t\t\tthrow new MailFailure(\n\t\t\t\t\t\t`send: Resend did not answer within ${timeoutMs} ms`,\n\t\t\t\t\t\t{ cause: error },\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new MailFailure('send: Resend could not be reached', {\n\t\t\t\t\tcause: error,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst answer = await readAnswer(response, signal);\n\t\t\tif (response.ok) return { messageId: text(answer.id) };\n\n\t\t\tconst cause = resendAnswer(\n\t\t\t\tresponse.status,\n\t\t\t\ttext(answer.name),\n\t\t\t\ttext(answer.message),\n\t\t\t);\n\t\t\t// 400 and 422 are Resend refusing the message, 413 a request too large\n\t\t\t// to take, and a 409 invalid_idempotent_request an idempotency key\n\t\t\t// already used for another message: sending again cannot fix any of\n\t\t\t// them. Anything else — a key refused, a rate limit, an outage, a 409\n\t\t\t// for a send with the same key still in progress — is Resend failing\n\t\t\t// to take it.\n\t\t\tif (\n\t\t\t\tresponse.status === 400 ||\n\t\t\t\tresponse.status === 413 ||\n\t\t\t\tresponse.status === 422 ||\n\t\t\t\t(response.status === 409 &&\n\t\t\t\t\tcause.errorName === 'invalid_idempotent_request')\n\t\t\t) {\n\t\t\t\tthrow new MailRefused('send: Resend refused the message', { cause });\n\t\t\t}\n\t\t\tthrow new MailFailure('send: Resend could not take the message', {\n\t\t\t\tcause,\n\t\t\t});\n\t\t},\n\t};\n}\n"
6
6
  ],
7
- "mappings": ";AAiBA;AAAA;AAAA;AAAA;AAAA;AA2BO,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,WAAW,OACpB,MAAM,cAAc,8BACpB;AAAA,QACD,MAAM,IAAI,YAAY,oCAAoC,EAAE,MAAM,CAAC;AAAA,MACpE;AAAA,MACA,MAAM,IAAI,YAAY,2CAA2C;AAAA,QAChE;AAAA,MACD,CAAC;AAAA;AAAA,EAEH;AAAA;",
8
+ "debugId": "BC85082B780FD90964756E2164756E21",
9
9
  "names": []
10
10
  }
package/docs/README.md CHANGED
@@ -7,7 +7,7 @@ mailer, transport, hand-over, refusal, failure — are defined once, in the
7
7
 
8
8
  | Page | Read it when |
9
9
  | --- | --- |
10
- | [Setting up](guide/setup.md) | You are wiring `createResendMailer`: the key, the default sender, a proxy or another `baseUrl`, your own `fetch`, the timeout, and the request each message becomes |
10
+ | [Setting up](guide/setup.md) | You are wiring `createResendMailer`: the key, the default sender, a proxy or another `baseUrl`, your own `fetch`, the timeout, the request each message becomes, and the idempotency key |
11
11
  | [Errors](guide/errors.md) | You are handling what `send` throws: which Resend answers are a `MailRefused`, which a `MailFailure`, what is on `cause`, and every `TypeError` at wiring |
12
12
  | [Testing](guide/testing.md) | You are testing the transport against a local server answering as Resend does, with `describeMailer` — or an application that uses it |
13
13
  | [Troubleshooting](troubleshooting.md) | You have an error message and want its cause and its fix |
@@ -45,7 +45,10 @@ Resend answers an error as `{ statusCode, name, message }`:
45
45
  | Resend answers | Typical `name` | Throws |
46
46
  | --- | --- | --- |
47
47
  | `400` | `validation_error` | `MailRefused` |
48
- | `422` | `validation_error`, `missing_required_field` | `MailRefused` |
48
+ | `413` | — (not in Resend's reference: a request too large for what sits in front of the API; refused, as a resend would fail again) | `MailRefused` |
49
+ | `422` | `validation_error`, `missing_required_field`, `invalid_attachment` | `MailRefused` |
50
+ | `409` | `invalid_idempotent_request` — the `idempotencyKey` was already used, within 24 hours, for a different message | `MailRefused` |
51
+ | `409` | `concurrent_idempotent_requests` — a send with the same key is still in progress | `MailFailure` |
49
52
  | `401`, `403` | `missing_api_key`, `invalid_api_key`, an unverified domain | `MailFailure` |
50
53
  | `429` | `rate_limit_exceeded`, `daily_quota_exceeded` | `MailFailure` |
51
54
  | `5xx` | `internal_server_error` | `MailFailure` |
@@ -57,6 +60,26 @@ A `401` or `403` is a failure although it is a `4xx`: a bad key or an
57
60
  unverified domain refuses every message alike. It is the wiring that is
58
61
  wrong, not the message.
59
62
 
63
+ A `409` is decided by its `name`. `invalid_idempotent_request` is a refusal:
64
+ the key names another e-mail, and sending this one again under it fails
65
+ again — give it its own key. `concurrent_idempotent_requests` is a failure:
66
+ the first send with that key has not finished, and a retry later answers
67
+ its id. See [Setting up — the idempotency key](setup.md#the-idempotency-key).
68
+
69
+ ```ts
70
+ import { MailError, MailRefused } from '@nxgt/mail';
71
+
72
+ try {
73
+ await mailer.send(message);
74
+ } catch (error) {
75
+ const cause = error instanceof MailError ? (error.cause as { status?: number; errorName?: string | null }) : undefined;
76
+ if (error instanceof MailRefused && cause?.errorName === 'invalid_idempotent_request') {
77
+ // a bug in how keys are derived: two different e-mails were given the same one
78
+ }
79
+ throw error;
80
+ }
81
+ ```
82
+
60
83
  ## What `cause` holds
61
84
 
62
85
  For an answer, `cause` is a plain `Error` — the transport defines no class —
@@ -95,8 +118,8 @@ hold one.
95
118
 
96
119
  | `message` | Class | When |
97
120
  | --- | --- | --- |
98
- | `send: Resend refused the message` | `MailRefused` | A `400` or `422` |
99
- | `send: Resend could not take the message` | `MailFailure` | Any other answer that is not `2xx` |
121
+ | `send: Resend refused the message` | `MailRefused` | A `400`, `413` or `422`, or a `409 invalid_idempotent_request` |
122
+ | `send: Resend could not take the message` | `MailFailure` | Any other answer that is not `2xx` — a `409 concurrent_idempotent_requests` included |
100
123
  | `send: Resend could not be reached` | `MailFailure` | `fetch` threw |
101
124
  | `send: Resend did not answer within <timeoutMs> ms` | `MailFailure` | The timeout aborted the request |
102
125
  | `send: from is missing — give the message a from, or createResendMailer a default one` | `MailRefused` | A message without `from`, on a mailer without a default. No request is made |
@@ -152,6 +152,7 @@ await mailer.send({
152
152
  subject: 'Hi',
153
153
  html: '<p>Hi</p>',
154
154
  text: 'Hi',
155
+ attachments: [{ filename: 'hello.txt', content: new TextEncoder().encode('Hello'), contentType: 'text/plain' }],
155
156
  });
156
157
  ```
157
158
 
@@ -168,7 +169,10 @@ Content-Type: application/json
168
169
  "html": "<p>Hi</p>",
169
170
  "text": "Hi",
170
171
  "reply_to": "support@acme.test",
171
- "headers": { "List-Unsubscribe": "<https://acme.test/u>" }
172
+ "headers": { "List-Unsubscribe": "<https://acme.test/u>" },
173
+ "attachments": [
174
+ { "filename": "hello.txt", "content": "SGVsbG8=", "content_type": "text/plain" }
175
+ ]
172
176
  }
173
177
  ```
174
178
 
@@ -185,6 +189,15 @@ Content-Type: application/json
185
189
 
186
190
  - `replyTo` is sent as `reply_to`, Resend's name for it; `reply_to` and
187
191
  `headers` are left out when the message has none.
192
+ - Each attachment is sent as `{ filename, content, content_type }`: its bytes
193
+ as base64, encoded in slices with `btoa` — no `Buffer`, so it runs on an
194
+ edge runtime — and its type as `content_type`, Resend's name for it.
195
+ Resend's `path`, a URL it would fetch, is never used. `attachments` is left
196
+ out when the list is empty.
197
+ - Resend takes at most 40 MB per e-mail **after** base64, which makes a file
198
+ a third larger; over it, the answer is a `4xx` and `send` throws
199
+ `MailRefused`. A large or sensitive file is a signed link in the template
200
+ instead.
188
201
  - Before any of it, `checkMessage` from `@nxgt/mail` refuses what no transport
189
202
  hands over. Its messages are listed in
190
203
  [`@nxgt/mail`'s troubleshooting](https://github.com/softistx/nxgt-mail/blob/develop/packages/mail/docs/troubleshooting.md#sending).
@@ -192,6 +205,70 @@ Content-Type: application/json
192
205
  `send` answers `{ messageId }`: Resend's `id`, or `null` when a `2xx` answer
193
206
  carries none, or is not JSON — the message was accepted, the id is absent.
194
207
 
208
+ ## The idempotency key
209
+
210
+ A message's `idempotencyKey` is sent as Resend's `Idempotency-Key` header —
211
+ never in the JSON body, so it never reaches the e-mail — and a message
212
+ without one sends no such header:
213
+
214
+ ```ts
215
+ await mailer.send({
216
+ to: 'ada@example.com',
217
+ subject: 'Your receipt',
218
+ html: '<p>Thank you for your order.</p>',
219
+ text: 'Thank you for your order.',
220
+ idempotencyKey: 'order-42/receipt',
221
+ });
222
+ ```
223
+
224
+ ```http
225
+ POST /emails HTTP/1.1
226
+ Host: api.resend.com
227
+ Authorization: Bearer re_…
228
+ Content-Type: application/json
229
+ Idempotency-Key: order-42/receipt
230
+
231
+ { "from": "\"Acme\" <noreply@acme.test>", "to": ["ada@example.com"], "subject": "Your receipt", … }
232
+ ```
233
+
234
+ Resend remembers a key for **24 hours**. What it answers a second request
235
+ with the same key:
236
+
237
+ | The second request | Resend answers | `send` |
238
+ | --- | --- | --- |
239
+ | the same message, after the first was accepted | `200`, the first send's `id` | resolves with that `messageId`; nothing more is delivered |
240
+ | a different message — another subject, recipient, attachment | `409 invalid_idempotent_request` | rejects with `MailRefused`: sending it again fails again. Give that e-mail its own key |
241
+ | any message, while the first is still in progress | `409 concurrent_idempotent_requests` | rejects with `MailFailure`: retry later, with the same key |
242
+ | any message, more than 24 hours later | a new send | resolves with a new id: the e-mail is delivered again |
243
+
244
+ Derive the key from what the e-mail is about — `order-42/receipt`,
245
+ `user-7/welcome` — never from the time or a random value, or every retry
246
+ carries a new key. `checkMessage` refuses a key that is not 1 to 256 visible
247
+ ASCII characters, before any request. The transport itself retries nothing:
248
+ the key is what makes **your** retry safe.
249
+
250
+ A job that retries after a failure, with the key it was queued with:
251
+
252
+ ```ts
253
+ import { MailFailure, type MailMessage } from '@nxgt/mail';
254
+ import { createResendMailer } from '@nxgt/mail-resend';
255
+
256
+ const mailer = createResendMailer({ apiKey: process.env.RESEND_API_KEY ?? '', from: 'noreply@acme.test' });
257
+
258
+ // Yours: the queue that runs a job again later — well within 24 hours.
259
+ declare function retryIn(seconds: number): Promise<void>;
260
+
261
+ export async function sendReceiptJob(order: { id: string; email: string }, rendered: Omit<MailMessage, 'to'>): Promise<void> {
262
+ try {
263
+ await mailer.send({ ...rendered, to: order.email, idempotencyKey: `order-${order.id}/receipt` });
264
+ } catch (error) {
265
+ // A timeout, a 5xx, a 409 still in progress: the same key, later, delivers at most once.
266
+ if (error instanceof MailFailure) return retryIn(60);
267
+ throw error; // MailRefused: fix the message, or its key
268
+ }
269
+ }
270
+ ```
271
+
195
272
  ## With the renderer
196
273
 
197
274
  ```ts
@@ -49,8 +49,25 @@ export function startResend() {
49
49
  if (fault === 'outage') return answer(503, 'internal_server_error', 'Service unavailable.');
50
50
  if (fault === 'refusal') return answer(422, 'validation_error', 'Invalid `to` field.');
51
51
 
52
- const body = (await request.json()) as { to: string[]; subject: string; html: string; text: string };
53
- delivered.push({ to: body.to.map(addressOf), subject: body.subject, html: body.html, text: body.text });
52
+ const body = (await request.json()) as {
53
+ to: string[];
54
+ subject: string;
55
+ html: string;
56
+ text: string;
57
+ attachments?: { filename: string; content: string; content_type: string }[];
58
+ };
59
+ delivered.push({
60
+ to: body.to.map(addressOf),
61
+ subject: body.subject,
62
+ html: body.html,
63
+ text: body.text,
64
+ // As Resend reads them: the content is base64, decoded back to bytes.
65
+ attachments: (body.attachments ?? []).map((file) => ({
66
+ filename: file.filename,
67
+ content: Uint8Array.from(atob(file.content), (char) => char.charCodeAt(0)),
68
+ contentType: file.content_type,
69
+ })),
70
+ });
54
71
  return Response.json({ id: `resend-${delivered.length}` });
55
72
  },
56
73
  });
@@ -102,10 +119,11 @@ describeMailer({
102
119
  });
103
120
  ```
104
121
 
105
- All eleven cases pass: a send answers `SentMail`, the message arrives byte for
122
+ All thirteen cases pass: a send answers `SentMail`, the message arrives byte for
106
123
  byte (accents, an emoji, `&amp;` in a link), every recipient is delivered to,
107
- a hostile name reaches only its own address, the refusals — a `Bcc` among the
108
- custom headers included — and the three
124
+ a hostile name reaches only its own address, an attachment arrives byte for
125
+ byte with its name and type, the refusals — a `Bcc` among the custom headers
126
+ and an attachment named with a path included — and the three
109
127
  failure cases — an outage is a `MailFailure` with its `cause` and one attempt,
110
128
  a refusal a `MailRefused`, and the next send goes through.
111
129
 
@@ -115,8 +133,15 @@ The package's own specs
115
133
  ([`src/index.spec.ts`](https://github.com/softistx/nxgt-mail/blob/develop/packages/mail-resend/src/index.spec.ts))
116
134
  add what the suite does not ask of every transport:
117
135
 
118
- - a `400` is a `MailRefused`; a `403`, a `429` and a `503` are a `MailFailure`
136
+ - a `400` and a `413` are a `MailRefused`; a `403`, a `429` and a `503` are a `MailFailure`
119
137
  with the status on `cause`, each tried once;
138
+ - a `409 invalid_idempotent_request` — a key sent again with another
139
+ message — is a `MailRefused`, and a `409 concurrent_idempotent_requests` a
140
+ `MailFailure`, both with `status` and `errorName` on `cause`;
141
+ - `idempotencyKey` is sent as the `Idempotency-Key` header, never in the
142
+ body, and no header is sent without one; a retry with the same key
143
+ answers the first id and delivers once, as the local server keeps keys as
144
+ Resend does;
120
145
  - a server that is not listening ends in `MailFailure` —
121
146
  `send: Resend could not be reached` — with the `fetch` error as `cause`;
122
147
  - a server that does not answer within `timeoutMs` ends in `MailFailure`, a
@@ -127,6 +152,9 @@ add what the suite does not ask of every transport:
127
152
  address or what Resend said;
128
153
  - the request: `POST /emails`, the bearer key, JSON, a quoted name,
129
154
  `reply_to` and `headers`;
155
+ - each attachment as `{ filename, content, content_type }`, the content
156
+ base64 — a file larger than one slice of the encoder included — and no
157
+ `attachments` for an empty list;
130
158
  - a `2xx` with no id, or with a body that is not JSON, answers
131
159
  `{ messageId: null }`;
132
160
  - every `TypeError` at wiring, a `timeoutMs` above `2147483647` included.
package/docs/roadmap.md CHANGED
@@ -5,7 +5,13 @@ no dates here, and the version something shipped in is the only number.
5
5
 
6
6
  ## Now
7
7
 
8
- Nothing between releases.
8
+ - **An idempotency key per send** — a message's `idempotencyKey` is sent as
9
+ Resend's `Idempotency-Key` header, so a retry the caller decides, within
10
+ Resend's 24 hours, answers the first send's id and cannot send the same
11
+ e-mail twice. A `409 invalid_idempotent_request` (the key already used for
12
+ another message) is a `MailRefused`; a `409 concurrent_idempotent_requests`
13
+ (the same key still in progress) stays a `MailFailure`. Needs `@nxgt/mail`
14
+ 0.3. Built, not yet published.
9
15
 
10
16
  ## Next
11
17
 
@@ -13,8 +19,6 @@ Nothing yet.
13
19
 
14
20
  ## Later
15
21
 
16
- - **An idempotency key per send** — Resend's `Idempotency-Key` header, so a
17
- retry the caller decides cannot send the same e-mail twice.
18
22
  - **Tags** — Resend's `tags`, to group sends in its dashboard.
19
23
 
20
24
  ## Not planned
@@ -26,14 +30,20 @@ Nothing yet.
26
30
  send the same e-mail twice.
27
31
  - **A transport's own error class** — it throws `@nxgt/mail`'s `MailFailure`
28
32
  and `MailRefused`, so `instanceof` holds whichever transport you wire.
29
- - **Scheduling, batch sending and attachments** — a message is three strings
30
- sent now; the port has no room for more.
33
+ - **Scheduling and batch sending** — a message is sent now, one per request;
34
+ the port has no room for more.
31
35
 
32
36
  ## Shipped
33
37
 
34
38
  The last ten, newest first, each with the version it came in. Everything
35
39
  before is in the [CHANGELOG](../CHANGELOG.md).
36
40
 
41
+ - **Attachments, v0.2.0** — the `attachments` of a message are sent in Resend's
42
+ `attachments`, each as `{ filename, content, content_type }` with the bytes
43
+ in base64, encoded with no Node built-in so the transport still runs on an
44
+ edge runtime. Resend's `path` (a URL it would fetch) is never used. A
45
+ request too large (`413`) is a `MailRefused`, as a `400` or `422` is. Needs
46
+ `@nxgt/mail` 0.2.
37
47
  - **A Resend transport over `fetch`, v0.1.0** — `createResendMailer({ apiKey, from })`:
38
48
  one `POST /emails` per message, no SDK, no dependency, no Node built-in, so
39
49
  it runs on an edge runtime too. Each message is checked as every transport
@@ -51,11 +51,19 @@ A `send: …` message not on this page comes from `checkMessage` in
51
51
 
52
52
  A `MailRefused`, code `MAIL_REFUSED`.
53
53
 
54
- **When:** Resend answered `400` or `422`: a field it does not accept — an
55
- address in a form it refuses, a header it does not allow, a subject too long.
54
+ **When:** Resend answered `400`, `413` or `422`: a field it does not accept —
55
+ an address in a form it refuses, a header it does not allow, a subject too
56
+ long, an attachment it will not carry (a `422` `invalid_attachment`, over
57
+ 40 MB once encoded in base64 included, a third larger than the files) — or a
58
+ `413`, a request too large for what sits in front of the API. Or a `409`
59
+ `invalid_idempotent_request`: the message's `idempotencyKey` was already used,
60
+ within Resend's 24 hours, for a different message — a key per user rather
61
+ than per e-mail, or a template, a variable or a recipient that changed
62
+ between two attempts at the same e-mail.
56
63
 
57
64
  **Why:** Resend will refuse the same message again; retrying it unchanged is
58
- pointless.
65
+ pointless. For a `409`, the first message with that key was taken; this one
66
+ was not, and will not be under that key.
59
67
 
60
68
  **Fix:** read `cause.errorName` and `cause.detail` — Resend's own words:
61
69
 
@@ -72,6 +80,10 @@ try {
72
80
  detail?: string | null;
73
81
  };
74
82
  console.warn(status, errorName, detail); // 422 validation_error Invalid `to` field. …
83
+ if (status === 409 && errorName === 'invalid_idempotent_request') {
84
+ // The key already named another message: it is not one key per e-mail.
85
+ console.warn('idempotencyKey reused for a different message');
86
+ }
75
87
  }
76
88
  throw error;
77
89
  }
@@ -79,6 +91,22 @@ try {
79
91
 
80
92
  `detail` may quote an address: keep it out of logs that must not hold one.
81
93
 
94
+ For a message too large (`cause.status` `413`, or a `422` whose `detail`
95
+ names the size), sending it again fails again: send the file as a signed
96
+ link in the template instead of an attachment.
97
+
98
+ For an `invalid_idempotent_request`, make the key name one e-mail — derived
99
+ from what it is about, the same on every attempt at it — and render that
100
+ e-mail the same way on every attempt:
101
+
102
+ ```ts
103
+ await mailer.send({ ...message, idempotencyKey: `user-${user.id}` }); // ✗ every e-mail to that user
104
+ await mailer.send({ ...message, idempotencyKey: `order-${order.id}/receipt` }); // ✓ this e-mail
105
+ ```
106
+
107
+ A message that was meant to be different — a corrected receipt — is a new
108
+ e-mail: give it a new key (`order-42/receipt-2`).
109
+
82
110
  ### `send: Resend could not take the message`
83
111
 
84
112
  A `MailFailure`, code `MAIL_FAILED`. **Nothing is known to have been sent**:
@@ -91,11 +119,30 @@ a server that accepted it before failing.
91
119
  | --- | --- | --- |
92
120
  | `401` | No key reached Resend | Check the key the process was started with |
93
121
  | `403` | An invalid or revoked key; a sending domain not verified; a test key sending to someone else than the account's owner | Check the key, and verify the `from` domain in Resend |
122
+ | `409` `concurrent_idempotent_requests` | A send with the same `idempotencyKey` is still in progress — a retry, or a second worker, that started before the first attempt finished | Retry later, with the same key: once the first finishes, the retry answers its id |
94
123
  | `429` | The rate limit or the daily quota | Send less often, or from a queue that spaces the sends |
95
124
  | `5xx` | Resend is failing | Retry later |
96
125
 
97
126
  The transport does not retry: a retry is yours to decide, where you can see
98
- it.
127
+ it. With an `idempotencyKey`, a retry of the same message within 24 hours is
128
+ safe: if the first attempt went through, Resend answers its id and delivers
129
+ nothing more.
130
+
131
+ ```ts
132
+ import { MailFailure } from '@nxgt/mail';
133
+
134
+ try {
135
+ await mailer.send({ ...message, idempotencyKey: `order-${order.id}/receipt` });
136
+ } catch (error) {
137
+ const errorName = error instanceof MailFailure
138
+ ? (error.cause as { errorName?: string | null } | undefined)?.errorName
139
+ : undefined;
140
+ if (errorName === 'concurrent_idempotent_requests') {
141
+ // The first attempt is still running: retry later, with the same key.
142
+ }
143
+ throw error;
144
+ }
145
+ ```
99
146
 
100
147
  ### `send: Resend could not be reached`
101
148
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nxgt/mail-resend",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "A Resend transport for @nxgt/mail over fetch, with no SDK: it throws the MailFailure and MailRefused of its @nxgt/mail peer, and passes the conformance suite.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -43,11 +43,11 @@
43
43
  "typecheck": "tsc --noEmit"
44
44
  },
45
45
  "devDependencies": {
46
- "@nxgt/mail": "0.1.0",
46
+ "@nxgt/mail": "0.3.0",
47
47
  "@types/bun": "^1.4.2"
48
48
  },
49
49
  "peerDependencies": {
50
- "@nxgt/mail": "^0.1.0",
50
+ "@nxgt/mail": "^0.3.0",
51
51
  "typescript": "^6.0.3"
52
52
  }
53
53
  }