@fmontoya/aws-ses-adapter 1.0.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.
@@ -0,0 +1,652 @@
1
+ /**
2
+ * @module types
3
+ * Core types and interfaces for the aws-ses-adapter library.
4
+ */
5
+ /**
6
+ * Configuration options for initializing the SES Adapter.
7
+ * All credential fields are optional and will fall back to the corresponding
8
+ * environment variables if not provided.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * const config: SesAdapterConfig = {
13
+ * region: 'us-east-1',
14
+ * accessKeyId: 'AKIAIOSFODNN7EXAMPLE',
15
+ * secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
16
+ * defaultFrom: 'noreply@example.com',
17
+ * };
18
+ * ```
19
+ */
20
+ interface SesAdapterConfig {
21
+ /**
22
+ * AWS region where SES is configured.
23
+ * Falls back to the `AWS_SES_REGION` environment variable if not provided.
24
+ */
25
+ region?: string;
26
+ /**
27
+ * AWS access key ID for authentication.
28
+ * Falls back to the `AWS_ACCESS_KEY_ID` environment variable if not provided.
29
+ */
30
+ accessKeyId?: string;
31
+ /**
32
+ * AWS secret access key for authentication.
33
+ * Falls back to the `AWS_SECRET_ACCESS_KEY` environment variable if not provided.
34
+ */
35
+ secretAccessKey?: string;
36
+ /**
37
+ * Default "From" email address used when no `from` is specified in {@link SendEmailOptions}.
38
+ * Falls back to the `AWS_SES_FROM_EMAIL` environment variable if not provided.
39
+ * This field is optional — emails can still provide their own `from` address.
40
+ */
41
+ defaultFrom?: string;
42
+ }
43
+ /**
44
+ * A file attachment to include in an email sent via {@link sendEmailWithAttachments}.
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * const attachment: EmailAttachment = {
49
+ * filename: 'report.pdf',
50
+ * content: fs.readFileSync('./report.pdf'),
51
+ * contentType: 'application/pdf',
52
+ * };
53
+ * ```
54
+ */
55
+ interface EmailAttachment {
56
+ /**
57
+ * The filename shown to the recipient (e.g. `'report.pdf'`).
58
+ */
59
+ filename: string;
60
+ /**
61
+ * The attachment content. Use a `Buffer` for binary files (images, PDFs, etc.)
62
+ * or a `string` for plain text files.
63
+ */
64
+ content: Buffer | string;
65
+ /**
66
+ * MIME content type of the attachment (e.g. `'application/pdf'`, `'image/png'`).
67
+ */
68
+ contentType: string;
69
+ }
70
+ /**
71
+ * Options for sending an email with attachments via SES.
72
+ * Extends {@link SendEmailOptions} with a required `attachments` array.
73
+ * At least one of `html` or `text` must be provided, plus at least one attachment.
74
+ *
75
+ * @example
76
+ * ```ts
77
+ * const options: SendEmailWithAttachmentsOptions = {
78
+ * to: 'user@example.com',
79
+ * subject: 'Your report',
80
+ * html: '<p>Please find the report attached.</p>',
81
+ * attachments: [
82
+ * { filename: 'report.pdf', content: pdfBuffer, contentType: 'application/pdf' },
83
+ * ],
84
+ * };
85
+ * ```
86
+ */
87
+ interface SendEmailWithAttachmentsOptions extends SendEmailOptions {
88
+ /**
89
+ * List of file attachments to include in the email.
90
+ * Must contain at least one item.
91
+ */
92
+ attachments: EmailAttachment[];
93
+ }
94
+ /**
95
+ * Options for sending an email via SES.
96
+ * At least one of `html` or `text` must be provided.
97
+ *
98
+ * @example
99
+ * ```ts
100
+ * const options: SendEmailOptions = {
101
+ * to: 'user@example.com',
102
+ * subject: 'Hello!',
103
+ * html: '<h1>Hello World</h1>',
104
+ * cc: ['manager@example.com'],
105
+ * };
106
+ * ```
107
+ */
108
+ interface SendEmailOptions {
109
+ /**
110
+ * Recipient email address or array of addresses.
111
+ */
112
+ to: string | string[];
113
+ /**
114
+ * Subject line of the email.
115
+ */
116
+ subject: string;
117
+ /**
118
+ * HTML body of the email.
119
+ * At least one of `html` or `text` must be provided.
120
+ */
121
+ html?: string;
122
+ /**
123
+ * Plain text body of the email.
124
+ * At least one of `html` or `text` must be provided.
125
+ */
126
+ text?: string;
127
+ /**
128
+ * Sender email address. Overrides the `defaultFrom` configured during initialization.
129
+ * Must be a verified SES identity.
130
+ */
131
+ from?: string;
132
+ /**
133
+ * Reply-To email address or array of addresses.
134
+ */
135
+ replyTo?: string | string[];
136
+ /**
137
+ * CC email address or array of addresses.
138
+ */
139
+ cc?: string | string[];
140
+ /**
141
+ * BCC email address or array of addresses.
142
+ */
143
+ bcc?: string | string[];
144
+ }
145
+ /**
146
+ * Result object returned by {@link sendEmail}, {@link sendEmailWithAttachments},
147
+ * and {@link sendRawEmail} on success.
148
+ *
149
+ * All send methods throw a typed error on failure (see {@link SesSendError},
150
+ * {@link SesValidationError}), so a returned `SendEmailResult` always represents
151
+ * a successful send.
152
+ *
153
+ * @example
154
+ * ```ts
155
+ * const result = await sendEmail(options);
156
+ * console.log('Message ID:', result.messageId);
157
+ * ```
158
+ */
159
+ interface SendEmailResult {
160
+ /**
161
+ * Always `true` for a returned result — failures are thrown as errors.
162
+ */
163
+ success: true;
164
+ /**
165
+ * The SES message ID returned by AWS.
166
+ */
167
+ messageId?: string;
168
+ }
169
+
170
+ /**
171
+ * @module adapter
172
+ * Core SesAdapter class that wraps the AWS SES client and provides
173
+ * simplified email sending methods.
174
+ */
175
+
176
+ /**
177
+ * Core adapter class that wraps the AWS SES client and provides a simplified
178
+ * API for sending emails.
179
+ *
180
+ * This class is not meant to be instantiated directly by consumers.
181
+ * Use the singleton functions exported from the main module instead.
182
+ *
183
+ * @see {@link init} to initialize the singleton.
184
+ * @see {@link sendEmail} to send a standard email.
185
+ * @see {@link sendRawEmail} to send a raw MIME email.
186
+ */
187
+ declare class SesAdapter {
188
+ /** @internal */
189
+ private readonly sesClient;
190
+ /** @internal */
191
+ private readonly config;
192
+ /**
193
+ * Creates a new SesAdapter instance.
194
+ *
195
+ * @param userConfig - Optional configuration. Missing fields fall back to environment variables.
196
+ * @throws {SesConfigError} When required configuration fields are missing.
197
+ */
198
+ constructor(userConfig?: SesAdapterConfig);
199
+ /**
200
+ * Sends an email using AWS SES.
201
+ *
202
+ * At least one of `options.html` or `options.text` must be provided.
203
+ * If `options.from` is not specified, the `defaultFrom` configured during
204
+ * initialization is used. If neither is available, the call throws.
205
+ *
206
+ * @param options - Email sending options.
207
+ * @returns A promise resolving to a {@link SendEmailResult}.
208
+ * @throws {SesValidationError} When required email fields are missing or invalid.
209
+ * @throws {SesSendError} When the AWS SES API call fails.
210
+ *
211
+ * @example
212
+ * ```ts
213
+ * const result = await adapter.sendEmail({
214
+ * to: ['alice@example.com', 'bob@example.com'],
215
+ * subject: 'Hello!',
216
+ * html: '<p>Hello World</p>',
217
+ * text: 'Hello World',
218
+ * cc: 'manager@example.com',
219
+ * });
220
+ * ```
221
+ */
222
+ sendEmail(options: SendEmailOptions): Promise<SendEmailResult>;
223
+ /**
224
+ * Sends a raw MIME email using AWS SES.
225
+ *
226
+ * Use this method when you need full control over the email format, such as
227
+ * sending emails with attachments or custom headers.
228
+ *
229
+ * @param rawMessage - The raw MIME email message as a string.
230
+ * @returns A promise resolving to a {@link SendEmailResult}.
231
+ * @throws {SesValidationError} When the raw message is empty.
232
+ * @throws {SesSendError} When the AWS SES API call fails.
233
+ *
234
+ * @example
235
+ * ```ts
236
+ * const mimeMessage = [
237
+ * 'From: sender@example.com',
238
+ * 'To: recipient@example.com',
239
+ * 'Subject: Test',
240
+ * 'MIME-Version: 1.0',
241
+ * 'Content-Type: text/plain',
242
+ * '',
243
+ * 'Hello World',
244
+ * ].join('\r\n');
245
+ *
246
+ * const result = await adapter.sendRawEmail(mimeMessage);
247
+ * ```
248
+ */
249
+ sendRawEmail(rawMessage: string): Promise<SendEmailResult>;
250
+ /**
251
+ * Sends an email with one or more file attachments using AWS SES.
252
+ *
253
+ * Internally builds a multipart/mixed MIME message and dispatches it via
254
+ * `SendRawEmailCommand`, giving you full attachment support without needing
255
+ * to craft raw MIME by hand.
256
+ *
257
+ * At least one of `options.html` or `options.text` must be provided.
258
+ * The `options.attachments` array must contain at least one item.
259
+ *
260
+ * @param options - Email options including the attachments array.
261
+ * @returns A promise resolving to a {@link SendEmailResult}.
262
+ * @throws {SesValidationError} When required fields are missing or invalid.
263
+ * @throws {SesSendError} When the AWS SES API call fails.
264
+ *
265
+ * @example
266
+ * ```ts
267
+ * const result = await adapter.sendEmailWithAttachments({
268
+ * to: 'alice@example.com',
269
+ * subject: 'Your invoice',
270
+ * html: '<p>Please find the invoice attached.</p>',
271
+ * attachments: [
272
+ * {
273
+ * filename: 'invoice.pdf',
274
+ * content: fs.readFileSync('./invoice.pdf'),
275
+ * contentType: 'application/pdf',
276
+ * },
277
+ * ],
278
+ * });
279
+ * ```
280
+ */
281
+ sendEmailWithAttachments(options: SendEmailWithAttachmentsOptions): Promise<SendEmailResult>;
282
+ /**
283
+ * Returns whether the adapter has a default "From" address configured.
284
+ *
285
+ * @returns `true` if a default from address is available.
286
+ *
287
+ * @example
288
+ * ```ts
289
+ * if (adapter.hasDefaultFrom()) {
290
+ * console.log('Default from:', adapter.getDefaultFrom());
291
+ * }
292
+ * ```
293
+ */
294
+ hasDefaultFrom(): boolean;
295
+ /**
296
+ * Returns the default "From" email address, or `undefined` if not set.
297
+ *
298
+ * @returns The default sender address, or `undefined`.
299
+ *
300
+ * @example
301
+ * ```ts
302
+ * const from = adapter.getDefaultFrom();
303
+ * // => 'noreply@example.com' or undefined
304
+ * ```
305
+ */
306
+ getDefaultFrom(): string | undefined;
307
+ /**
308
+ * Returns the AWS region the adapter is configured to use.
309
+ *
310
+ * @returns The AWS region string.
311
+ *
312
+ * @example
313
+ * ```ts
314
+ * console.log(adapter.getRegion()); // => 'us-east-1'
315
+ * ```
316
+ */
317
+ getRegion(): string;
318
+ }
319
+
320
+ /**
321
+ * @module errors
322
+ * Custom error classes for the aws-ses-adapter library.
323
+ * All errors extend the native `Error` class and include a `name` property
324
+ * suitable for programmatic error identification.
325
+ */
326
+ /**
327
+ * Thrown when an operation is attempted before the adapter has been initialized
328
+ * via {@link init}.
329
+ *
330
+ * @example
331
+ * ```ts
332
+ * import { sendEmail } from 'aws-ses-adapter';
333
+ *
334
+ * // Calling sendEmail before init() throws this error
335
+ * try {
336
+ * await sendEmail({ to: 'user@example.com', subject: 'Hi', text: 'Hello' });
337
+ * } catch (err) {
338
+ * if (err instanceof SesNotInitializedError) {
339
+ * console.error('Call init() first');
340
+ * }
341
+ * }
342
+ * ```
343
+ */
344
+ declare class SesNotInitializedError extends Error {
345
+ /** @override */
346
+ readonly name: "SesNotInitializedError";
347
+ constructor();
348
+ }
349
+ /**
350
+ * Thrown when the configuration provided to {@link init} is invalid or incomplete.
351
+ * This typically happens when required credentials are missing from both the config
352
+ * object and the environment variables.
353
+ *
354
+ * @example
355
+ * ```ts
356
+ * import { init } from 'aws-ses-adapter';
357
+ *
358
+ * try {
359
+ * init({}); // No region, no env vars set
360
+ * } catch (err) {
361
+ * if (err instanceof SesConfigError) {
362
+ * console.error('Config error:', err.message);
363
+ * }
364
+ * }
365
+ * ```
366
+ */
367
+ declare class SesConfigError extends Error {
368
+ /** @override */
369
+ readonly name: "SesConfigError";
370
+ /**
371
+ * @param message - Description of the configuration issue.
372
+ */
373
+ constructor(message: string);
374
+ }
375
+ /**
376
+ * Thrown when an email send operation fails at the AWS SES level.
377
+ * The original AWS error is available via the `cause` property (ES2022+).
378
+ *
379
+ * @example
380
+ * ```ts
381
+ * import { sendEmail, SesSendError } from 'aws-ses-adapter';
382
+ *
383
+ * try {
384
+ * await sendEmail({ to: 'user@example.com', subject: 'Hi', text: 'Hello' });
385
+ * } catch (err) {
386
+ * if (err instanceof SesSendError) {
387
+ * console.error('Send failed:', err.message);
388
+ * console.error('Original cause:', err.cause);
389
+ * }
390
+ * }
391
+ * ```
392
+ */
393
+ declare class SesSendError extends Error {
394
+ /** @override */
395
+ readonly name: "SesSendError";
396
+ /**
397
+ * @param message - Description of the send failure.
398
+ * @param cause - The underlying error from AWS SDK.
399
+ */
400
+ constructor(message: string, cause?: unknown);
401
+ }
402
+ /**
403
+ * Thrown when {@link SendEmailOptions} are invalid, such as missing both
404
+ * `html` and `text`, or having an invalid email address format.
405
+ *
406
+ * @example
407
+ * ```ts
408
+ * import { sendEmail, SesValidationError } from 'aws-ses-adapter';
409
+ *
410
+ * try {
411
+ * // Missing both html and text
412
+ * await sendEmail({ to: 'user@example.com', subject: 'Hi' });
413
+ * } catch (err) {
414
+ * if (err instanceof SesValidationError) {
415
+ * console.error('Validation error:', err.message);
416
+ * }
417
+ * }
418
+ * ```
419
+ */
420
+ declare class SesValidationError extends Error {
421
+ /** @override */
422
+ readonly name: "SesValidationError";
423
+ /**
424
+ * @param message - Description of the validation failure.
425
+ */
426
+ constructor(message: string);
427
+ }
428
+
429
+ /**
430
+ * @module aws-ses-adapter
431
+ *
432
+ * A lightweight adapter that simplifies the AWS SES email sending API for Node.js.
433
+ *
434
+ * ## Quick Start
435
+ *
436
+ * **1. Initialize once** (at application startup):
437
+ * ```ts
438
+ * import { init } from 'aws-ses-adapter';
439
+ *
440
+ * init({
441
+ * region: 'us-east-1',
442
+ * accessKeyId: 'YOUR_KEY',
443
+ * secretAccessKey: 'YOUR_SECRET',
444
+ * defaultFrom: 'noreply@example.com',
445
+ * });
446
+ * ```
447
+ *
448
+ * **2. Use anywhere** in your application:
449
+ * ```ts
450
+ * import { sendEmail } from 'aws-ses-adapter';
451
+ *
452
+ * await sendEmail({
453
+ * to: 'user@example.com',
454
+ * subject: 'Welcome!',
455
+ * html: '<h1>Welcome</h1>',
456
+ * });
457
+ * ```
458
+ *
459
+ * ## Environment Variables
460
+ *
461
+ * If credentials are not passed to `init()`, the adapter reads:
462
+ * - `AWS_SES_REGION`
463
+ * - `AWS_ACCESS_KEY_ID`
464
+ * - `AWS_SECRET_ACCESS_KEY`
465
+ * - `AWS_SES_FROM_EMAIL` (optional default sender)
466
+ */
467
+
468
+ /**
469
+ * Initializes the SES Adapter singleton.
470
+ *
471
+ * Must be called **once** before any other function in this module.
472
+ * Calling `init()` again will replace the existing singleton instance,
473
+ * which is useful for reconfiguration during testing.
474
+ *
475
+ * Credentials are resolved in the following order:
476
+ * 1. Values provided in the `config` argument.
477
+ * 2. Environment variables (`AWS_SES_REGION`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`).
478
+ *
479
+ * @param config - Optional configuration. Omit any field to fall back to environment variables.
480
+ * @throws {SesConfigError} When required credentials cannot be resolved.
481
+ *
482
+ * @example
483
+ * ```ts
484
+ * // Using explicit credentials
485
+ * init({
486
+ * region: 'us-east-1',
487
+ * accessKeyId: process.env.MY_KEY_ID,
488
+ * secretAccessKey: process.env.MY_SECRET,
489
+ * defaultFrom: 'no-reply@myapp.com',
490
+ * });
491
+ *
492
+ * // Relying entirely on environment variables
493
+ * init();
494
+ * ```
495
+ */
496
+ declare function init(config?: SesAdapterConfig): void;
497
+ /**
498
+ * Sends an email using the initialized SES Adapter.
499
+ *
500
+ * At least one of `options.html` or `options.text` must be provided.
501
+ * If `options.from` is not specified, the `defaultFrom` set during {@link init} is used.
502
+ *
503
+ * @param options - Email sending options.
504
+ * @returns A promise resolving to a {@link SendEmailResult}.
505
+ * @throws {SesNotInitializedError} If {@link init} has not been called.
506
+ * @throws {SesValidationError} When required email fields are missing or invalid.
507
+ * @throws {SesSendError} When the AWS SES API call fails.
508
+ *
509
+ * @example
510
+ * ```ts
511
+ * import { sendEmail } from 'aws-ses-adapter';
512
+ *
513
+ * const result = await sendEmail({
514
+ * to: 'alice@example.com',
515
+ * subject: 'Hello Alice',
516
+ * html: '<p>Hi Alice!</p>',
517
+ * text: 'Hi Alice!',
518
+ * cc: 'manager@example.com',
519
+ * bcc: ['audit@example.com'],
520
+ * replyTo: 'support@example.com',
521
+ * });
522
+ *
523
+ * console.log(result.messageId);
524
+ * ```
525
+ */
526
+ declare function sendEmail(options: SendEmailOptions): Promise<SendEmailResult>;
527
+ /**
528
+ * Sends an email with one or more file attachments using the initialized SES Adapter.
529
+ *
530
+ * Internally builds a multipart/mixed MIME message, so you don't need to
531
+ * construct raw MIME yourself. At least one of `options.html` or `options.text`
532
+ * must be provided, and `options.attachments` must contain at least one item.
533
+ *
534
+ * @param options - Email options including the attachments array.
535
+ * @returns A promise resolving to a {@link SendEmailResult}.
536
+ * @throws {SesNotInitializedError} If {@link init} has not been called.
537
+ * @throws {SesValidationError} When required fields are missing or invalid.
538
+ * @throws {SesSendError} When the AWS SES API call fails.
539
+ *
540
+ * @example
541
+ * ```ts
542
+ * import { sendEmailWithAttachments } from 'aws-ses-adapter';
543
+ * import { readFileSync } from 'fs';
544
+ *
545
+ * const result = await sendEmailWithAttachments({
546
+ * to: 'alice@example.com',
547
+ * subject: 'Your invoice',
548
+ * html: '<p>Please find the invoice attached.</p>',
549
+ * attachments: [
550
+ * {
551
+ * filename: 'invoice.pdf',
552
+ * content: readFileSync('./invoice.pdf'),
553
+ * contentType: 'application/pdf',
554
+ * },
555
+ * ],
556
+ * });
557
+ *
558
+ * console.log(result.messageId);
559
+ * ```
560
+ */
561
+ declare function sendEmailWithAttachments(options: SendEmailWithAttachmentsOptions): Promise<SendEmailResult>;
562
+ /**
563
+ * Sends a raw MIME email using the initialized SES Adapter.
564
+ *
565
+ * Use this when you need full control over the email, such as including
566
+ * attachments or custom MIME headers.
567
+ *
568
+ * @param rawMessage - The raw MIME email message as a string.
569
+ * @returns A promise resolving to a {@link SendEmailResult}.
570
+ * @throws {SesNotInitializedError} If {@link init} has not been called.
571
+ * @throws {SesValidationError} When the raw message is empty.
572
+ * @throws {SesSendError} When the AWS SES API call fails.
573
+ *
574
+ * @example
575
+ * ```ts
576
+ * import { sendRawEmail } from 'aws-ses-adapter';
577
+ *
578
+ * const mime = [
579
+ * 'From: sender@example.com',
580
+ * 'To: recipient@example.com',
581
+ * 'Subject: File attached',
582
+ * 'MIME-Version: 1.0',
583
+ * 'Content-Type: text/plain',
584
+ * '',
585
+ * 'Please find the attachment.',
586
+ * ].join('\r\n');
587
+ *
588
+ * const result = await sendRawEmail(mime);
589
+ * ```
590
+ */
591
+ declare function sendRawEmail(rawMessage: string): Promise<SendEmailResult>;
592
+ /**
593
+ * Returns whether the singleton has been initialized via {@link init}.
594
+ *
595
+ * @returns `true` if `init()` has been called successfully.
596
+ *
597
+ * @example
598
+ * ```ts
599
+ * import { isInitialized } from 'aws-ses-adapter';
600
+ *
601
+ * if (!isInitialized()) {
602
+ * init();
603
+ * }
604
+ * ```
605
+ */
606
+ declare function isInitialized(): boolean;
607
+ /**
608
+ * Returns whether a default "From" address is configured in the singleton.
609
+ *
610
+ * @returns `true` if a default sender address is set.
611
+ * @throws {SesNotInitializedError} If {@link init} has not been called.
612
+ *
613
+ * @example
614
+ * ```ts
615
+ * import { hasDefaultFrom } from 'aws-ses-adapter';
616
+ *
617
+ * console.log(hasDefaultFrom()); // => true
618
+ * ```
619
+ */
620
+ declare function hasDefaultFrom(): boolean;
621
+ /**
622
+ * Returns the default "From" email address configured in the singleton,
623
+ * or `undefined` if none was set.
624
+ *
625
+ * @returns The default sender address, or `undefined`.
626
+ * @throws {SesNotInitializedError} If {@link init} has not been called.
627
+ *
628
+ * @example
629
+ * ```ts
630
+ * import { getDefaultFrom } from 'aws-ses-adapter';
631
+ *
632
+ * const from = getDefaultFrom();
633
+ * // => 'noreply@example.com' or undefined
634
+ * ```
635
+ */
636
+ declare function getDefaultFrom(): string | undefined;
637
+ /**
638
+ * Returns the AWS region the singleton is configured to use.
639
+ *
640
+ * @returns The AWS region string (e.g. `'us-east-1'`).
641
+ * @throws {SesNotInitializedError} If {@link init} has not been called.
642
+ *
643
+ * @example
644
+ * ```ts
645
+ * import { getRegion } from 'aws-ses-adapter';
646
+ *
647
+ * console.log(getRegion()); // => 'us-east-1'
648
+ * ```
649
+ */
650
+ declare function getRegion(): string;
651
+
652
+ export { type EmailAttachment, type SendEmailOptions, type SendEmailResult, type SendEmailWithAttachmentsOptions, SesAdapter, type SesAdapterConfig, SesConfigError, SesNotInitializedError, SesSendError, SesValidationError, getDefaultFrom, getRegion, hasDefaultFrom, init, isInitialized, sendEmail, sendEmailWithAttachments, sendRawEmail };