@fmontoya/aws-ses-adapter 1.0.0 → 1.2.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/dist/index.js CHANGED
@@ -58,8 +58,8 @@ var SesValidationError = class extends Error {
58
58
  // src/adapter.ts
59
59
  function resolveConfig(config = {}) {
60
60
  const region = config.region ?? process.env["AWS_SES_REGION"];
61
- const accessKeyId = config.accessKeyId ?? process.env["AWS_ACCESS_KEY_ID"];
62
- const secretAccessKey = config.secretAccessKey ?? process.env["AWS_SECRET_ACCESS_KEY"];
61
+ const accessKeyId = config.credentials?.accessKeyId ?? config.accessKeyId ?? process.env["AWS_ACCESS_KEY_ID"];
62
+ const secretAccessKey = config.credentials?.secretAccessKey ?? config.secretAccessKey ?? process.env["AWS_SECRET_ACCESS_KEY"];
63
63
  const defaultFrom = config.defaultFrom ?? process.env["AWS_SES_FROM_EMAIL"];
64
64
  if (!region) {
65
65
  throw new SesConfigError(
@@ -68,12 +68,12 @@ function resolveConfig(config = {}) {
68
68
  }
69
69
  if (!accessKeyId) {
70
70
  throw new SesConfigError(
71
- "AWS access key ID is required. Provide it via config.accessKeyId or the AWS_ACCESS_KEY_ID environment variable."
71
+ "AWS access key ID is required. Provide it via config.credentials.accessKeyId, or the AWS_ACCESS_KEY_ID environment variable."
72
72
  );
73
73
  }
74
74
  if (!secretAccessKey) {
75
75
  throw new SesConfigError(
76
- "AWS secret access key is required. Provide it via config.secretAccessKey or the AWS_SECRET_ACCESS_KEY environment variable."
76
+ "AWS secret access key is required. Provide it via config.credentials.secretAccessKey, or the AWS_SECRET_ACCESS_KEY environment variable."
77
77
  );
78
78
  }
79
79
  return { region, accessKeyId, secretAccessKey, defaultFrom };
@@ -165,6 +165,69 @@ var SesAdapter = class {
165
165
  this.config = resolveConfig(userConfig);
166
166
  this.sesClient = buildSesClient(this.config);
167
167
  }
168
+ /**
169
+ * Validates that at least one body content field (`html` or `text`) is provided.
170
+ *
171
+ * @param options - Object containing optional `html` and `text` fields.
172
+ * @throws {SesValidationError} When neither field is present.
173
+ *
174
+ * @internal
175
+ */
176
+ validateBodyOptions(options) {
177
+ if (!options.html && !options.text) {
178
+ throw new SesValidationError(
179
+ 'At least one of "html" or "text" must be provided.'
180
+ );
181
+ }
182
+ }
183
+ /**
184
+ * Resolves the sender address from the per-call option or the adapter default.
185
+ *
186
+ * @param from - The per-call "from" address, if provided.
187
+ * @returns The resolved sender address.
188
+ * @throws {SesValidationError} When no sender address can be determined.
189
+ *
190
+ * @internal
191
+ */
192
+ resolveFrom(from) {
193
+ const resolved = from ?? this.config.defaultFrom;
194
+ if (!resolved) {
195
+ throw new SesValidationError(
196
+ 'A sender address is required. Provide "from" in the options or set "defaultFrom" during init().'
197
+ );
198
+ }
199
+ return resolved;
200
+ }
201
+ /**
202
+ * Dispatches a raw MIME message via `SendRawEmailCommand`.
203
+ *
204
+ * @param rawMessage - The raw MIME string to send.
205
+ * @param errorContext - Human-readable context prepended to error messages.
206
+ * @returns A promise resolving to a {@link SendEmailResult}.
207
+ * @throws {SesSendError} When the AWS SES API call fails.
208
+ *
209
+ * @internal
210
+ */
211
+ async dispatchRawEmail(rawMessage, errorContext) {
212
+ const params = {
213
+ RawMessage: {
214
+ Data: Buffer.from(rawMessage)
215
+ }
216
+ };
217
+ try {
218
+ const command = new clientSes.SendRawEmailCommand(params);
219
+ const response = await this.sesClient.send(command);
220
+ return {
221
+ success: true,
222
+ messageId: response.MessageId
223
+ };
224
+ } catch (error) {
225
+ throw new SesSendError(
226
+ `${errorContext}: ${error instanceof Error ? error.message : String(error)}`,
227
+ error
228
+ );
229
+ }
230
+ }
168
231
  /**
169
232
  * Sends an email using AWS SES.
170
233
  *
@@ -189,17 +252,8 @@ var SesAdapter = class {
189
252
  * ```
190
253
  */
191
254
  async sendEmail(options) {
192
- if (!options.html && !options.text) {
193
- throw new SesValidationError(
194
- 'At least one of "html" or "text" must be provided in SendEmailOptions.'
195
- );
196
- }
197
- const from = options.from ?? this.config.defaultFrom;
198
- if (!from) {
199
- throw new SesValidationError(
200
- 'A sender address is required. Provide "from" in SendEmailOptions or set "defaultFrom" during init().'
201
- );
202
- }
255
+ this.validateBodyOptions(options);
256
+ const from = this.resolveFrom(options.from);
203
257
  const toAddresses = toArray(options.to);
204
258
  const params = {
205
259
  Source: from,
@@ -264,24 +318,7 @@ var SesAdapter = class {
264
318
  if (!rawMessage || rawMessage.trim().length === 0) {
265
319
  throw new SesValidationError("rawMessage cannot be empty.");
266
320
  }
267
- const params = {
268
- RawMessage: {
269
- Data: Buffer.from(rawMessage)
270
- }
271
- };
272
- try {
273
- const command = new clientSes.SendRawEmailCommand(params);
274
- const response = await this.sesClient.send(command);
275
- return {
276
- success: true,
277
- messageId: response.MessageId
278
- };
279
- } catch (error) {
280
- throw new SesSendError(
281
- `Failed to send raw email: ${error instanceof Error ? error.message : String(error)}`,
282
- error
283
- );
284
- }
321
+ return this.dispatchRawEmail(rawMessage, "Failed to send raw email");
285
322
  }
286
323
  /**
287
324
  * Sends an email with one or more file attachments using AWS SES.
@@ -315,42 +352,19 @@ var SesAdapter = class {
315
352
  * ```
316
353
  */
317
354
  async sendEmailWithAttachments(options) {
318
- if (!options.html && !options.text) {
319
- throw new SesValidationError(
320
- 'At least one of "html" or "text" must be provided in SendEmailWithAttachmentsOptions.'
321
- );
322
- }
355
+ this.validateBodyOptions(options);
323
356
  if (!options.attachments || options.attachments.length === 0) {
324
357
  throw new SesValidationError(
325
358
  "At least one attachment must be provided in SendEmailWithAttachmentsOptions.attachments."
326
359
  );
327
360
  }
328
- const from = options.from ?? this.config.defaultFrom;
329
- if (!from) {
330
- throw new SesValidationError(
331
- 'A sender address is required. Provide "from" in SendEmailWithAttachmentsOptions or set "defaultFrom" during init().'
332
- );
333
- }
334
- const rawMessage = buildMimeMessage(options, from);
361
+ const from = this.resolveFrom(options.from);
335
362
  const toAddresses = toArray(options.to);
336
- const params = {
337
- RawMessage: {
338
- Data: Buffer.from(rawMessage)
339
- }
340
- };
341
- try {
342
- const command = new clientSes.SendRawEmailCommand(params);
343
- const response = await this.sesClient.send(command);
344
- return {
345
- success: true,
346
- messageId: response.MessageId
347
- };
348
- } catch (error) {
349
- throw new SesSendError(
350
- `Failed to send email with attachments to ${toAddresses.join(", ")}: ${error instanceof Error ? error.message : String(error)}`,
351
- error
352
- );
353
- }
363
+ const rawMessage = buildMimeMessage(options, from);
364
+ return this.dispatchRawEmail(
365
+ rawMessage,
366
+ `Failed to send email with attachments to ${toAddresses.join(", ")}`
367
+ );
354
368
  }
355
369
  /**
356
370
  * Returns whether the adapter has a default "From" address configured.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/errors.ts","../src/adapter.ts","../src/index.ts"],"names":["SESClient","SendEmailCommand","SendRawEmailCommand"],"mappings":";;;;;AA2BO,SAAS,eAAe,MAAA,EAA6C;AAC1E,EAAA,OAAO,IAAIA,mBAAA,CAAU;AAAA,IACnB,QAAQ,MAAA,CAAO,MAAA;AAAA,IACf,WAAA,EAAa;AAAA,MACX,aAAa,MAAA,CAAO,WAAA;AAAA,MACpB,iBAAiB,MAAA,CAAO;AAAA;AAC1B,GACD,CAAA;AACH;;;ACVO,IAAM,sBAAA,GAAN,cAAqC,KAAA,CAAM;AAAA,EAIhD,WAAA,GAAc;AACZ,IAAA,KAAA;AAAA,MACE;AAAA,KACF;AALF;AAAA,IAAA,IAAA,CAAS,IAAA,GAAO,wBAAA;AAAA,EAMhB;AACF;AAoBO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA;AAAA;AAAA;AAAA,EAOxC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AANf;AAAA,IAAA,IAAA,CAAS,IAAA,GAAO,gBAAA;AAAA,EAOhB;AACF;AAoBO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA;AAAA;AAAA;AAAA;AAAA,EAQtC,WAAA,CAAY,SAAiB,K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AI,WAAW,MAAM,CAAA;AACnC;AA+BA,eAAsB,UACpB,OAAA,EAC0B;AAC1B,EAAA,OAAO,WAAA,EAAY,CAAE,SAAA,CAAU,OAAO,CAAA;AACxC;AAoCA,eAAsB,yBACpB,OAAA,EAC0B;AAC1B,EAAA,OAAO,WAAA,EAAY,CAAE,wBAAA,CAAyB,OAAO,CAAA;AACvD;AA+BA,eAAsB,aACpB,UAAA,EAC0B;AAC1B,EAAA,OAAO,WAAA,EAAY,CAAE,YAAA,CAAa,UAAU,CAAA;AAC9C;AAgBO,SAAS,aAAA,GAAyB;AACvC,EAAA,OAAO,SAAA,KAAc,IAAA;AACvB;AAeO,SAAS,cAAA,GAA0B;AACxC,EAAA,OAAO,WAAA,GAAc,cAAA,EAAe;AACtC;AAiBO,SAAS,cAAA,GAAqC;AACnD,EAAA,OAAO,WAAA,GAAc,cAAA,EAAe;AACtC;AAeO,SAAS,SAAA,GAAoB;AAClC,EAAA,OAAO,WAAA,GAAc,SAAA,EAAU;AACjC","file":"index.js","sourcesContent":["/**\n * @module client\n * Factory and utilities for building an AWS SESClient instance\n * from a resolved adapter configuration.\n */\n\nimport { SESClient } from '@aws-sdk/client-ses';\nimport type { ResolvedSesAdapterConfig } from './types.js';\n\n/**\n * Creates and returns a configured {@link SESClient} instance using the\n * resolved adapter configuration.\n *\n * @param config - The resolved configuration containing region and credentials.\n * @returns A ready-to-use AWS SESClient.\n *\n * @example\n * ```ts\n * const client = buildSesClient({\n * region: 'us-east-1',\n * accessKeyId: 'AKIAIOSFODNN7EXAMPLE',\n * secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',\n * });\n * ```\n *\n * @internal\n */\nexport function buildSesClient(config: ResolvedSesAdapterConfig): SESClient {\n return new SESClient({\n region: config.region,\n credentials: {\n accessKeyId: config.accessKeyId,\n secretAccessKey: config.secretAccessKey,\n },\n });\n}\n","/**\n * @module errors\n * Custom error classes for the aws-ses-adapter library.\n * All errors extend the native `Error` class and include a `name` property\n * suitable for programmatic error identification.\n */\n\n/**\n * Thrown when an operation is attempted before the adapter has been initialized\n * via {@link init}.\n *\n * @example\n * ```ts\n * import { sendEmail } from 'aws-ses-adapter';\n *\n * // Calling sendEmail before init() throws this error\n * try {\n * await sendEmail({ to: 'user@example.com', subject: 'Hi', text: 'Hello' });\n * } catch (err) {\n * if (err instanceof SesNotInitializedError) {\n * console.error('Call init() first');\n * }\n * }\n * ```\n */\nexport class SesNotInitializedError extends Error {\n /** @override */\n readonly name = 'SesNotInitializedError' as const;\n\n constructor() {\n super(\n 'SES Adapter has not been initialized. Call init() before using any adapter methods.',\n );\n }\n}\n\n/**\n * Thrown when the configuration provided to {@link init} is invalid or incomplete.\n * This typically happens when required credentials are missing from both the config\n * object and the environment variables.\n *\n * @example\n * ```ts\n * import { init } from 'aws-ses-adapter';\n *\n * try {\n * init({}); // No region, no env vars set\n * } catch (err) {\n * if (err instanceof SesConfigError) {\n * console.error('Config error:', err.message);\n * }\n * }\n * ```\n */\nexport class SesConfigError extends Error {\n /** @override */\n readonly name = 'SesConfigError' as const;\n\n /**\n * @param message - Description of the configuration issue.\n */\n constructor(message: string) {\n super(message);\n }\n}\n\n/**\n * Thrown when an email send operation fails at the AWS SES level.\n * The original AWS error is available via the `cause` property (ES2022+).\n *\n * @example\n * ```ts\n * import { sendEmail, SesSendError } from 'aws-ses-adapter';\n *\n * try {\n * await sendEmail({ to: 'user@example.com', subject: 'Hi', text: 'Hello' });\n * } catch (err) {\n * if (err instanceof SesSendError) {\n * console.error('Send failed:', err.message);\n * console.error('Original cause:', err.cause);\n * }\n * }\n * ```\n */\nexport class SesSendError extends Error {\n /** @override */\n readonly name = 'SesSendError' as const;\n\n /**\n * @param message - Description of the send failure.\n * @param cause - The underlying error from AWS SDK.\n */\n constructor(message: string, cause?: unknown) {\n super(message, { cause });\n }\n}\n\n/**\n * Thrown when {@link SendEmailOptions} are invalid, such as missing both\n * `html` and `text`, or having an invalid email address format.\n *\n * @example\n * ```ts\n * import { sendEmail, SesValidationError } from 'aws-ses-adapter';\n *\n * try {\n * // Missing both html and text\n * await sendEmail({ to: 'user@example.com', subject: 'Hi' });\n * } catch (err) {\n * if (err instanceof SesValidationError) {\n * console.error('Validation error:', err.message);\n * }\n * }\n * ```\n */\nexport class SesValidationError extends Error {\n /** @override */\n readonly name = 'SesValidationError' as const;\n\n /**\n * @param message - Description of the validation failure.\n */\n constructor(message: string) {\n super(message);\n }\n}\n","/**\n * @module adapter\n * Core SesAdapter class that wraps the AWS SES client and provides\n * simplified email sending methods.\n */\n\nimport type {\n SendEmailCommandInput,\n SendRawEmailCommandInput,\n SESClient,\n} from '@aws-sdk/client-ses';\nimport { SendEmailCommand, SendRawEmailCommand } from '@aws-sdk/client-ses';\nimport { buildSesClient } from './client.js';\nimport { SesConfigError, SesSendError, SesValidationError } from './errors.js';\nimport type {\n EmailAttachment,\n ResolvedSesAdapterConfig,\n SendEmailOptions,\n SendEmailResult,\n SendEmailWithAttachmentsOptions,\n SesAdapterConfig,\n} from './types.js';\n\n/**\n * Resolves the adapter configuration by merging user-provided values with\n * environment variable fallbacks.\n *\n * @param config - Optional user-provided configuration.\n * @returns The resolved configuration with all required fields populated.\n * @throws {SesConfigError} When required fields cannot be resolved from config or env vars.\n *\n * @internal\n */\nfunction resolveConfig(\n config: SesAdapterConfig = {},\n): ResolvedSesAdapterConfig {\n const region = config.region ?? process.env['AWS_SES_REGION'];\n const accessKeyId = config.accessKeyId ?? process.env['AWS_ACCESS_KEY_ID'];\n const secretAccessKey =\n config.secretAccessKey ?? process.env['AWS_SECRET_ACCESS_KEY'];\n const defaultFrom = config.defaultFrom ?? process.env['AWS_SES_FROM_EMAIL'];\n\n if (!region) {\n throw new SesConfigError(\n 'AWS SES region is required. Provide it via config.region or the AWS_SES_REGION environment variable.',\n );\n }\n if (!accessKeyId) {\n throw new SesConfigError(\n 'AWS access key ID is required. Provide it via config.accessKeyId or the AWS_ACCESS_KEY_ID environment variable.',\n );\n }\n if (!secretAccessKey) {\n throw new SesConfigError(\n 'AWS secret access key is required. Provide it via config.secretAccessKey or the AWS_SECRET_ACCESS_KEY environment variable.',\n );\n }\n\n return { region, accessKeyId, secretAccessKey, defaultFrom };\n}\n\n/**\n * Normalizes a value that can be a single string or an array of strings\n * into a guaranteed array.\n *\n * @param value - A string or array of strings.\n * @returns An array of strings.\n *\n * @internal\n */\nfunction toArray(value: string | string[]): string[] {\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Encodes a MIME header value using RFC 2047 Base64 encoded-word syntax\n * when the value contains non-ASCII characters.\n *\n * @param value - The raw header value (e.g. a subject line).\n * @returns The value as-is if it is pure ASCII, otherwise `=?UTF-8?B?...?=`.\n *\n * @internal\n */\nfunction encodeHeaderValue(value: string): string {\n // If no non-ASCII characters are present, return as-is\n if (!/[\\u0080-\\uFFFF]/.test(value)) return value;\n return `=?UTF-8?B?${Buffer.from(value, 'utf-8').toString('base64')}?=`;\n}\n\n/**\n * Builds a multipart/mixed MIME email message ready to be sent via\n * `SendRawEmailCommand`.\n *\n * The body section uses multipart/alternative when both `html` and `text` are\n * supplied so that email clients can choose the best representation.\n *\n * @internal\n */\nfunction buildMimeMessage(\n options: SendEmailWithAttachmentsOptions,\n from: string,\n): string {\n const mixedBoundary = `----=_Mixed_${Date.now()}_${Math.random().toString(36).slice(2)}`;\n const altBoundary = `----=_Alt_${Date.now()}_${Math.random().toString(36).slice(2)}`;\n\n const lines: string[] = [];\n\n // RFC 2822 headers\n lines.push(`From: ${from}`);\n lines.push(`To: ${toArray(options.to).join(', ')}`);\n if (options.cc) lines.push(`Cc: ${toArray(options.cc).join(', ')}`);\n if (options.bcc) lines.push(`Bcc: ${toArray(options.bcc).join(', ')}`);\n if (options.replyTo)\n lines.push(`Reply-To: ${toArray(options.replyTo).join(', ')}`);\n lines.push(`Subject: ${encodeHeaderValue(options.subject)}`);\n lines.push('MIME-Version: 1.0');\n lines.push(`Content-Type: multipart/mixed; boundary=\"${mixedBoundary}\"`);\n lines.push('');\n\n // ── Body part ────────────────────────────────────────────────────────────\n if (options.html && options.text) {\n // Both formats: wrap in multipart/alternative\n lines.push(`--${mixedBoundary}`);\n lines.push(\n `Content-Type: multipart/alternative; boundary=\"${altBoundary}\"`,\n );\n lines.push('');\n\n lines.push(`--${altBoundary}`);\n lines.push('Content-Type: text/plain; charset=UTF-8');\n lines.push('Content-Transfer-Encoding: 8bit');\n lines.push('');\n lines.push(options.text);\n lines.push('');\n\n lines.push(`--${altBoundary}`);\n lines.push('Content-Type: text/html; charset=UTF-8');\n lines.push('Content-Transfer-Encoding: 8bit');\n lines.push('');\n lines.push(options.html);\n lines.push('');\n\n lines.push(`--${altBoundary}--`);\n lines.push('');\n } else if (options.html) {\n lines.push(`--${mixedBoundary}`);\n lines.push('Content-Type: text/html; charset=UTF-8');\n lines.push('Content-Transfer-Encoding: 8bit');\n lines.push('');\n lines.push(options.html);\n lines.push('');\n } else if (options.text) {\n lines.push(`--${mixedBoundary}`);\n lines.push('Content-Type: text/plain; charset=UTF-8');\n lines.push('Content-Transfer-Encoding: 8bit');\n lines.push('');\n lines.push(options.text);\n lines.push('');\n }\n\n // ── Attachment parts ─────────────────────────────────────────────────────\n for (const attachment of options.attachments) {\n const encoded = encodeAttachment(attachment);\n const safeName = attachment.filename.replace(/\"/g, '');\n\n lines.push(`--${mixedBoundary}`);\n lines.push(`Content-Type: ${attachment.contentType}; name=\"${safeName}\"`);\n lines.push('Content-Transfer-Encoding: base64');\n lines.push(`Content-Disposition: attachment; filename=\"${safeName}\"`);\n lines.push('');\n // RFC 2045: base64 lines must not exceed 76 characters\n lines.push(encoded.match(/.{1,76}/g)?.join('\\r\\n') ?? encoded);\n lines.push('');\n }\n\n lines.push(`--${mixedBoundary}--`);\n\n return lines.join('\\r\\n');\n}\n\n/**\n * Encodes an attachment's content as a base64 string.\n *\n * @param attachment - The attachment to encode.\n * @returns Base64-encoded string.\n *\n * @internal\n */\nfunction encodeAttachment(attachment: EmailAttachment): string {\n if (Buffer.isBuffer(attachment.content)) {\n return attachment.content.toString('base64');\n }\n return Buffer.from(attachment.content).toString('base64');\n}\n\n/**\n * Core adapter class that wraps the AWS SES client and provides a simplified\n * API for sending emails.\n *\n * This class is not meant to be instantiated directly by consumers.\n * Use the singleton functions exported from the main module instead.\n *\n * @see {@link init} to initialize the singleton.\n * @see {@link sendEmail} to send a standard email.\n * @see {@link sendRawEmail} to send a raw MIME email.\n */\nexport class SesAdapter {\n /** @internal */\n private readonly sesClient: SESClient;\n\n /** @internal */\n private readonly config: ResolvedSesAdapterConfig;\n\n /**\n * Creates a new SesAdapter instance.\n *\n * @param userConfig - Optional configuration. Missing fields fall back to environment variables.\n * @throws {SesConfigError} When required configuration fields are missing.\n */\n constructor(userConfig: SesAdapterConfig = {}) {\n this.config = resolveConfig(userConfig);\n this.sesClient = buildSesClient(this.config);\n }\n\n /**\n * Sends an email using AWS SES.\n *\n * At least one of `options.html` or `options.text` must be provided.\n * If `options.from` is not specified, the `defaultFrom` configured during\n * initialization is used. If neither is available, the call throws.\n *\n * @param options - Email sending options.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesValidationError} When required email fields are missing or invalid.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * const result = await adapter.sendEmail({\n * to: ['alice@example.com', 'bob@example.com'],\n * subject: 'Hello!',\n * html: '<p>Hello World</p>',\n * text: 'Hello World',\n * cc: 'manager@example.com',\n * });\n * ```\n */\n async sendEmail(options: SendEmailOptions): Promise<SendEmailResult> {\n if (!options.html && !options.text) {\n throw new SesValidationError(\n 'At least one of \"html\" or \"text\" must be provided in SendEmailOptions.',\n );\n }\n\n const from = options.from ?? this.config.defaultFrom;\n if (!from) {\n throw new SesValidationError(\n 'A sender address is required. Provide \"from\" in SendEmailOptions or set \"defaultFrom\" during init().',\n );\n }\n\n const toAddresses = toArray(options.to);\n\n const params: SendEmailCommandInput = {\n Source: from,\n Destination: {\n ToAddresses: toAddresses,\n CcAddresses: options.cc ? toArray(options.cc) : undefined,\n BccAddresses: options.bcc ? toArray(options.bcc) : undefined,\n },\n Message: {\n Subject: {\n Data: options.subject,\n Charset: 'UTF-8',\n },\n Body: {\n Html: options.html\n ? { Data: options.html, Charset: 'UTF-8' }\n : undefined,\n Text: options.text\n ? { Data: options.text, Charset: 'UTF-8' }\n : undefined,\n },\n },\n ReplyToAddresses: options.replyTo ? toArray(options.replyTo) : undefined,\n };\n\n try {\n const command = new SendEmailCommand(params);\n const response = await this.sesClient.send(command);\n\n return {\n success: true,\n messageId: response.MessageId,\n };\n } catch (error) {\n throw new SesSendError(\n `Failed to send email to ${toAddresses.join(', ')}: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n }\n\n /**\n * Sends a raw MIME email using AWS SES.\n *\n * Use this method when you need full control over the email format, such as\n * sending emails with attachments or custom headers.\n *\n * @param rawMessage - The raw MIME email message as a string.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesValidationError} When the raw message is empty.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * const mimeMessage = [\n * 'From: sender@example.com',\n * 'To: recipient@example.com',\n * 'Subject: Test',\n * 'MIME-Version: 1.0',\n * 'Content-Type: text/plain',\n * '',\n * 'Hello World',\n * ].join('\\r\\n');\n *\n * const result = await adapter.sendRawEmail(mimeMessage);\n * ```\n */\n async sendRawEmail(rawMessage: string): Promise<SendEmailResult> {\n if (!rawMessage || rawMessage.trim().length === 0) {\n throw new SesValidationError('rawMessage cannot be empty.');\n }\n\n const params: SendRawEmailCommandInput = {\n RawMessage: {\n Data: Buffer.from(rawMessage),\n },\n };\n\n try {\n const command = new SendRawEmailCommand(params);\n const response = await this.sesClient.send(command);\n\n return {\n success: true,\n messageId: response.MessageId,\n };\n } catch (error) {\n throw new SesSendError(\n `Failed to send raw email: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n }\n\n /**\n * Sends an email with one or more file attachments using AWS SES.\n *\n * Internally builds a multipart/mixed MIME message and dispatches it via\n * `SendRawEmailCommand`, giving you full attachment support without needing\n * to craft raw MIME by hand.\n *\n * At least one of `options.html` or `options.text` must be provided.\n * The `options.attachments` array must contain at least one item.\n *\n * @param options - Email options including the attachments array.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesValidationError} When required fields are missing or invalid.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * const result = await adapter.sendEmailWithAttachments({\n * to: 'alice@example.com',\n * subject: 'Your invoice',\n * html: '<p>Please find the invoice attached.</p>',\n * attachments: [\n * {\n * filename: 'invoice.pdf',\n * content: fs.readFileSync('./invoice.pdf'),\n * contentType: 'application/pdf',\n * },\n * ],\n * });\n * ```\n */\n async sendEmailWithAttachments(\n options: SendEmailWithAttachmentsOptions,\n ): Promise<SendEmailResult> {\n if (!options.html && !options.text) {\n throw new SesValidationError(\n 'At least one of \"html\" or \"text\" must be provided in SendEmailWithAttachmentsOptions.',\n );\n }\n\n if (!options.attachments || options.attachments.length === 0) {\n throw new SesValidationError(\n 'At least one attachment must be provided in SendEmailWithAttachmentsOptions.attachments.',\n );\n }\n\n const from = options.from ?? this.config.defaultFrom;\n if (!from) {\n throw new SesValidationError(\n 'A sender address is required. Provide \"from\" in SendEmailWithAttachmentsOptions or set \"defaultFrom\" during init().',\n );\n }\n\n const rawMessage = buildMimeMessage(options, from);\n const toAddresses = toArray(options.to);\n\n const params: SendRawEmailCommandInput = {\n RawMessage: {\n Data: Buffer.from(rawMessage),\n },\n };\n\n try {\n const command = new SendRawEmailCommand(params);\n const response = await this.sesClient.send(command);\n\n return {\n success: true,\n messageId: response.MessageId,\n };\n } catch (error) {\n throw new SesSendError(\n `Failed to send email with attachments to ${toAddresses.join(', ')}: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n }\n\n /**\n * Returns whether the adapter has a default \"From\" address configured.\n *\n * @returns `true` if a default from address is available.\n *\n * @example\n * ```ts\n * if (adapter.hasDefaultFrom()) {\n * console.log('Default from:', adapter.getDefaultFrom());\n * }\n * ```\n */\n hasDefaultFrom(): boolean {\n return !!this.config.defaultFrom;\n }\n\n /**\n * Returns the default \"From\" email address, or `undefined` if not set.\n *\n * @returns The default sender address, or `undefined`.\n *\n * @example\n * ```ts\n * const from = adapter.getDefaultFrom();\n * // => 'noreply@example.com' or undefined\n * ```\n */\n getDefaultFrom(): string | undefined {\n return this.config.defaultFrom;\n }\n\n /**\n * Returns the AWS region the adapter is configured to use.\n *\n * @returns The AWS region string.\n *\n * @example\n * ```ts\n * console.log(adapter.getRegion()); // => 'us-east-1'\n * ```\n */\n getRegion(): string {\n return this.config.region;\n }\n}\n","/**\n * @module aws-ses-adapter\n *\n * A lightweight adapter that simplifies the AWS SES email sending API for Node.js.\n *\n * ## Quick Start\n *\n * **1. Initialize once** (at application startup):\n * ```ts\n * import { init } from 'aws-ses-adapter';\n *\n * init({\n * region: 'us-east-1',\n * accessKeyId: 'YOUR_KEY',\n * secretAccessKey: 'YOUR_SECRET',\n * defaultFrom: 'noreply@example.com',\n * });\n * ```\n *\n * **2. Use anywhere** in your application:\n * ```ts\n * import { sendEmail } from 'aws-ses-adapter';\n *\n * await sendEmail({\n * to: 'user@example.com',\n * subject: 'Welcome!',\n * html: '<h1>Welcome</h1>',\n * });\n * ```\n *\n * ## Environment Variables\n *\n * If credentials are not passed to `init()`, the adapter reads:\n * - `AWS_SES_REGION`\n * - `AWS_ACCESS_KEY_ID`\n * - `AWS_SECRET_ACCESS_KEY`\n * - `AWS_SES_FROM_EMAIL` (optional default sender)\n */\n\nimport { SesAdapter } from './adapter.js';\nimport { SesNotInitializedError } from './errors.js';\nimport type {\n SendEmailOptions,\n SendEmailResult,\n SendEmailWithAttachmentsOptions,\n SesAdapterConfig,\n} from './types.js';\n\n// ─── Singleton state ──────────────────────────────────────────────────────────\n\n/** @internal */\nlet _instance: SesAdapter | null = null;\n\n/**\n * Returns the current singleton instance.\n * @throws {SesNotInitializedError} If `init()` has not been called yet.\n * @internal\n */\nfunction getInstance(): SesAdapter {\n if (!_instance) {\n throw new SesNotInitializedError();\n }\n return _instance;\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Initializes the SES Adapter singleton.\n *\n * Must be called **once** before any other function in this module.\n * Calling `init()` again will replace the existing singleton instance,\n * which is useful for reconfiguration during testing.\n *\n * Credentials are resolved in the following order:\n * 1. Values provided in the `config` argument.\n * 2. Environment variables (`AWS_SES_REGION`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`).\n *\n * @param config - Optional configuration. Omit any field to fall back to environment variables.\n * @throws {SesConfigError} When required credentials cannot be resolved.\n *\n * @example\n * ```ts\n * // Using explicit credentials\n * init({\n * region: 'us-east-1',\n * accessKeyId: process.env.MY_KEY_ID,\n * secretAccessKey: process.env.MY_SECRET,\n * defaultFrom: 'no-reply@myapp.com',\n * });\n *\n * // Relying entirely on environment variables\n * init();\n * ```\n */\nexport function init(config: SesAdapterConfig = {}): void {\n _instance = new SesAdapter(config);\n}\n\n/**\n * Sends an email using the initialized SES Adapter.\n *\n * At least one of `options.html` or `options.text` must be provided.\n * If `options.from` is not specified, the `defaultFrom` set during {@link init} is used.\n *\n * @param options - Email sending options.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n * @throws {SesValidationError} When required email fields are missing or invalid.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * import { sendEmail } from 'aws-ses-adapter';\n *\n * const result = await sendEmail({\n * to: 'alice@example.com',\n * subject: 'Hello Alice',\n * html: '<p>Hi Alice!</p>',\n * text: 'Hi Alice!',\n * cc: 'manager@example.com',\n * bcc: ['audit@example.com'],\n * replyTo: 'support@example.com',\n * });\n *\n * console.log(result.messageId);\n * ```\n */\nexport async function sendEmail(\n options: SendEmailOptions,\n): Promise<SendEmailResult> {\n return getInstance().sendEmail(options);\n}\n\n/**\n * Sends an email with one or more file attachments using the initialized SES Adapter.\n *\n * Internally builds a multipart/mixed MIME message, so you don't need to\n * construct raw MIME yourself. At least one of `options.html` or `options.text`\n * must be provided, and `options.attachments` must contain at least one item.\n *\n * @param options - Email options including the attachments array.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n * @throws {SesValidationError} When required fields are missing or invalid.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * import { sendEmailWithAttachments } from 'aws-ses-adapter';\n * import { readFileSync } from 'fs';\n *\n * const result = await sendEmailWithAttachments({\n * to: 'alice@example.com',\n * subject: 'Your invoice',\n * html: '<p>Please find the invoice attached.</p>',\n * attachments: [\n * {\n * filename: 'invoice.pdf',\n * content: readFileSync('./invoice.pdf'),\n * contentType: 'application/pdf',\n * },\n * ],\n * });\n *\n * console.log(result.messageId);\n * ```\n */\nexport async function sendEmailWithAttachments(\n options: SendEmailWithAttachmentsOptions,\n): Promise<SendEmailResult> {\n return getInstance().sendEmailWithAttachments(options);\n}\n\n/**\n * Sends a raw MIME email using the initialized SES Adapter.\n *\n * Use this when you need full control over the email, such as including\n * attachments or custom MIME headers.\n *\n * @param rawMessage - The raw MIME email message as a string.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n * @throws {SesValidationError} When the raw message is empty.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * import { sendRawEmail } from 'aws-ses-adapter';\n *\n * const mime = [\n * 'From: sender@example.com',\n * 'To: recipient@example.com',\n * 'Subject: File attached',\n * 'MIME-Version: 1.0',\n * 'Content-Type: text/plain',\n * '',\n * 'Please find the attachment.',\n * ].join('\\r\\n');\n *\n * const result = await sendRawEmail(mime);\n * ```\n */\nexport async function sendRawEmail(\n rawMessage: string,\n): Promise<SendEmailResult> {\n return getInstance().sendRawEmail(rawMessage);\n}\n\n/**\n * Returns whether the singleton has been initialized via {@link init}.\n *\n * @returns `true` if `init()` has been called successfully.\n *\n * @example\n * ```ts\n * import { isInitialized } from 'aws-ses-adapter';\n *\n * if (!isInitialized()) {\n * init();\n * }\n * ```\n */\nexport function isInitialized(): boolean {\n return _instance !== null;\n}\n\n/**\n * Returns whether a default \"From\" address is configured in the singleton.\n *\n * @returns `true` if a default sender address is set.\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n *\n * @example\n * ```ts\n * import { hasDefaultFrom } from 'aws-ses-adapter';\n *\n * console.log(hasDefaultFrom()); // => true\n * ```\n */\nexport function hasDefaultFrom(): boolean {\n return getInstance().hasDefaultFrom();\n}\n\n/**\n * Returns the default \"From\" email address configured in the singleton,\n * or `undefined` if none was set.\n *\n * @returns The default sender address, or `undefined`.\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n *\n * @example\n * ```ts\n * import { getDefaultFrom } from 'aws-ses-adapter';\n *\n * const from = getDefaultFrom();\n * // => 'noreply@example.com' or undefined\n * ```\n */\nexport function getDefaultFrom(): string | undefined {\n return getInstance().getDefaultFrom();\n}\n\n/**\n * Returns the AWS region the singleton is configured to use.\n *\n * @returns The AWS region string (e.g. `'us-east-1'`).\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n *\n * @example\n * ```ts\n * import { getRegion } from 'aws-ses-adapter';\n *\n * console.log(getRegion()); // => 'us-east-1'\n * ```\n */\nexport function getRegion(): string {\n return getInstance().getRegion();\n}\n\n// ─── Re-exports ───────────────────────────────────────────────────────────────\n\n/**\n * Re-export the core adapter class for advanced use cases such as\n * creating multiple independent instances or building framework integrations\n * (e.g., a NestJS module).\n */\nexport { SesAdapter } from './adapter.js';\n\n/** Re-export all custom error classes for consumer-side `instanceof` checks. */\nexport {\n SesConfigError,\n SesNotInitializedError,\n SesSendError,\n SesValidationError,\n} from './errors.js';\n\n/** Re-export all public types and interfaces. */\nexport type {\n EmailAttachment,\n SendEmailOptions,\n SendEmailResult,\n SendEmailWithAttachmentsOptions,\n SesAdapterConfig,\n} from './types.js';\n"]}
1
+ {"version":3,"sources":["../src/client.ts","../src/errors.ts","../src/adapter.ts","../src/index.ts"],"names":["SESClient","SendRawEmailCommand","SendEmailCommand"],"mappings":";;;;;AA2BO,SAAS,eAAe,MAAA,EAA6C;AAC1E,EAAA,OAAO,IAAIA,mBAAA,CAAU;AAAA,IACnB,QAAQ,MAAA,CAAO,MAAA;AAAA,IACf,WAAA,EAAa;AAAA,MACX,aAAa,MAAA,CAAO,WAAA;AAAA,MACpB,iBAAiB,MAAA,CAAO;AAAA;AAC1B,GACD,CAAA;AACH;;;ACVO,IAAM,sBAAA,GAAN,cAAqC,KAAA,CAAM;AAAA,EAIhD,WAAA,GAAc;AACZ,IAAA,KAAA;AAAA,MACE;AAAA,KACF;AALF;AAAA,IAAA,IAAA,CAAS,IAAA,GAAO,wBAAA;AAAA,EAMhB;AACF;AAoBO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA;AAAA;AAAA;AAAA,EAOxC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AANf;AAAA,IAAA,IAAA,CAAS,IAAA,GAAO,gBAAA;AAAA,EAOhB;AACF;AAoBO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA;AAAA;AAAA;AAAA;AAAA,EAQtC,WAAA,CAAY,SAAiB,KAAA,EAAiB;AAC5C,IAAA,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,CAAA;AAP1B;AAAA,IAAA,IAAA,CAAS,IAAA,GAAO,cAAA;AAAA,EAQhB;AACF;AAoBO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA;AAAA;AAAA;AAAA,EAO5C,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AANf;AAAA,IAAA,IAAA,CAAS,IAAA,GAAO,oBAAA;AAAA,EAOhB;AACF;;;AC5FA,SAAS,aAAA,CACP,MAAA,GAA2B,EAAC,EACF;AAC1B,EAAA,MAAM,MAAA,GAAS,MAAA,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A,GAAc,cAAA,EAAe;AACtC;AAeO,SAAS,SAAA,GAAoB;AAClC,EAAA,OAAO,WAAA,GAAc,SAAA,EAAU;AACjC","file":"index.js","sourcesContent":["/**\n * @module client\n * Factory and utilities for building an AWS SESClient instance\n * from a resolved adapter configuration.\n */\n\nimport { SESClient } from '@aws-sdk/client-ses';\nimport type { ResolvedSesAdapterConfig } from './types';\n\n/**\n * Creates and returns a configured {@link SESClient} instance using the\n * resolved adapter configuration.\n *\n * @param config - The resolved configuration containing region and credentials.\n * @returns A ready-to-use AWS SESClient.\n *\n * @example\n * ```ts\n * const client = buildSesClient({\n * region: 'us-east-1',\n * accessKeyId: 'AKIAIOSFODNN7EXAMPLE',\n * secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',\n * });\n * ```\n *\n * @internal\n */\nexport function buildSesClient(config: ResolvedSesAdapterConfig): SESClient {\n return new SESClient({\n region: config.region,\n credentials: {\n accessKeyId: config.accessKeyId,\n secretAccessKey: config.secretAccessKey,\n },\n });\n}\n","/**\n * @module errors\n * Custom error classes for the aws-ses-adapter library.\n * All errors extend the native `Error` class and include a `name` property\n * suitable for programmatic error identification.\n */\n\n/**\n * Thrown when an operation is attempted before the adapter has been initialized\n * via {@link init}.\n *\n * @example\n * ```ts\n * import { sendEmail } from '@fmontoya/aws-ses-adapter';\n *\n * // Calling sendEmail before init() throws this error\n * try {\n * await sendEmail({ to: 'user@example.com', subject: 'Hi', text: 'Hello' });\n * } catch (err) {\n * if (err instanceof SesNotInitializedError) {\n * console.error('Call init() first');\n * }\n * }\n * ```\n */\nexport class SesNotInitializedError extends Error {\n /** @override */\n readonly name = 'SesNotInitializedError' as const;\n\n constructor() {\n super(\n 'SES Adapter has not been initialized. Call init() before using any adapter methods.',\n );\n }\n}\n\n/**\n * Thrown when the configuration provided to {@link init} is invalid or incomplete.\n * This typically happens when required credentials are missing from both the config\n * object and the environment variables.\n *\n * @example\n * ```ts\n * import { init } from '@fmontoya/aws-ses-adapter';\n *\n * try {\n * init({}); // No region, no env vars set\n * } catch (err) {\n * if (err instanceof SesConfigError) {\n * console.error('Config error:', err.message);\n * }\n * }\n * ```\n */\nexport class SesConfigError extends Error {\n /** @override */\n readonly name = 'SesConfigError' as const;\n\n /**\n * @param message - Description of the configuration issue.\n */\n constructor(message: string) {\n super(message);\n }\n}\n\n/**\n * Thrown when an email send operation fails at the AWS SES level.\n * The original AWS error is available via the `cause` property (ES2022+).\n *\n * @example\n * ```ts\n * import { sendEmail, SesSendError } from '@fmontoya/aws-ses-adapter';\n *\n * try {\n * await sendEmail({ to: 'user@example.com', subject: 'Hi', text: 'Hello' });\n * } catch (err) {\n * if (err instanceof SesSendError) {\n * console.error('Send failed:', err.message);\n * console.error('Original cause:', err.cause);\n * }\n * }\n * ```\n */\nexport class SesSendError extends Error {\n /** @override */\n readonly name = 'SesSendError' as const;\n\n /**\n * @param message - Description of the send failure.\n * @param cause - The underlying error from AWS SDK.\n */\n constructor(message: string, cause?: unknown) {\n super(message, { cause });\n }\n}\n\n/**\n * Thrown when {@link SendEmailOptions} are invalid, such as missing both\n * `html` and `text`, or having an invalid email address format.\n *\n * @example\n * ```ts\n * import { sendEmail, SesValidationError } from '@fmontoya/aws-ses-adapter';\n *\n * try {\n * // Missing both html and text\n * await sendEmail({ to: 'user@example.com', subject: 'Hi' });\n * } catch (err) {\n * if (err instanceof SesValidationError) {\n * console.error('Validation error:', err.message);\n * }\n * }\n * ```\n */\nexport class SesValidationError extends Error {\n /** @override */\n readonly name = 'SesValidationError' as const;\n\n /**\n * @param message - Description of the validation failure.\n */\n constructor(message: string) {\n super(message);\n }\n}\n","/**\n * @module adapter\n * Core SesAdapter class that wraps the AWS SES client and provides\n * simplified email sending methods.\n */\n\nimport type {\n SendEmailCommandInput,\n SendRawEmailCommandInput,\n SESClient,\n} from '@aws-sdk/client-ses';\nimport { SendEmailCommand, SendRawEmailCommand } from '@aws-sdk/client-ses';\nimport { buildSesClient } from './client';\nimport { SesConfigError, SesSendError, SesValidationError } from './errors';\nimport type {\n EmailAttachment,\n ResolvedSesAdapterConfig,\n SendEmailOptions,\n SendEmailResult,\n SendEmailWithAttachmentsOptions,\n SesAdapterConfig,\n} from './types';\n\n/**\n * Resolves the adapter configuration by merging user-provided values with\n * environment variable fallbacks.\n *\n * @param config - Optional user-provided configuration.\n * @returns The resolved configuration with all required fields populated.\n * @throws {SesConfigError} When required fields cannot be resolved from config or env vars.\n *\n * @internal\n */\nfunction resolveConfig(\n config: SesAdapterConfig = {},\n): ResolvedSesAdapterConfig {\n const region = config.region ?? process.env['AWS_SES_REGION'];\n const accessKeyId =\n config.credentials?.accessKeyId ??\n config.accessKeyId ??\n process.env['AWS_ACCESS_KEY_ID'];\n const secretAccessKey =\n config.credentials?.secretAccessKey ??\n config.secretAccessKey ??\n process.env['AWS_SECRET_ACCESS_KEY'];\n const defaultFrom = config.defaultFrom ?? process.env['AWS_SES_FROM_EMAIL'];\n\n if (!region) {\n throw new SesConfigError(\n 'AWS SES region is required. Provide it via config.region or the AWS_SES_REGION environment variable.',\n );\n }\n if (!accessKeyId) {\n throw new SesConfigError(\n 'AWS access key ID is required. Provide it via config.credentials.accessKeyId, or the AWS_ACCESS_KEY_ID environment variable.',\n );\n }\n if (!secretAccessKey) {\n throw new SesConfigError(\n 'AWS secret access key is required. Provide it via config.credentials.secretAccessKey, or the AWS_SECRET_ACCESS_KEY environment variable.',\n );\n }\n\n return { region, accessKeyId, secretAccessKey, defaultFrom };\n}\n\n/**\n * Normalizes a value that can be a single string or an array of strings\n * into a guaranteed array.\n *\n * @param value - A string or array of strings.\n * @returns An array of strings.\n *\n * @internal\n */\nfunction toArray(value: string | string[]): string[] {\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Encodes a MIME header value using RFC 2047 Base64 encoded-word syntax\n * when the value contains non-ASCII characters.\n *\n * @param value - The raw header value (e.g. a subject line).\n * @returns The value as-is if it is pure ASCII, otherwise `=?UTF-8?B?...?=`.\n *\n * @internal\n */\nfunction encodeHeaderValue(value: string): string {\n // If no non-ASCII characters are present, return as-is\n if (!/[\\u0080-\\uFFFF]/.test(value)) return value;\n return `=?UTF-8?B?${Buffer.from(value, 'utf-8').toString('base64')}?=`;\n}\n\n/**\n * Builds a multipart/mixed MIME email message ready to be sent via\n * `SendRawEmailCommand`.\n *\n * The body section uses multipart/alternative when both `html` and `text` are\n * supplied so that email clients can choose the best representation.\n *\n * @internal\n */\nfunction buildMimeMessage(\n options: SendEmailWithAttachmentsOptions,\n from: string,\n): string {\n const mixedBoundary = `----=_Mixed_${Date.now()}_${Math.random().toString(36).slice(2)}`;\n const altBoundary = `----=_Alt_${Date.now()}_${Math.random().toString(36).slice(2)}`;\n\n const lines: string[] = [];\n\n // RFC 2822 headers\n lines.push(`From: ${from}`);\n lines.push(`To: ${toArray(options.to).join(', ')}`);\n if (options.cc) lines.push(`Cc: ${toArray(options.cc).join(', ')}`);\n if (options.bcc) lines.push(`Bcc: ${toArray(options.bcc).join(', ')}`);\n if (options.replyTo)\n lines.push(`Reply-To: ${toArray(options.replyTo).join(', ')}`);\n lines.push(`Subject: ${encodeHeaderValue(options.subject)}`);\n lines.push('MIME-Version: 1.0');\n lines.push(`Content-Type: multipart/mixed; boundary=\"${mixedBoundary}\"`);\n lines.push('');\n\n // ── Body part ────────────────────────────────────────────────────────────\n if (options.html && options.text) {\n // Both formats: wrap in multipart/alternative\n lines.push(`--${mixedBoundary}`);\n lines.push(\n `Content-Type: multipart/alternative; boundary=\"${altBoundary}\"`,\n );\n lines.push('');\n\n lines.push(`--${altBoundary}`);\n lines.push('Content-Type: text/plain; charset=UTF-8');\n lines.push('Content-Transfer-Encoding: 8bit');\n lines.push('');\n lines.push(options.text);\n lines.push('');\n\n lines.push(`--${altBoundary}`);\n lines.push('Content-Type: text/html; charset=UTF-8');\n lines.push('Content-Transfer-Encoding: 8bit');\n lines.push('');\n lines.push(options.html);\n lines.push('');\n\n lines.push(`--${altBoundary}--`);\n lines.push('');\n } else if (options.html) {\n lines.push(`--${mixedBoundary}`);\n lines.push('Content-Type: text/html; charset=UTF-8');\n lines.push('Content-Transfer-Encoding: 8bit');\n lines.push('');\n lines.push(options.html);\n lines.push('');\n } else if (options.text) {\n lines.push(`--${mixedBoundary}`);\n lines.push('Content-Type: text/plain; charset=UTF-8');\n lines.push('Content-Transfer-Encoding: 8bit');\n lines.push('');\n lines.push(options.text);\n lines.push('');\n }\n\n // ── Attachment parts ─────────────────────────────────────────────────────\n for (const attachment of options.attachments) {\n const encoded = encodeAttachment(attachment);\n const safeName = attachment.filename.replace(/\"/g, '');\n\n lines.push(`--${mixedBoundary}`);\n lines.push(`Content-Type: ${attachment.contentType}; name=\"${safeName}\"`);\n lines.push('Content-Transfer-Encoding: base64');\n lines.push(`Content-Disposition: attachment; filename=\"${safeName}\"`);\n lines.push('');\n // RFC 2045: base64 lines must not exceed 76 characters\n lines.push(encoded.match(/.{1,76}/g)?.join('\\r\\n') ?? encoded);\n lines.push('');\n }\n\n lines.push(`--${mixedBoundary}--`);\n\n return lines.join('\\r\\n');\n}\n\n/**\n * Encodes an attachment's content as a base64 string.\n *\n * @param attachment - The attachment to encode.\n * @returns Base64-encoded string.\n *\n * @internal\n */\nfunction encodeAttachment(attachment: EmailAttachment): string {\n if (Buffer.isBuffer(attachment.content)) {\n return attachment.content.toString('base64');\n }\n return Buffer.from(attachment.content).toString('base64');\n}\n\n/**\n * Core adapter class that wraps the AWS SES client and provides a simplified\n * API for sending emails.\n *\n * This class is not meant to be instantiated directly by consumers.\n * Use the singleton functions exported from the main module instead.\n *\n * @see {@link init} to initialize the singleton.\n * @see {@link sendEmail} to send a standard email.\n * @see {@link sendRawEmail} to send a raw MIME email.\n */\nexport class SesAdapter {\n /** @internal */\n private readonly sesClient: SESClient;\n\n /** @internal */\n private readonly config: ResolvedSesAdapterConfig;\n\n /**\n * Creates a new SesAdapter instance.\n *\n * @param userConfig - Optional configuration. Missing fields fall back to environment variables.\n * @throws {SesConfigError} When required configuration fields are missing.\n */\n constructor(userConfig: SesAdapterConfig = {}) {\n this.config = resolveConfig(userConfig);\n this.sesClient = buildSesClient(this.config);\n }\n\n /**\n * Validates that at least one body content field (`html` or `text`) is provided.\n *\n * @param options - Object containing optional `html` and `text` fields.\n * @throws {SesValidationError} When neither field is present.\n *\n * @internal\n */\n private validateBodyOptions(options: { html?: string; text?: string }): void {\n if (!options.html && !options.text) {\n throw new SesValidationError(\n 'At least one of \"html\" or \"text\" must be provided.',\n );\n }\n }\n\n /**\n * Resolves the sender address from the per-call option or the adapter default.\n *\n * @param from - The per-call \"from\" address, if provided.\n * @returns The resolved sender address.\n * @throws {SesValidationError} When no sender address can be determined.\n *\n * @internal\n */\n private resolveFrom(from?: string): string {\n const resolved = from ?? this.config.defaultFrom;\n if (!resolved) {\n throw new SesValidationError(\n 'A sender address is required. Provide \"from\" in the options or set \"defaultFrom\" during init().',\n );\n }\n return resolved;\n }\n\n /**\n * Dispatches a raw MIME message via `SendRawEmailCommand`.\n *\n * @param rawMessage - The raw MIME string to send.\n * @param errorContext - Human-readable context prepended to error messages.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @internal\n */\n private async dispatchRawEmail(\n rawMessage: string,\n errorContext: string,\n ): Promise<SendEmailResult> {\n const params: SendRawEmailCommandInput = {\n RawMessage: {\n Data: Buffer.from(rawMessage),\n },\n };\n\n try {\n const command = new SendRawEmailCommand(params);\n const response = await this.sesClient.send(command);\n\n return {\n success: true,\n messageId: response.MessageId,\n };\n } catch (error) {\n throw new SesSendError(\n `${errorContext}: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n }\n\n /**\n * Sends an email using AWS SES.\n *\n * At least one of `options.html` or `options.text` must be provided.\n * If `options.from` is not specified, the `defaultFrom` configured during\n * initialization is used. If neither is available, the call throws.\n *\n * @param options - Email sending options.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesValidationError} When required email fields are missing or invalid.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * const result = await adapter.sendEmail({\n * to: ['alice@example.com', 'bob@example.com'],\n * subject: 'Hello!',\n * html: '<p>Hello World</p>',\n * text: 'Hello World',\n * cc: 'manager@example.com',\n * });\n * ```\n */\n async sendEmail(options: SendEmailOptions): Promise<SendEmailResult> {\n this.validateBodyOptions(options);\n\n const from = this.resolveFrom(options.from);\n\n const toAddresses = toArray(options.to);\n\n const params: SendEmailCommandInput = {\n Source: from,\n Destination: {\n ToAddresses: toAddresses,\n CcAddresses: options.cc ? toArray(options.cc) : undefined,\n BccAddresses: options.bcc ? toArray(options.bcc) : undefined,\n },\n Message: {\n Subject: {\n Data: options.subject,\n Charset: 'UTF-8',\n },\n Body: {\n Html: options.html\n ? { Data: options.html, Charset: 'UTF-8' }\n : undefined,\n Text: options.text\n ? { Data: options.text, Charset: 'UTF-8' }\n : undefined,\n },\n },\n ReplyToAddresses: options.replyTo ? toArray(options.replyTo) : undefined,\n };\n\n try {\n const command = new SendEmailCommand(params);\n const response = await this.sesClient.send(command);\n\n return {\n success: true,\n messageId: response.MessageId,\n };\n } catch (error) {\n throw new SesSendError(\n `Failed to send email to ${toAddresses.join(', ')}: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n }\n\n /**\n * Sends a raw MIME email using AWS SES.\n *\n * Use this method when you need full control over the email format, such as\n * sending emails with attachments or custom headers.\n *\n * @param rawMessage - The raw MIME email message as a string.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesValidationError} When the raw message is empty.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * const mimeMessage = [\n * 'From: sender@example.com',\n * 'To: recipient@example.com',\n * 'Subject: Test',\n * 'MIME-Version: 1.0',\n * 'Content-Type: text/plain',\n * '',\n * 'Hello World',\n * ].join('\\r\\n');\n *\n * const result = await adapter.sendRawEmail(mimeMessage);\n * ```\n */\n async sendRawEmail(rawMessage: string): Promise<SendEmailResult> {\n if (!rawMessage || rawMessage.trim().length === 0) {\n throw new SesValidationError('rawMessage cannot be empty.');\n }\n\n return this.dispatchRawEmail(rawMessage, 'Failed to send raw email');\n }\n\n /**\n * Sends an email with one or more file attachments using AWS SES.\n *\n * Internally builds a multipart/mixed MIME message and dispatches it via\n * `SendRawEmailCommand`, giving you full attachment support without needing\n * to craft raw MIME by hand.\n *\n * At least one of `options.html` or `options.text` must be provided.\n * The `options.attachments` array must contain at least one item.\n *\n * @param options - Email options including the attachments array.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesValidationError} When required fields are missing or invalid.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * const result = await adapter.sendEmailWithAttachments({\n * to: 'alice@example.com',\n * subject: 'Your invoice',\n * html: '<p>Please find the invoice attached.</p>',\n * attachments: [\n * {\n * filename: 'invoice.pdf',\n * content: fs.readFileSync('./invoice.pdf'),\n * contentType: 'application/pdf',\n * },\n * ],\n * });\n * ```\n */\n async sendEmailWithAttachments(\n options: SendEmailWithAttachmentsOptions,\n ): Promise<SendEmailResult> {\n this.validateBodyOptions(options);\n\n if (!options.attachments || options.attachments.length === 0) {\n throw new SesValidationError(\n 'At least one attachment must be provided in SendEmailWithAttachmentsOptions.attachments.',\n );\n }\n\n const from = this.resolveFrom(options.from);\n const toAddresses = toArray(options.to);\n const rawMessage = buildMimeMessage(options, from);\n\n return this.dispatchRawEmail(\n rawMessage,\n `Failed to send email with attachments to ${toAddresses.join(', ')}`,\n );\n }\n\n /**\n * Returns whether the adapter has a default \"From\" address configured.\n *\n * @returns `true` if a default from address is available.\n *\n * @example\n * ```ts\n * if (adapter.hasDefaultFrom()) {\n * console.log('Default from:', adapter.getDefaultFrom());\n * }\n * ```\n */\n hasDefaultFrom(): boolean {\n return !!this.config.defaultFrom;\n }\n\n /**\n * Returns the default \"From\" email address, or `undefined` if not set.\n *\n * @returns The default sender address, or `undefined`.\n *\n * @example\n * ```ts\n * const from = adapter.getDefaultFrom();\n * // => 'noreply@example.com' or undefined\n * ```\n */\n getDefaultFrom(): string | undefined {\n return this.config.defaultFrom;\n }\n\n /**\n * Returns the AWS region the adapter is configured to use.\n *\n * @returns The AWS region string.\n *\n * @example\n * ```ts\n * console.log(adapter.getRegion()); // => 'us-east-1'\n * ```\n */\n getRegion(): string {\n return this.config.region;\n }\n}\n","/**\n * @module aws-ses-adapter\n *\n * A lightweight adapter that simplifies the AWS SES email sending API for Node.js.\n *\n * ## Quick Start\n *\n * **1. Initialize once** (at application startup):\n * ```ts\n * import { init } from '@fmontoya/aws-ses-adapter';\n *\n * init({\n * region: 'us-east-1',\n * credentials: {\n * accessKeyId: 'YOUR_KEY',\n * secretAccessKey: 'YOUR_SECRET',\n * },\n * defaultFrom: 'noreply@example.com',\n * });\n * ```\n *\n * **2. Use anywhere** in your application:\n * ```ts\n * import { sendEmail } from '@fmontoya/aws-ses-adapter';\n *\n * await sendEmail({\n * to: 'user@example.com',\n * subject: 'Welcome!',\n * html: '<h1>Welcome</h1>',\n * });\n * ```\n *\n * ## Environment Variables\n *\n * If credentials are not passed to `init()`, the adapter reads:\n * - `AWS_SES_REGION`\n * - `AWS_ACCESS_KEY_ID`\n * - `AWS_SECRET_ACCESS_KEY`\n * - `AWS_SES_FROM_EMAIL` (optional default sender)\n */\n\nimport { SesAdapter } from './adapter';\nimport { SesNotInitializedError } from './errors';\nimport type {\n SendEmailOptions,\n SendEmailResult,\n SendEmailWithAttachmentsOptions,\n SesAdapterConfig,\n} from './types';\n\n// ─── Singleton state ──────────────────────────────────────────────────────────\n\n/** @internal */\nlet _instance: SesAdapter | null = null;\n\n/**\n * Returns the current singleton instance.\n * @throws {SesNotInitializedError} If `init()` has not been called yet.\n * @internal\n */\nfunction getInstance(): SesAdapter {\n if (!_instance) {\n throw new SesNotInitializedError();\n }\n return _instance;\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Initializes the SES Adapter singleton.\n *\n * Must be called **once** before any other function in this module.\n * Calling `init()` again will replace the existing singleton instance,\n * which is useful for reconfiguration during testing.\n *\n * Credentials are resolved in the following order:\n * 1. `config.credentials.accessKeyId` / `config.credentials.secretAccessKey`\n * 2. `config.accessKeyId` / `config.secretAccessKey` _(deprecated)_\n * 3. Environment variables (`AWS_SES_REGION`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`)\n *\n * @param config - Optional configuration. Omit any field to fall back to environment variables.\n * @throws {SesConfigError} When required credentials cannot be resolved.\n *\n * @example\n * ```ts\n * // Using explicit credentials\n * init({\n * region: 'us-east-1',\n * credentials: {\n * accessKeyId: process.env.MY_KEY_ID,\n * secretAccessKey: process.env.MY_SECRET,\n * },\n * defaultFrom: 'no-reply@myapp.com',\n * });\n *\n * // Relying entirely on environment variables\n * init();\n * ```\n */\nexport function init(config: SesAdapterConfig = {}): void {\n _instance = new SesAdapter(config);\n}\n\n/**\n * Sends an email using the initialized SES Adapter.\n *\n * At least one of `options.html` or `options.text` must be provided.\n * If `options.from` is not specified, the `defaultFrom` set during {@link init} is used.\n *\n * @param options - Email sending options.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n * @throws {SesValidationError} When required email fields are missing or invalid.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * import { sendEmail } from '@fmontoya/aws-ses-adapter';\n *\n * const result = await sendEmail({\n * to: 'alice@example.com',\n * subject: 'Hello Alice',\n * html: '<p>Hi Alice!</p>',\n * text: 'Hi Alice!',\n * cc: 'manager@example.com',\n * bcc: ['audit@example.com'],\n * replyTo: 'support@example.com',\n * });\n *\n * console.log(result.messageId);\n * ```\n */\nexport async function sendEmail(\n options: SendEmailOptions,\n): Promise<SendEmailResult> {\n return getInstance().sendEmail(options);\n}\n\n/**\n * Sends an email with one or more file attachments using the initialized SES Adapter.\n *\n * Internally builds a multipart/mixed MIME message, so you don't need to\n * construct raw MIME yourself. At least one of `options.html` or `options.text`\n * must be provided, and `options.attachments` must contain at least one item.\n *\n * @param options - Email options including the attachments array.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n * @throws {SesValidationError} When required fields are missing or invalid.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * import { sendEmailWithAttachments } from '@fmontoya/aws-ses-adapter';\n * import { readFileSync } from 'fs';\n *\n * const result = await sendEmailWithAttachments({\n * to: 'alice@example.com',\n * subject: 'Your invoice',\n * html: '<p>Please find the invoice attached.</p>',\n * attachments: [\n * {\n * filename: 'invoice.pdf',\n * content: readFileSync('./invoice.pdf'),\n * contentType: 'application/pdf',\n * },\n * ],\n * });\n *\n * console.log(result.messageId);\n * ```\n */\nexport async function sendEmailWithAttachments(\n options: SendEmailWithAttachmentsOptions,\n): Promise<SendEmailResult> {\n return getInstance().sendEmailWithAttachments(options);\n}\n\n/**\n * Sends a raw MIME email using the initialized SES Adapter.\n *\n * Use this when you need full control over the email, such as including\n * attachments or custom MIME headers.\n *\n * @param rawMessage - The raw MIME email message as a string.\n * @returns A promise resolving to a {@link SendEmailResult}.\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n * @throws {SesValidationError} When the raw message is empty.\n * @throws {SesSendError} When the AWS SES API call fails.\n *\n * @example\n * ```ts\n * import { sendRawEmail } from '@fmontoya/aws-ses-adapter';\n *\n * const mime = [\n * 'From: sender@example.com',\n * 'To: recipient@example.com',\n * 'Subject: File attached',\n * 'MIME-Version: 1.0',\n * 'Content-Type: text/plain',\n * '',\n * 'Please find the attachment.',\n * ].join('\\r\\n');\n *\n * const result = await sendRawEmail(mime);\n * ```\n */\nexport async function sendRawEmail(\n rawMessage: string,\n): Promise<SendEmailResult> {\n return getInstance().sendRawEmail(rawMessage);\n}\n\n/**\n * Returns whether the singleton has been initialized via {@link init}.\n *\n * @returns `true` if `init()` has been called successfully.\n *\n * @example\n * ```ts\n * import { isInitialized } from '@fmontoya/aws-ses-adapter';\n *\n * if (!isInitialized()) {\n * init();\n * }\n * ```\n */\nexport function isInitialized(): boolean {\n return _instance !== null;\n}\n\n/**\n * Returns whether a default \"From\" address is configured in the singleton.\n *\n * @returns `true` if a default sender address is set.\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n *\n * @example\n * ```ts\n * import { hasDefaultFrom } from '@fmontoya/aws-ses-adapter';\n *\n * console.log(hasDefaultFrom()); // => true\n * ```\n */\nexport function hasDefaultFrom(): boolean {\n return getInstance().hasDefaultFrom();\n}\n\n/**\n * Returns the default \"From\" email address configured in the singleton,\n * or `undefined` if none was set.\n *\n * @returns The default sender address, or `undefined`.\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n *\n * @example\n * ```ts\n * import { getDefaultFrom } from '@fmontoya/aws-ses-adapter';\n *\n * const from = getDefaultFrom();\n * // => 'noreply@example.com' or undefined\n * ```\n */\nexport function getDefaultFrom(): string | undefined {\n return getInstance().getDefaultFrom();\n}\n\n/**\n * Returns the AWS region the singleton is configured to use.\n *\n * @returns The AWS region string (e.g. `'us-east-1'`).\n * @throws {SesNotInitializedError} If {@link init} has not been called.\n *\n * @example\n * ```ts\n * import { getRegion } from '@fmontoya/aws-ses-adapter';\n *\n * console.log(getRegion()); // => 'us-east-1'\n * ```\n */\nexport function getRegion(): string {\n return getInstance().getRegion();\n}\n\n// ─── Re-exports ───────────────────────────────────────────────────────────────\n\n/**\n * Re-export the core adapter class for advanced use cases such as\n * creating multiple independent instances or building framework integrations\n * (e.g., a NestJS module).\n */\nexport { SesAdapter } from './adapter';\n\n/** Re-export all custom error classes for consumer-side `instanceof` checks. */\nexport {\n SesConfigError,\n SesNotInitializedError,\n SesSendError,\n SesValidationError,\n} from './errors';\n\n/** Re-export all public types and interfaces. */\nexport type {\n EmailAttachment,\n SendEmailOptions,\n SendEmailResult,\n SendEmailWithAttachmentsOptions,\n SesAdapterConfig,\n} from './types';\n"]}
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { SendEmailCommand, SendRawEmailCommand, SESClient } from '@aws-sdk/client-ses';
1
+ import { SendRawEmailCommand, SendEmailCommand, SESClient } from '@aws-sdk/client-ses';
2
2
 
3
3
  // src/adapter.ts
4
4
  function buildSesClient(config) {
@@ -56,8 +56,8 @@ var SesValidationError = class extends Error {
56
56
  // src/adapter.ts
57
57
  function resolveConfig(config = {}) {
58
58
  const region = config.region ?? process.env["AWS_SES_REGION"];
59
- const accessKeyId = config.accessKeyId ?? process.env["AWS_ACCESS_KEY_ID"];
60
- const secretAccessKey = config.secretAccessKey ?? process.env["AWS_SECRET_ACCESS_KEY"];
59
+ const accessKeyId = config.credentials?.accessKeyId ?? config.accessKeyId ?? process.env["AWS_ACCESS_KEY_ID"];
60
+ const secretAccessKey = config.credentials?.secretAccessKey ?? config.secretAccessKey ?? process.env["AWS_SECRET_ACCESS_KEY"];
61
61
  const defaultFrom = config.defaultFrom ?? process.env["AWS_SES_FROM_EMAIL"];
62
62
  if (!region) {
63
63
  throw new SesConfigError(
@@ -66,12 +66,12 @@ function resolveConfig(config = {}) {
66
66
  }
67
67
  if (!accessKeyId) {
68
68
  throw new SesConfigError(
69
- "AWS access key ID is required. Provide it via config.accessKeyId or the AWS_ACCESS_KEY_ID environment variable."
69
+ "AWS access key ID is required. Provide it via config.credentials.accessKeyId, or the AWS_ACCESS_KEY_ID environment variable."
70
70
  );
71
71
  }
72
72
  if (!secretAccessKey) {
73
73
  throw new SesConfigError(
74
- "AWS secret access key is required. Provide it via config.secretAccessKey or the AWS_SECRET_ACCESS_KEY environment variable."
74
+ "AWS secret access key is required. Provide it via config.credentials.secretAccessKey, or the AWS_SECRET_ACCESS_KEY environment variable."
75
75
  );
76
76
  }
77
77
  return { region, accessKeyId, secretAccessKey, defaultFrom };
@@ -163,6 +163,69 @@ var SesAdapter = class {
163
163
  this.config = resolveConfig(userConfig);
164
164
  this.sesClient = buildSesClient(this.config);
165
165
  }
166
+ /**
167
+ * Validates that at least one body content field (`html` or `text`) is provided.
168
+ *
169
+ * @param options - Object containing optional `html` and `text` fields.
170
+ * @throws {SesValidationError} When neither field is present.
171
+ *
172
+ * @internal
173
+ */
174
+ validateBodyOptions(options) {
175
+ if (!options.html && !options.text) {
176
+ throw new SesValidationError(
177
+ 'At least one of "html" or "text" must be provided.'
178
+ );
179
+ }
180
+ }
181
+ /**
182
+ * Resolves the sender address from the per-call option or the adapter default.
183
+ *
184
+ * @param from - The per-call "from" address, if provided.
185
+ * @returns The resolved sender address.
186
+ * @throws {SesValidationError} When no sender address can be determined.
187
+ *
188
+ * @internal
189
+ */
190
+ resolveFrom(from) {
191
+ const resolved = from ?? this.config.defaultFrom;
192
+ if (!resolved) {
193
+ throw new SesValidationError(
194
+ 'A sender address is required. Provide "from" in the options or set "defaultFrom" during init().'
195
+ );
196
+ }
197
+ return resolved;
198
+ }
199
+ /**
200
+ * Dispatches a raw MIME message via `SendRawEmailCommand`.
201
+ *
202
+ * @param rawMessage - The raw MIME string to send.
203
+ * @param errorContext - Human-readable context prepended to error messages.
204
+ * @returns A promise resolving to a {@link SendEmailResult}.
205
+ * @throws {SesSendError} When the AWS SES API call fails.
206
+ *
207
+ * @internal
208
+ */
209
+ async dispatchRawEmail(rawMessage, errorContext) {
210
+ const params = {
211
+ RawMessage: {
212
+ Data: Buffer.from(rawMessage)
213
+ }
214
+ };
215
+ try {
216
+ const command = new SendRawEmailCommand(params);
217
+ const response = await this.sesClient.send(command);
218
+ return {
219
+ success: true,
220
+ messageId: response.MessageId
221
+ };
222
+ } catch (error) {
223
+ throw new SesSendError(
224
+ `${errorContext}: ${error instanceof Error ? error.message : String(error)}`,
225
+ error
226
+ );
227
+ }
228
+ }
166
229
  /**
167
230
  * Sends an email using AWS SES.
168
231
  *
@@ -187,17 +250,8 @@ var SesAdapter = class {
187
250
  * ```
188
251
  */
189
252
  async sendEmail(options) {
190
- if (!options.html && !options.text) {
191
- throw new SesValidationError(
192
- 'At least one of "html" or "text" must be provided in SendEmailOptions.'
193
- );
194
- }
195
- const from = options.from ?? this.config.defaultFrom;
196
- if (!from) {
197
- throw new SesValidationError(
198
- 'A sender address is required. Provide "from" in SendEmailOptions or set "defaultFrom" during init().'
199
- );
200
- }
253
+ this.validateBodyOptions(options);
254
+ const from = this.resolveFrom(options.from);
201
255
  const toAddresses = toArray(options.to);
202
256
  const params = {
203
257
  Source: from,
@@ -262,24 +316,7 @@ var SesAdapter = class {
262
316
  if (!rawMessage || rawMessage.trim().length === 0) {
263
317
  throw new SesValidationError("rawMessage cannot be empty.");
264
318
  }
265
- const params = {
266
- RawMessage: {
267
- Data: Buffer.from(rawMessage)
268
- }
269
- };
270
- try {
271
- const command = new SendRawEmailCommand(params);
272
- const response = await this.sesClient.send(command);
273
- return {
274
- success: true,
275
- messageId: response.MessageId
276
- };
277
- } catch (error) {
278
- throw new SesSendError(
279
- `Failed to send raw email: ${error instanceof Error ? error.message : String(error)}`,
280
- error
281
- );
282
- }
319
+ return this.dispatchRawEmail(rawMessage, "Failed to send raw email");
283
320
  }
284
321
  /**
285
322
  * Sends an email with one or more file attachments using AWS SES.
@@ -313,42 +350,19 @@ var SesAdapter = class {
313
350
  * ```
314
351
  */
315
352
  async sendEmailWithAttachments(options) {
316
- if (!options.html && !options.text) {
317
- throw new SesValidationError(
318
- 'At least one of "html" or "text" must be provided in SendEmailWithAttachmentsOptions.'
319
- );
320
- }
353
+ this.validateBodyOptions(options);
321
354
  if (!options.attachments || options.attachments.length === 0) {
322
355
  throw new SesValidationError(
323
356
  "At least one attachment must be provided in SendEmailWithAttachmentsOptions.attachments."
324
357
  );
325
358
  }
326
- const from = options.from ?? this.config.defaultFrom;
327
- if (!from) {
328
- throw new SesValidationError(
329
- 'A sender address is required. Provide "from" in SendEmailWithAttachmentsOptions or set "defaultFrom" during init().'
330
- );
331
- }
332
- const rawMessage = buildMimeMessage(options, from);
359
+ const from = this.resolveFrom(options.from);
333
360
  const toAddresses = toArray(options.to);
334
- const params = {
335
- RawMessage: {
336
- Data: Buffer.from(rawMessage)
337
- }
338
- };
339
- try {
340
- const command = new SendRawEmailCommand(params);
341
- const response = await this.sesClient.send(command);
342
- return {
343
- success: true,
344
- messageId: response.MessageId
345
- };
346
- } catch (error) {
347
- throw new SesSendError(
348
- `Failed to send email with attachments to ${toAddresses.join(", ")}: ${error instanceof Error ? error.message : String(error)}`,
349
- error
350
- );
351
- }
361
+ const rawMessage = buildMimeMessage(options, from);
362
+ return this.dispatchRawEmail(
363
+ rawMessage,
364
+ `Failed to send email with attachments to ${toAddresses.join(", ")}`
365
+ );
352
366
  }
353
367
  /**
354
368
  * Returns whether the adapter has a default "From" address configured.