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