@upyo/resend 0.3.0-dev.33

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/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright 2025 Hong Minhee
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,102 @@
1
+ <!-- deno-fmt-ignore-file -->
2
+
3
+ @upyo/resend
4
+ ============
5
+
6
+ [![JSR][JSR badge]][JSR]
7
+ [![npm][npm badge]][npm]
8
+
9
+ [Resend] transport for the [Upyo] email library.
10
+
11
+ [JSR]: https://jsr.io/@upyo/resend
12
+ [JSR badge]: https://jsr.io/badges/@upyo/resend
13
+ [npm]: https://www.npmjs.com/package/@upyo/resend
14
+ [npm badge]: https://img.shields.io/npm/v/@upyo/resend?logo=npm
15
+ [Resend]: https://resend.com/
16
+ [Upyo]: https://upyo.org/
17
+
18
+
19
+ Features
20
+ --------
21
+
22
+ - Single and batch email sending via Resend's HTTP API
23
+ - Automatic idempotency for reliable delivery
24
+ - Smart batch optimization: uses batch API when possible
25
+ - Cross-runtime compatibility (Node.js, Deno, Bun, edge functions)
26
+ - Rich content support: HTML emails, attachments, custom headers
27
+ - Retry logic with exponential backoff
28
+ - Type-safe configuration with sensible defaults
29
+ - Comprehensive error handling
30
+
31
+
32
+ Installation
33
+ ------------
34
+
35
+ ~~~~ sh
36
+ npm add @upyo/core @upyo/resend
37
+ pnpm add @upyo/core @upyo/resend
38
+ yarn add @upyo/core @upyo/resend
39
+ deno add --jsr @upyo/core @upyo/resend
40
+ bun add @upyo/core @upyo/resend
41
+ ~~~~
42
+
43
+
44
+ Usage
45
+ -----
46
+
47
+ ~~~~ typescript
48
+ import { createMessage } from "@upyo/core";
49
+ import { ResendTransport } from "@upyo/resend";
50
+ import process from "node:process";
51
+
52
+ const message = createMessage({
53
+ from: "sender@example.com",
54
+ to: "recipient@example.net",
55
+ subject: "Hello from Upyo!",
56
+ content: { text: "This is a test email." },
57
+ });
58
+
59
+ const transport = new ResendTransport({
60
+ apiKey: process.env.RESEND_API_KEY!,
61
+ });
62
+
63
+ const receipt = await transport.send(message);
64
+ if (receipt.successful) {
65
+ console.log("Message sent with ID:", receipt.messageId);
66
+ } else {
67
+ console.error("Send failed:", receipt.errorMessages.join(", "));
68
+ }
69
+ ~~~~
70
+
71
+ ### Sending Multiple Emails
72
+
73
+ ~~~~ typescript
74
+ const messages = [message1, message2, message3];
75
+
76
+ for await (const receipt of transport.sendMany(messages)) {
77
+ if (receipt.successful) {
78
+ console.log(`Email sent with ID: ${receipt.messageId}`);
79
+ } else {
80
+ console.error(`Email failed: ${receipt.errorMessages.join(", ")}`);
81
+ }
82
+ }
83
+ ~~~~
84
+
85
+
86
+
87
+
88
+ Configuration
89
+ -------------
90
+
91
+ See the [Resend docs] for more information about configuration options.
92
+
93
+ [Resend docs]: https://resend.com/docs
94
+
95
+ ### Available Options
96
+
97
+ - `apiKey`: Your Resend API key
98
+ - `baseUrl`: Resend API base URL (default: `https://api.resend.com`)
99
+ - `timeout`: Request timeout in milliseconds (default: `30000`)
100
+ - `retries`: Number of retry attempts (default: `3`)
101
+ - `validateSsl`: Whether to validate SSL certificates (default: `true`)
102
+ - `headers`: Additional HTTP headers
package/dist/index.cjs ADDED
@@ -0,0 +1,553 @@
1
+
2
+ //#region src/config.ts
3
+ /**
4
+ * Creates a resolved Resend configuration by applying default values to optional fields.
5
+ *
6
+ * This function takes a partial Resend configuration and returns a complete
7
+ * configuration with all optional fields filled with sensible defaults.
8
+ * It is used internally by the Resend transport.
9
+ *
10
+ * @param config - The Resend configuration with optional fields
11
+ * @returns A resolved configuration with all defaults applied
12
+ * @internal
13
+ */
14
+ function createResendConfig(config) {
15
+ return {
16
+ apiKey: config.apiKey,
17
+ baseUrl: config.baseUrl ?? "https://api.resend.com",
18
+ timeout: config.timeout ?? 3e4,
19
+ retries: config.retries ?? 3,
20
+ validateSsl: config.validateSsl ?? true,
21
+ headers: config.headers ?? {}
22
+ };
23
+ }
24
+
25
+ //#endregion
26
+ //#region src/http-client.ts
27
+ /**
28
+ * Resend API error class for handling API-specific errors.
29
+ */
30
+ var ResendApiError = class extends Error {
31
+ statusCode;
32
+ constructor(message, statusCode) {
33
+ super(message);
34
+ this.name = "ResendApiError";
35
+ this.statusCode = statusCode;
36
+ }
37
+ };
38
+ /**
39
+ * HTTP client wrapper for Resend API requests.
40
+ *
41
+ * This class handles authentication, request formatting, error handling,
42
+ * and retry logic for Resend API calls.
43
+ */
44
+ var ResendHttpClient = class {
45
+ config;
46
+ constructor(config) {
47
+ this.config = config;
48
+ }
49
+ /**
50
+ * Sends a single message via Resend API.
51
+ *
52
+ * @param messageData The JSON data to send to Resend.
53
+ * @param signal Optional AbortSignal for cancellation.
54
+ * @returns Promise that resolves to the Resend response.
55
+ */
56
+ sendMessage(messageData, signal) {
57
+ const url = `${this.config.baseUrl}/emails`;
58
+ return this.makeRequest(url, {
59
+ method: "POST",
60
+ headers: { "Content-Type": "application/json" },
61
+ body: JSON.stringify(messageData),
62
+ signal
63
+ });
64
+ }
65
+ /**
66
+ * Sends multiple messages via Resend batch API.
67
+ *
68
+ * @param messagesData Array of message data objects to send.
69
+ * @param signal Optional AbortSignal for cancellation.
70
+ * @returns Promise that resolves to the Resend batch response.
71
+ */
72
+ sendBatch(messagesData, signal) {
73
+ const url = `${this.config.baseUrl}/emails/batch`;
74
+ return this.makeRequest(url, {
75
+ method: "POST",
76
+ headers: { "Content-Type": "application/json" },
77
+ body: JSON.stringify(messagesData),
78
+ signal
79
+ });
80
+ }
81
+ /**
82
+ * Makes an HTTP request to Resend API with retry logic.
83
+ *
84
+ * @param url The URL to make the request to.
85
+ * @param options Fetch options.
86
+ * @returns Promise that resolves to the parsed response.
87
+ */
88
+ async makeRequest(url, options) {
89
+ let lastError = null;
90
+ for (let attempt = 0; attempt <= this.config.retries; attempt++) try {
91
+ const response = await this.fetchWithAuth(url, options);
92
+ const text = await response.text();
93
+ if (!response.ok) {
94
+ let errorMessage;
95
+ try {
96
+ const errorBody = JSON.parse(text);
97
+ errorMessage = errorBody.message;
98
+ } catch {}
99
+ throw new ResendApiError(errorMessage || text || `HTTP ${response.status}`, response.status);
100
+ }
101
+ try {
102
+ return JSON.parse(text);
103
+ } catch (parseError) {
104
+ throw new Error(`Invalid JSON response from Resend API: ${parseError instanceof Error ? parseError.message : String(parseError)}`);
105
+ }
106
+ } catch (error) {
107
+ lastError = error instanceof Error ? error : new Error(String(error));
108
+ if (error instanceof ResendApiError && error.statusCode >= 400 && error.statusCode < 500) throw error;
109
+ if (error instanceof Error && error.name === "AbortError") throw error;
110
+ if (attempt === this.config.retries) throw lastError;
111
+ const backoffMs = Math.min(1e3 * Math.pow(2, attempt), 1e4);
112
+ await new Promise((resolve) => setTimeout(resolve, backoffMs));
113
+ }
114
+ throw lastError || /* @__PURE__ */ new Error("Request failed after all retry attempts");
115
+ }
116
+ /**
117
+ * Makes a fetch request with authentication headers.
118
+ *
119
+ * @param url The URL to fetch.
120
+ * @param options Fetch options.
121
+ * @returns Promise that resolves to the Response.
122
+ */
123
+ async fetchWithAuth(url, options) {
124
+ const headers = new Headers(options.headers);
125
+ headers.set("Authorization", `Bearer ${this.config.apiKey}`);
126
+ for (const [key, value] of Object.entries(this.config.headers)) headers.set(key, value);
127
+ const controller = new AbortController();
128
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
129
+ let signal;
130
+ if (options.signal) {
131
+ const combinedController = new AbortController();
132
+ const onAbort = () => combinedController.abort();
133
+ options.signal.addEventListener("abort", onAbort, { once: true });
134
+ controller.signal.addEventListener("abort", onAbort, { once: true });
135
+ signal = combinedController.signal;
136
+ } else signal = controller.signal;
137
+ try {
138
+ const response = await fetch(url, {
139
+ ...options,
140
+ headers,
141
+ signal
142
+ });
143
+ return response;
144
+ } finally {
145
+ clearTimeout(timeoutId);
146
+ }
147
+ }
148
+ };
149
+
150
+ //#endregion
151
+ //#region src/message-converter.ts
152
+ /**
153
+ * Converts a Upyo Message to Resend API JSON format.
154
+ *
155
+ * This function transforms the standardized Upyo message format into
156
+ * the specific format expected by the Resend API.
157
+ *
158
+ * @param message - The Upyo message to convert
159
+ * @param config - The resolved Resend configuration
160
+ * @param options - Optional conversion options
161
+ * @returns JSON object ready for Resend API submission
162
+ *
163
+ * @example
164
+ * ```typescript
165
+ * const emailData = await convertMessage(message, config);
166
+ * const response = await fetch(url, {
167
+ * method: 'POST',
168
+ * body: JSON.stringify(emailData),
169
+ * headers: { 'Content-Type': 'application/json' }
170
+ * });
171
+ * ```
172
+ */
173
+ async function convertMessage(message, _config, options = {}) {
174
+ const emailData = {
175
+ from: formatAddress(message.sender),
176
+ to: message.recipients.length === 1 ? formatAddress(message.recipients[0]) : message.recipients.map(formatAddress),
177
+ subject: message.subject
178
+ };
179
+ if (message.ccRecipients.length > 0) emailData.cc = message.ccRecipients.map(formatAddress);
180
+ if (message.bccRecipients.length > 0) emailData.bcc = message.bccRecipients.map(formatAddress);
181
+ if (message.replyRecipients.length > 0) emailData.reply_to = formatAddress(message.replyRecipients[0]);
182
+ if ("html" in message.content) {
183
+ emailData.html = message.content.html;
184
+ if (message.content.text) emailData.text = message.content.text;
185
+ } else emailData.text = message.content.text;
186
+ if (message.attachments.length > 0) emailData.attachments = await Promise.all(message.attachments.map(convertAttachment));
187
+ if (message.tags.length > 0) emailData.tags = message.tags.map((tag, index) => ({
188
+ name: `tag${index + 1}`,
189
+ value: tag
190
+ }));
191
+ const headers = {};
192
+ if (message.priority !== "normal") {
193
+ const priorityMap = {
194
+ "high": "1",
195
+ "normal": "3",
196
+ "low": "5"
197
+ };
198
+ headers["X-Priority"] = priorityMap[message.priority];
199
+ }
200
+ for (const [key, value] of message.headers.entries()) if (!isStandardHeader(key)) headers[key] = value;
201
+ if (options.idempotencyKey) headers["Idempotency-Key"] = options.idempotencyKey;
202
+ if (Object.keys(headers).length > 0) emailData.headers = headers;
203
+ if (options.scheduledAt) emailData.scheduled_at = options.scheduledAt.toISOString();
204
+ return emailData;
205
+ }
206
+ /**
207
+ * Converts multiple Upyo Messages to Resend batch API format.
208
+ *
209
+ * This function handles the batch conversion with proper validation
210
+ * for Resend's batch API limitations.
211
+ *
212
+ * @param messages - Array of Upyo messages to convert
213
+ * @param config - The resolved Resend configuration
214
+ * @param options - Optional conversion options
215
+ * @returns Array of JSON objects ready for Resend batch API
216
+ */
217
+ async function convertMessagesBatch(messages, _config, options = {}) {
218
+ if (messages.length > 100) throw new Error("Resend batch API supports maximum 100 emails per request");
219
+ for (const message of messages) {
220
+ if (message.attachments.length > 0) throw new Error("Attachments are not supported in Resend batch API");
221
+ if (message.tags.length > 0) throw new Error("Tags are not supported in Resend batch API");
222
+ }
223
+ const batchData = await Promise.all(messages.map((message, index) => convertMessage(message, _config, {
224
+ ...options,
225
+ idempotencyKey: options.idempotencyKey ? `${options.idempotencyKey}-${index}` : void 0
226
+ })));
227
+ return batchData;
228
+ }
229
+ /**
230
+ * Formats an Address object into a string suitable for Resend API.
231
+ *
232
+ * @param address - The address to format
233
+ * @returns Formatted address string
234
+ */
235
+ function formatAddress(address) {
236
+ if (address.name) {
237
+ const name = address.name.includes("\"") || address.name.includes(",") || address.name.includes("<") || address.name.includes(">") ? `"${address.name.replace(/"/g, "\\\"")}"` : address.name;
238
+ return `${name} <${address.address}>`;
239
+ }
240
+ return address.address;
241
+ }
242
+ /**
243
+ * Converts a Upyo Attachment to Resend attachment format.
244
+ *
245
+ * @param attachment - The Upyo attachment to convert
246
+ * @returns Resend attachment object
247
+ */
248
+ async function convertAttachment(attachment) {
249
+ const content = await attachment.content;
250
+ const resendAttachment = {
251
+ filename: attachment.filename,
252
+ content: await uint8ArrayToBase64(content)
253
+ };
254
+ if (attachment.contentType) resendAttachment.content_type = attachment.contentType;
255
+ return resendAttachment;
256
+ }
257
+ /**
258
+ * Converts a Uint8Array to base64 string using pure JavaScript implementation.
259
+ * This avoids deprecated APIs like btoa() and Node.js-specific Buffer.
260
+ *
261
+ * @param bytes - The Uint8Array to convert
262
+ * @returns Base64 encoded string
263
+ */
264
+ function uint8ArrayToBase64(bytes) {
265
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
266
+ let result = "";
267
+ let i = 0;
268
+ while (i < bytes.length) {
269
+ const a = bytes[i++];
270
+ const b = i < bytes.length ? bytes[i++] : 0;
271
+ const c = i < bytes.length ? bytes[i++] : 0;
272
+ const bitmap = a << 16 | b << 8 | c;
273
+ result += chars.charAt(bitmap >> 18 & 63) + chars.charAt(bitmap >> 12 & 63) + chars.charAt(bitmap >> 6 & 63) + chars.charAt(bitmap & 63);
274
+ }
275
+ const padding = 3 - (bytes.length - 1) % 3;
276
+ if (padding < 3) result = result.slice(0, -padding) + "=".repeat(padding);
277
+ return result;
278
+ }
279
+ /**
280
+ * Checks if a header is a standard email header that should not be prefixed.
281
+ *
282
+ * @param headerName - The header name to check
283
+ * @returns True if the header is a standard header
284
+ */
285
+ function isStandardHeader(headerName) {
286
+ const standardHeaders = new Set([
287
+ "from",
288
+ "to",
289
+ "cc",
290
+ "bcc",
291
+ "reply-to",
292
+ "subject",
293
+ "content-type",
294
+ "content-transfer-encoding",
295
+ "mime-version",
296
+ "date",
297
+ "message-id"
298
+ ]);
299
+ return standardHeaders.has(headerName.toLowerCase());
300
+ }
301
+ /**
302
+ * Generates a random idempotency key for request deduplication.
303
+ *
304
+ * @returns A unique string suitable for use as an idempotency key
305
+ */
306
+ function generateIdempotencyKey() {
307
+ const timestamp = Date.now().toString(36);
308
+ const random1 = Math.random().toString(36).substring(2, 15);
309
+ const random2 = Math.random().toString(36).substring(2, 15);
310
+ return `${timestamp}-${random1}${random2}`;
311
+ }
312
+
313
+ //#endregion
314
+ //#region src/resend-transport.ts
315
+ /**
316
+ * Resend transport implementation for sending emails via Resend API.
317
+ *
318
+ * This transport provides efficient email delivery using Resend's HTTP API,
319
+ * with support for authentication, retry logic, batch sending capabilities,
320
+ * and idempotency for reliable delivery.
321
+ *
322
+ * @example
323
+ * ```typescript
324
+ * import { ResendTransport } from '@upyo/resend';
325
+ *
326
+ * const transport = new ResendTransport({
327
+ * apiKey: 'your-resend-api-key',
328
+ * timeout: 30000,
329
+ * retries: 3
330
+ * });
331
+ *
332
+ * const receipt = await transport.send(message);
333
+ * if (receipt.successful) {
334
+ * console.log('Message sent with ID:', receipt.messageId);
335
+ * } else {
336
+ * console.error('Send failed:', receipt.errorMessages.join(', '));
337
+ * }
338
+ * ```
339
+ */
340
+ var ResendTransport = class {
341
+ /**
342
+ * The resolved Resend configuration used by this transport.
343
+ */
344
+ config;
345
+ httpClient;
346
+ /**
347
+ * Creates a new Resend transport instance.
348
+ *
349
+ * @param config Resend configuration including API key and options.
350
+ */
351
+ constructor(config) {
352
+ this.config = createResendConfig(config);
353
+ this.httpClient = new ResendHttpClient(this.config);
354
+ }
355
+ /**
356
+ * Sends a single email message via Resend API.
357
+ *
358
+ * This method converts the message to Resend format, makes an HTTP request
359
+ * to the Resend API with automatic idempotency key generation, and returns
360
+ * a receipt with the result.
361
+ *
362
+ * @example
363
+ * ```typescript
364
+ * const receipt = await transport.send({
365
+ * sender: { address: 'from@example.com' },
366
+ * recipients: [{ address: 'to@example.com' }],
367
+ * ccRecipients: [],
368
+ * bccRecipients: [],
369
+ * replyRecipients: [],
370
+ * subject: 'Hello',
371
+ * content: { text: 'Hello World!' },
372
+ * attachments: [],
373
+ * priority: 'normal',
374
+ * tags: [],
375
+ * headers: new Headers()
376
+ * });
377
+ *
378
+ * if (receipt.successful) {
379
+ * console.log('Message sent with ID:', receipt.messageId);
380
+ * }
381
+ * ```
382
+ *
383
+ * @param message The email message to send.
384
+ * @param options Optional transport options including `AbortSignal` for
385
+ * cancellation.
386
+ * @returns A promise that resolves to a receipt indicating success or
387
+ * failure.
388
+ */
389
+ async send(message, options) {
390
+ try {
391
+ options?.signal?.throwIfAborted();
392
+ const idempotencyKey = generateIdempotencyKey();
393
+ const emailData = await convertMessage(message, this.config, { idempotencyKey });
394
+ options?.signal?.throwIfAborted();
395
+ const response = await this.httpClient.sendMessage(emailData, options?.signal);
396
+ return {
397
+ successful: true,
398
+ messageId: response.id
399
+ };
400
+ } catch (error) {
401
+ const errorMessage = error instanceof Error ? error.message : String(error);
402
+ return {
403
+ successful: false,
404
+ errorMessages: [errorMessage]
405
+ };
406
+ }
407
+ }
408
+ /**
409
+ * Sends multiple email messages efficiently via Resend API.
410
+ *
411
+ * This method intelligently chooses between single requests and batch API
412
+ * based on message count and features used. For optimal performance:
413
+ * - Uses batch API for ≤100 messages without attachments or tags
414
+ * - Falls back to individual requests for messages with unsupported features
415
+ * - Chunks large batches (>100) into multiple batch requests
416
+ *
417
+ * @example
418
+ * ```typescript
419
+ * const messages = [
420
+ * {
421
+ * sender: { address: 'from@example.com' },
422
+ * recipients: [{ address: 'user1@example.com' }],
423
+ * ccRecipients: [],
424
+ * bccRecipients: [],
425
+ * replyRecipients: [],
426
+ * subject: 'Message 1',
427
+ * content: { text: 'Hello User 1!' },
428
+ * attachments: [],
429
+ * priority: 'normal',
430
+ * tags: [],
431
+ * headers: new Headers()
432
+ * },
433
+ * {
434
+ * sender: { address: 'from@example.com' },
435
+ * recipients: [{ address: 'user2@example.com' }],
436
+ * ccRecipients: [],
437
+ * bccRecipients: [],
438
+ * replyRecipients: [],
439
+ * subject: 'Message 2',
440
+ * content: { text: 'Hello User 2!' },
441
+ * attachments: [],
442
+ * priority: 'normal',
443
+ * tags: [],
444
+ * headers: new Headers()
445
+ * }
446
+ * ];
447
+ *
448
+ * for await (const receipt of transport.sendMany(messages)) {
449
+ * if (receipt.successful) {
450
+ * console.log('Sent:', receipt.messageId);
451
+ * } else {
452
+ * console.error('Failed:', receipt.errorMessages);
453
+ * }
454
+ * }
455
+ * ```
456
+ *
457
+ * @param messages An iterable or async iterable of messages to send.
458
+ * @param options Optional transport options including `AbortSignal` for
459
+ * cancellation.
460
+ * @returns An async iterable of receipts, one for each message.
461
+ */
462
+ async *sendMany(messages, options) {
463
+ options?.signal?.throwIfAborted();
464
+ const isAsyncIterable = Symbol.asyncIterator in messages;
465
+ const messageArray = [];
466
+ if (isAsyncIterable) for await (const message of messages) {
467
+ options?.signal?.throwIfAborted();
468
+ messageArray.push(message);
469
+ }
470
+ else for (const message of messages) {
471
+ options?.signal?.throwIfAborted();
472
+ messageArray.push(message);
473
+ }
474
+ yield* this.sendManyOptimized(messageArray, options);
475
+ }
476
+ /**
477
+ * Optimized batch sending that chooses the best strategy based on message features.
478
+ *
479
+ * @param messages Array of messages to send
480
+ * @param options Transport options
481
+ * @returns Async iterable of receipts
482
+ */
483
+ async *sendManyOptimized(messages, options) {
484
+ if (messages.length === 0) return;
485
+ const canUseBatch = this.canUseBatchApi(messages);
486
+ if (canUseBatch && messages.length <= 100) yield* this.sendBatch(messages, options);
487
+ else if (canUseBatch && messages.length > 100) {
488
+ const chunks = this.chunkArray(messages, 100);
489
+ for (const chunk of chunks) {
490
+ options?.signal?.throwIfAborted();
491
+ yield* this.sendBatch(chunk, options);
492
+ }
493
+ } else for (const message of messages) {
494
+ options?.signal?.throwIfAborted();
495
+ yield await this.send(message, options);
496
+ }
497
+ }
498
+ /**
499
+ * Sends a batch of messages using Resend's batch API.
500
+ *
501
+ * @param messages Array of messages (≤100)
502
+ * @param options Transport options
503
+ * @returns Async iterable of receipts
504
+ */
505
+ async *sendBatch(messages, options) {
506
+ options?.signal?.throwIfAborted();
507
+ try {
508
+ const idempotencyKey = generateIdempotencyKey();
509
+ const batchData = await convertMessagesBatch(messages, this.config, { idempotencyKey });
510
+ options?.signal?.throwIfAborted();
511
+ const response = await this.httpClient.sendBatch(batchData, options?.signal);
512
+ for (const result of response.data) yield {
513
+ successful: true,
514
+ messageId: result.id
515
+ };
516
+ } catch (error) {
517
+ const errorMessage = error instanceof Error ? error.message : String(error);
518
+ for (let i = 0; i < messages.length; i++) yield {
519
+ successful: false,
520
+ errorMessages: [errorMessage]
521
+ };
522
+ }
523
+ }
524
+ /**
525
+ * Checks if messages can use Resend's batch API.
526
+ *
527
+ * Batch API limitations:
528
+ * - No attachments
529
+ * - No tags
530
+ * - No scheduled sending
531
+ *
532
+ * @param messages Array of messages to check
533
+ * @returns True if all messages are suitable for batch API
534
+ */
535
+ canUseBatchApi(messages) {
536
+ return messages.every((message) => message.attachments.length === 0 && message.tags.length === 0);
537
+ }
538
+ /**
539
+ * Splits an array into chunks of specified size.
540
+ *
541
+ * @param array Array to chunk
542
+ * @param size Chunk size
543
+ * @returns Array of chunks
544
+ */
545
+ chunkArray(array, size) {
546
+ const chunks = [];
547
+ for (let i = 0; i < array.length; i += size) chunks.push(array.slice(i, i + size));
548
+ return chunks;
549
+ }
550
+ };
551
+
552
+ //#endregion
553
+ exports.ResendTransport = ResendTransport;