@upyo/sendgrid 0.1.0-dev.13

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 ADDED
@@ -0,0 +1,77 @@
1
+ <!-- deno-fmt-ignore-file -->
2
+
3
+ @upyo/sendgrid
4
+ ==============
5
+
6
+ [![JSR][JSR badge]][JSR]
7
+ [![npm][npm badge]][npm]
8
+
9
+ [SendGrid] transport for the [Upyo] email library.
10
+
11
+ [JSR]: https://jsr.io/@upyo/sendgrid
12
+ [JSR badge]: https://jsr.io/badges/@upyo/sendgrid
13
+ [npm]: https://www.npmjs.com/package/@upyo/sendgrid
14
+ [npm badge]: https://img.shields.io/npm/v/@upyo/sendgrid?logo=npm
15
+ [SendGrid]: https://sendgrid.com/
16
+ [Upyo]: https://upyo.org/
17
+
18
+
19
+ Installation
20
+ ------------
21
+
22
+ ~~~~ sh
23
+ npm add @upyo/core @upyo/sendgrid
24
+ pnpm add @upyo/core @upyo/sendgrid
25
+ yarn add @upyo/core @upyo/sendgrid
26
+ deno add --jsr @upyo/core @upyo/sendgrid
27
+ bun add @upyo/core @upyo/sendgrid
28
+ ~~~~
29
+
30
+
31
+ Usage
32
+ -----
33
+
34
+ ~~~~ typescript
35
+ import { createMessage } from "@upyo/core";
36
+ import { SendGridTransport } from "@upyo/sendgrid";
37
+ import fs from "node:fs/promises";
38
+ import process from "node:process";
39
+
40
+ const message = createMessage({
41
+ from: "sender@example.com",
42
+ to: "recipient@example.net",
43
+ subject: "Hello from Upyo!",
44
+ content: { text: "This is a test email." },
45
+ attachments: [
46
+ new File(
47
+ [await fs.readFile("image.jpg"), "image.jpg", { type: "image/jpeg" }]
48
+ )
49
+ ],
50
+ });
51
+
52
+ const transport = new SendGridTransport({
53
+ apiKey: process.env.SENDGRID_API_KEY!,
54
+ });
55
+
56
+ const receipt = await transport.send(message);
57
+ console.log("Email sent:", receipt.successful);
58
+ ~~~~
59
+
60
+
61
+ Configuration
62
+ -------------
63
+
64
+ See the [SendGrid docs] for more information about configuration options.
65
+
66
+ [SendGrid docs]: https://docs.sendgrid.com/
67
+
68
+ ### Available Options
69
+
70
+ - `apiKey`: Your SendGrid API key (starts with `SG.`)
71
+ - `baseUrl`: SendGrid API base URL (default: `https://api.sendgrid.com/v3`)
72
+ - `timeout`: Request timeout in milliseconds (default: 30000)
73
+ - `retries`: Number of retry attempts (default: 3)
74
+ - `clickTracking`: Enable click tracking (default: true)
75
+ - `openTracking`: Enable open tracking (default: true)
76
+ - `subscriptionTracking`: Enable subscription tracking (default: false)
77
+ - `googleAnalytics`: Enable Google Analytics tracking (default: false)
package/dist/index.cjs ADDED
@@ -0,0 +1,470 @@
1
+
2
+ //#region src/config.ts
3
+ /**
4
+ * Creates a resolved SendGrid configuration by applying default values to optional fields.
5
+ *
6
+ * This function takes a partial SendGrid configuration and returns a complete
7
+ * configuration with all optional fields filled with sensible defaults.
8
+ *
9
+ * @param config - The SendGrid configuration with optional fields
10
+ * @returns A resolved configuration with all defaults applied
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * const resolved = createSendGridConfig({
15
+ * apiKey: 'your-api-key'
16
+ * });
17
+ *
18
+ * // resolved.baseUrl will be 'https://api.sendgrid.com/v3' (default)
19
+ * // resolved.timeout will be 30000 (default)
20
+ * // resolved.retries will be 3 (default)
21
+ * ```
22
+ */
23
+ function createSendGridConfig(config) {
24
+ return {
25
+ apiKey: config.apiKey,
26
+ baseUrl: config.baseUrl ?? "https://api.sendgrid.com/v3",
27
+ timeout: config.timeout ?? 3e4,
28
+ retries: config.retries ?? 3,
29
+ validateSsl: config.validateSsl ?? true,
30
+ headers: config.headers ?? {},
31
+ clickTracking: config.clickTracking ?? true,
32
+ openTracking: config.openTracking ?? true,
33
+ subscriptionTracking: config.subscriptionTracking ?? false,
34
+ googleAnalytics: config.googleAnalytics ?? false
35
+ };
36
+ }
37
+
38
+ //#endregion
39
+ //#region src/http-client.ts
40
+ /**
41
+ * HTTP client wrapper for SendGrid API requests.
42
+ *
43
+ * This class handles authentication, request formatting, error handling,
44
+ * and retry logic for SendGrid API calls.
45
+ */
46
+ var SendGridHttpClient = class {
47
+ config;
48
+ constructor(config) {
49
+ this.config = config;
50
+ }
51
+ /**
52
+ * Sends a message via SendGrid API.
53
+ *
54
+ * @param messageData The JSON data to send to SendGrid.
55
+ * @param signal Optional AbortSignal for cancellation.
56
+ * @returns Promise that resolves to the SendGrid response.
57
+ */
58
+ sendMessage(messageData, signal) {
59
+ const url = `${this.config.baseUrl}/mail/send`;
60
+ return this.makeRequest(url, {
61
+ method: "POST",
62
+ headers: { "Content-Type": "application/json" },
63
+ body: JSON.stringify(messageData),
64
+ signal
65
+ });
66
+ }
67
+ /**
68
+ * Makes an HTTP request to SendGrid API with retry logic.
69
+ *
70
+ * @param url The URL to make the request to.
71
+ * @param options Fetch options.
72
+ * @returns Promise that resolves to the parsed response.
73
+ */
74
+ async makeRequest(url, options) {
75
+ let lastError = null;
76
+ for (let attempt = 0; attempt <= this.config.retries; attempt++) try {
77
+ const response = await this.fetchWithAuth(url, options);
78
+ const text = await response.text();
79
+ if (response.status === 202) return {
80
+ statusCode: response.status,
81
+ body: text,
82
+ headers: this.headersToRecord(response.headers)
83
+ };
84
+ let errorData;
85
+ try {
86
+ errorData = JSON.parse(text);
87
+ } catch {
88
+ errorData = { message: text || `HTTP ${response.status}` };
89
+ }
90
+ throw new SendGridApiError(errorData.message || `HTTP ${response.status}`, response.status, errorData.errors);
91
+ } catch (error) {
92
+ lastError = error instanceof Error ? error : new Error(String(error));
93
+ if (error instanceof SendGridApiError && error.statusCode && error.statusCode >= 400 && error.statusCode < 500) throw error;
94
+ if (attempt === this.config.retries) throw error;
95
+ const delay = Math.pow(2, attempt) * 1e3;
96
+ await new Promise((resolve) => setTimeout(resolve, delay));
97
+ }
98
+ throw lastError || /* @__PURE__ */ new Error("Request failed after all retries");
99
+ }
100
+ /**
101
+ * Makes a fetch request with SendGrid authentication.
102
+ *
103
+ * @param url The URL to make the request to.
104
+ * @param options Fetch options.
105
+ * @returns Promise that resolves to the fetch response.
106
+ */
107
+ async fetchWithAuth(url, options) {
108
+ const headers = new Headers(options.headers);
109
+ headers.set("Authorization", `Bearer ${this.config.apiKey}`);
110
+ for (const [key, value] of Object.entries(this.config.headers)) headers.set(key, value);
111
+ const controller = new AbortController();
112
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
113
+ let signal = controller.signal;
114
+ if (options.signal) {
115
+ signal = options.signal;
116
+ if (options.signal.aborted) controller.abort();
117
+ else options.signal.addEventListener("abort", () => controller.abort());
118
+ }
119
+ try {
120
+ return await globalThis.fetch(url, {
121
+ ...options,
122
+ headers,
123
+ signal
124
+ });
125
+ } finally {
126
+ clearTimeout(timeoutId);
127
+ }
128
+ }
129
+ /**
130
+ * Converts Headers object to a plain Record.
131
+ *
132
+ * @param headers The Headers object to convert.
133
+ * @returns A plain object with header key-value pairs.
134
+ */
135
+ headersToRecord(headers) {
136
+ const record = {};
137
+ for (const [key, value] of headers.entries()) record[key] = value;
138
+ return record;
139
+ }
140
+ };
141
+ /**
142
+ * Custom error class for SendGrid API errors.
143
+ */
144
+ var SendGridApiError = class extends Error {
145
+ statusCode;
146
+ errors;
147
+ constructor(message, statusCode, errors) {
148
+ super(message);
149
+ this.name = "SendGridApiError";
150
+ this.statusCode = statusCode;
151
+ this.errors = errors;
152
+ }
153
+ };
154
+
155
+ //#endregion
156
+ //#region src/message-converter.ts
157
+ /**
158
+ * Converts a Upyo Message to SendGrid API JSON format.
159
+ *
160
+ * This function transforms the standardized Upyo message format into
161
+ * the specific format expected by the SendGrid API.
162
+ *
163
+ * @param message - The Upyo message to convert
164
+ * @param config - The resolved SendGrid configuration
165
+ * @returns Promise that resolves to a SendGrid mail object
166
+ *
167
+ * @example
168
+ * ```typescript
169
+ * const mailData = await convertMessage(message, config);
170
+ * const response = await httpClient.sendMessage(mailData);
171
+ * ```
172
+ */
173
+ async function convertMessage(message, config) {
174
+ const sendGridMail = {
175
+ personalizations: [],
176
+ from: formatAddress(message.sender)
177
+ };
178
+ const personalization = {
179
+ to: message.recipients.map(formatAddress),
180
+ subject: message.subject
181
+ };
182
+ if (message.ccRecipients.length > 0) personalization.cc = message.ccRecipients.map(formatAddress);
183
+ if (message.bccRecipients.length > 0) personalization.bcc = message.bccRecipients.map(formatAddress);
184
+ sendGridMail.personalizations.push(personalization);
185
+ if (message.replyRecipients.length > 0) if (message.replyRecipients.length === 1) sendGridMail.reply_to = formatAddress(message.replyRecipients[0]);
186
+ else sendGridMail.reply_to_list = message.replyRecipients.map(formatAddress);
187
+ const content = [];
188
+ if ("html" in message.content) {
189
+ if (message.content.text) content.push({
190
+ type: "text/plain",
191
+ value: message.content.text
192
+ });
193
+ content.push({
194
+ type: "text/html",
195
+ value: message.content.html
196
+ });
197
+ } else content.push({
198
+ type: "text/plain",
199
+ value: message.content.text
200
+ });
201
+ sendGridMail.content = content;
202
+ if (message.priority !== "normal") {
203
+ const headers = {};
204
+ switch (message.priority) {
205
+ case "high":
206
+ headers["X-Priority"] = "1";
207
+ headers["X-MSMail-Priority"] = "High";
208
+ headers["Importance"] = "High";
209
+ break;
210
+ case "low":
211
+ headers["X-Priority"] = "5";
212
+ headers["X-MSMail-Priority"] = "Low";
213
+ headers["Importance"] = "Low";
214
+ break;
215
+ }
216
+ sendGridMail.headers = {
217
+ ...sendGridMail.headers,
218
+ ...headers
219
+ };
220
+ }
221
+ if (message.tags.length > 0) sendGridMail.categories = message.tags;
222
+ const customHeaders = {};
223
+ for (const [key, value] of message.headers.entries()) if (!isStandardHeader(key)) customHeaders[key] = value;
224
+ if (Object.keys(customHeaders).length > 0) sendGridMail.headers = {
225
+ ...sendGridMail.headers,
226
+ ...customHeaders
227
+ };
228
+ if (message.attachments.length > 0) sendGridMail.attachments = await Promise.all(message.attachments.map(convertAttachment));
229
+ const trackingSettings = {};
230
+ if (config.clickTracking !== void 0) trackingSettings.click_tracking = {
231
+ enable: config.clickTracking,
232
+ enable_text: config.clickTracking
233
+ };
234
+ if (config.openTracking !== void 0) trackingSettings.open_tracking = { enable: config.openTracking };
235
+ if (config.subscriptionTracking !== void 0) trackingSettings.subscription_tracking = { enable: config.subscriptionTracking };
236
+ if (config.googleAnalytics !== void 0) trackingSettings.ganalytics = { enable: config.googleAnalytics };
237
+ if (Object.keys(trackingSettings).length > 0) sendGridMail.tracking_settings = trackingSettings;
238
+ return sendGridMail;
239
+ }
240
+ /**
241
+ * Formats an address for SendGrid API.
242
+ *
243
+ * @param address - The address to format
244
+ * @returns Formatted address object
245
+ */
246
+ function formatAddress(address) {
247
+ const result = { email: address.address };
248
+ if (address.name) result.name = address.name;
249
+ return result;
250
+ }
251
+ /**
252
+ * Converts a Upyo attachment to SendGrid format.
253
+ *
254
+ * @param attachment - The attachment to convert
255
+ * @returns Promise that resolves to a SendGrid attachment object
256
+ */
257
+ async function convertAttachment(attachment) {
258
+ const contentBytes = await attachment.content;
259
+ const base64Content = btoa(String.fromCharCode(...contentBytes));
260
+ const sendGridAttachment = {
261
+ content: base64Content,
262
+ filename: attachment.filename
263
+ };
264
+ if (attachment.contentType) sendGridAttachment.type = attachment.contentType;
265
+ if (attachment.inline && attachment.contentId) {
266
+ sendGridAttachment.disposition = "inline";
267
+ sendGridAttachment.content_id = attachment.contentId;
268
+ } else sendGridAttachment.disposition = "attachment";
269
+ return sendGridAttachment;
270
+ }
271
+ /**
272
+ * Checks if a header is a standard email header that should not be added as custom header.
273
+ *
274
+ * @param headerName - The header name to check
275
+ * @returns True if it's a standard header
276
+ */
277
+ function isStandardHeader(headerName) {
278
+ const standardHeaders = [
279
+ "from",
280
+ "to",
281
+ "cc",
282
+ "bcc",
283
+ "reply-to",
284
+ "subject",
285
+ "date",
286
+ "message-id",
287
+ "content-type",
288
+ "content-transfer-encoding",
289
+ "mime-version",
290
+ "x-priority",
291
+ "x-msmail-priority",
292
+ "importance"
293
+ ];
294
+ return standardHeaders.includes(headerName.toLowerCase());
295
+ }
296
+
297
+ //#endregion
298
+ //#region src/sendgrid-transport.ts
299
+ /**
300
+ * SendGrid transport implementation for sending emails via SendGrid API.
301
+ *
302
+ * This transport provides efficient email delivery using SendGrid's v3 HTTP API,
303
+ * with support for authentication, retry logic, and batch sending capabilities.
304
+ *
305
+ * @example
306
+ * ```typescript
307
+ * import { SendGridTransport } from '@upyo/sendgrid';
308
+ *
309
+ * const transport = new SendGridTransport({
310
+ * apiKey: 'your-sendgrid-api-key',
311
+ * clickTracking: true,
312
+ * openTracking: true
313
+ * });
314
+ *
315
+ * const receipt = await transport.send(message);
316
+ * console.log('Message sent:', receipt.messageId);
317
+ * ```
318
+ */
319
+ var SendGridTransport = class {
320
+ config;
321
+ httpClient;
322
+ /**
323
+ * Creates a new SendGrid transport instance.
324
+ *
325
+ * @param config SendGrid configuration including API key and options.
326
+ */
327
+ constructor(config) {
328
+ this.config = createSendGridConfig(config);
329
+ this.httpClient = new SendGridHttpClient(this.config);
330
+ }
331
+ /**
332
+ * Sends a single email message via SendGrid API.
333
+ *
334
+ * This method converts the message to SendGrid format, makes an HTTP request
335
+ * to the SendGrid API, and returns a receipt with the result.
336
+ *
337
+ * @example
338
+ * ```typescript
339
+ * const receipt = await transport.send({
340
+ * sender: { address: 'from@example.com' },
341
+ * recipients: [{ address: 'to@example.com' }],
342
+ * ccRecipients: [],
343
+ * bccRecipients: [],
344
+ * replyRecipients: [],
345
+ * subject: 'Hello',
346
+ * content: { text: 'Hello World!' },
347
+ * attachments: [],
348
+ * priority: 'normal',
349
+ * tags: [],
350
+ * headers: new Headers()
351
+ * });
352
+ *
353
+ * if (receipt.successful) {
354
+ * console.log('Message sent successfully');
355
+ * }
356
+ * ```
357
+ *
358
+ * @param message The email message to send.
359
+ * @param options Optional transport options including `AbortSignal` for
360
+ * cancellation.
361
+ * @returns A promise that resolves to a receipt indicating success or
362
+ * failure.
363
+ */
364
+ async send(message, options) {
365
+ options?.signal?.throwIfAborted();
366
+ try {
367
+ const mailData = await convertMessage(message, this.config);
368
+ options?.signal?.throwIfAborted();
369
+ const response = await this.httpClient.sendMessage(mailData, options?.signal);
370
+ const messageId = this.extractMessageId(response);
371
+ return {
372
+ messageId,
373
+ errorMessages: [],
374
+ successful: true
375
+ };
376
+ } catch (error) {
377
+ const errorMessage = error instanceof Error ? error.message : String(error);
378
+ return {
379
+ messageId: "",
380
+ errorMessages: [errorMessage],
381
+ successful: false
382
+ };
383
+ }
384
+ }
385
+ /**
386
+ * Sends multiple email messages efficiently via SendGrid API.
387
+ *
388
+ * This method sends each message individually but provides a streamlined
389
+ * interface for processing multiple messages. Each message is sent as a
390
+ * separate API request to SendGrid.
391
+ *
392
+ * @example
393
+ * ```typescript
394
+ * const messages = [
395
+ * {
396
+ * sender: { address: 'from@example.com' },
397
+ * recipients: [{ address: 'user1@example.com' }],
398
+ * ccRecipients: [],
399
+ * bccRecipients: [],
400
+ * replyRecipients: [],
401
+ * subject: 'Message 1',
402
+ * content: { text: 'Hello User 1!' },
403
+ * attachments: [],
404
+ * priority: 'normal',
405
+ * tags: [],
406
+ * headers: new Headers()
407
+ * },
408
+ * {
409
+ * sender: { address: 'from@example.com' },
410
+ * recipients: [{ address: 'user2@example.com' }],
411
+ * ccRecipients: [],
412
+ * bccRecipients: [],
413
+ * replyRecipients: [],
414
+ * subject: 'Message 2',
415
+ * content: { text: 'Hello User 2!' },
416
+ * attachments: [],
417
+ * priority: 'normal',
418
+ * tags: [],
419
+ * headers: new Headers()
420
+ * }
421
+ * ];
422
+ *
423
+ * for await (const receipt of transport.sendMany(messages)) {
424
+ * if (receipt.successful) {
425
+ * console.log('Sent:', receipt.messageId);
426
+ * } else {
427
+ * console.error('Failed:', receipt.errorMessages);
428
+ * }
429
+ * }
430
+ * ```
431
+ *
432
+ * @param messages An iterable or async iterable of messages to send.
433
+ * @param options Optional transport options including `AbortSignal` for
434
+ * cancellation.
435
+ * @returns An async iterable of receipts, one for each message.
436
+ */
437
+ async *sendMany(messages, options) {
438
+ options?.signal?.throwIfAborted();
439
+ const isAsyncIterable = Symbol.asyncIterator in messages;
440
+ if (isAsyncIterable) for await (const message of messages) {
441
+ options?.signal?.throwIfAborted();
442
+ yield await this.send(message, options);
443
+ }
444
+ else for (const message of messages) {
445
+ options?.signal?.throwIfAborted();
446
+ yield await this.send(message, options);
447
+ }
448
+ }
449
+ /**
450
+ * Extracts or generates a message ID from the SendGrid response.
451
+ *
452
+ * SendGrid doesn't return a message ID in the response body for successful sends,
453
+ * so we generate a synthetic ID based on timestamp and some response data.
454
+ *
455
+ * @param response The SendGrid API response.
456
+ * @returns A message ID string.
457
+ */
458
+ extractMessageId(response) {
459
+ const messageIdHeader = response.headers?.["x-message-id"] || response.headers?.["X-Message-Id"];
460
+ if (messageIdHeader) return messageIdHeader;
461
+ const timestamp = Date.now();
462
+ const random = Math.random().toString(36).substring(2, 8);
463
+ return `sendgrid-${timestamp}-${random}`;
464
+ }
465
+ };
466
+
467
+ //#endregion
468
+ exports.SendGridApiError = SendGridApiError;
469
+ exports.SendGridTransport = SendGridTransport;
470
+ exports.createSendGridConfig = createSendGridConfig;