ts-mailkit 2.0.0 → 2.1.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.
Files changed (37) hide show
  1. package/README.md +114 -63
  2. package/dist/core/bulk-types.d.ts +196 -0
  3. package/dist/core/bulk-types.d.ts.map +1 -0
  4. package/dist/core/client.d.ts +38 -6
  5. package/dist/core/client.d.ts.map +1 -1
  6. package/dist/core/errors.d.ts +3 -0
  7. package/dist/core/errors.d.ts.map +1 -1
  8. package/dist/core/types.d.ts +5 -0
  9. package/dist/core/types.d.ts.map +1 -1
  10. package/dist/index.cjs +926 -754
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.ts +19 -13
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +904 -709
  15. package/dist/index.js.map +1 -1
  16. package/dist/renderers/default/default-renderer.d.ts +2 -2
  17. package/dist/renderers/default/default-renderer.d.ts.map +1 -1
  18. package/dist/renderers/renderer.interface.d.ts +1 -1
  19. package/dist/templates/factory.d.ts +1 -1
  20. package/dist/templates/factory.d.ts.map +1 -1
  21. package/dist/templates/template-builder.d.ts +36 -0
  22. package/dist/templates/template-builder.d.ts.map +1 -0
  23. package/dist/transports/console/console-sender.d.ts +7 -2
  24. package/dist/transports/console/console-sender.d.ts.map +1 -1
  25. package/dist/transports/cpaas/cpaas-sender.d.ts +51 -0
  26. package/dist/transports/cpaas/cpaas-sender.d.ts.map +1 -0
  27. package/dist/transports/cpaas/types.d.ts +133 -0
  28. package/dist/transports/cpaas/types.d.ts.map +1 -0
  29. package/dist/transports/memory/memory-sender.d.ts +26 -6
  30. package/dist/transports/memory/memory-sender.d.ts.map +1 -1
  31. package/dist/transports/sender.interface.d.ts +34 -3
  32. package/dist/transports/sender.interface.d.ts.map +1 -1
  33. package/dist/transports/zeptomail/types.d.ts +5 -46
  34. package/dist/transports/zeptomail/types.d.ts.map +1 -1
  35. package/dist/transports/zeptomail/zeptomail-sender.d.ts +4 -19
  36. package/dist/transports/zeptomail/zeptomail-sender.d.ts.map +1 -1
  37. package/package.json +40 -38
package/dist/index.js CHANGED
@@ -1,757 +1,952 @@
1
- // src/core/types.ts
1
+ //#region src/core/types.ts
2
+ /**
3
+ * Parses an RFC 5322 formatted address string into an EmailAddress.
4
+ * Supports formats such as:
5
+ * - "user@example.com" -> { address: "user@example.com" }
6
+ * - "Sender Name <sender@example.com>" -> { name: "Sender Name", address: "sender@example.com" }
7
+ * - "\"Sender Name\" <sender@example.com>" -> { name: "Sender Name", address: "sender@example.com" }
8
+ */
2
9
  function parseEmailAddress(input) {
3
- if (!input || typeof input !== "string") {
4
- return { address: "" };
5
- }
6
- const trimmed = input.trim();
7
- const match = trimmed.match(/^(?:["']?([^"']+)["']?\s+)?<?([^\s<>@]+@[^\s<>@]+)>?$/);
8
- if (!match) {
9
- return { address: trimmed };
10
- }
11
- return {
12
- address: match[2].trim(),
13
- name: match[1]?.trim() || void 0
14
- };
10
+ if (!input || typeof input !== "string") return { address: "" };
11
+ const trimmed = input.trim();
12
+ const match = trimmed.match(/^(?:["']?([^"']+)["']?\s+)?<?([^\s<>@]+@[^\s<>@]+)>?$/);
13
+ if (!match) return { address: trimmed };
14
+ return {
15
+ address: match[2].trim(),
16
+ name: match[1]?.trim() || void 0
17
+ };
15
18
  }
19
+ /**
20
+ * Normalizes a Recipient value into a standardized EmailAddress.
21
+ */
16
22
  function normalizeRecipient(recipient) {
17
- if (typeof recipient === "string") {
18
- return { address: recipient.trim() };
19
- }
20
- if ("email" in recipient) {
21
- return {
22
- address: (recipient.email ?? "").trim(),
23
- name: recipient.name?.trim()
24
- };
25
- }
26
- return {
27
- address: (recipient.address ?? "").trim(),
28
- name: recipient.name?.trim()
29
- };
23
+ if (typeof recipient === "string") return { address: recipient.trim() };
24
+ if ("email" in recipient) return {
25
+ address: (recipient.email ?? "").trim(),
26
+ name: recipient.name?.trim()
27
+ };
28
+ return {
29
+ address: (recipient.address ?? "").trim(),
30
+ name: recipient.name?.trim()
31
+ };
30
32
  }
33
+ /**
34
+ * Normalizes a single or array of Recipients into an array of EmailAddress.
35
+ */
31
36
  function normalizeRecipients(recipients) {
32
- if (!recipients) return [];
33
- const list = Array.isArray(recipients) ? recipients : [recipients];
34
- return list.map(normalizeRecipient).filter((r) => r.address.length > 0);
37
+ if (!recipients) return [];
38
+ return (Array.isArray(recipients) ? recipients : [recipients]).map(normalizeRecipient).filter((r) => r.address.length > 0);
35
39
  }
36
40
 
37
- // src/core/errors.ts
41
+ //#endregion
42
+ //#region src/core/errors.ts
43
+ /**
44
+ * Base error class for all ts-mailkit errors.
45
+ */
38
46
  var MailKitError = class extends Error {
39
- constructor(message) {
40
- super(message);
41
- this.name = "MailKitError";
42
- Object.setPrototypeOf(this, new.target.prototype);
43
- }
47
+ constructor(message) {
48
+ super(message);
49
+ this.name = "MailKitError";
50
+ Object.setPrototypeOf(this, new.target.prototype);
51
+ }
44
52
  };
53
+ /**
54
+ * Thrown when transport configuration is missing or invalid.
55
+ */
45
56
  var ConfigurationError = class extends MailKitError {
46
- constructor(message) {
47
- super(message);
48
- this.name = "ConfigurationError";
49
- Object.setPrototypeOf(this, new.target.prototype);
50
- }
57
+ constructor(message) {
58
+ super(message);
59
+ this.name = "ConfigurationError";
60
+ Object.setPrototypeOf(this, new.target.prototype);
61
+ }
51
62
  };
63
+ /**
64
+ * Thrown when an email transport fails to dispatch an email.
65
+ */
52
66
  var TransportError = class extends MailKitError {
53
- transportName;
54
- statusCode;
55
- responseBody;
56
- cause;
57
- constructor(message, options) {
58
- super(message);
59
- this.name = "TransportError";
60
- this.transportName = options.transportName;
61
- this.statusCode = options.statusCode;
62
- this.responseBody = options.responseBody;
63
- this.cause = options.cause;
64
- Object.setPrototypeOf(this, new.target.prototype);
65
- }
67
+ transportName;
68
+ statusCode;
69
+ responseBody;
70
+ /** Parsed raw provider response, when available. */
71
+ rawResponse;
72
+ cause;
73
+ constructor(message, options) {
74
+ super(message);
75
+ this.name = "TransportError";
76
+ this.transportName = options.transportName;
77
+ this.statusCode = options.statusCode;
78
+ this.responseBody = options.responseBody;
79
+ this.rawResponse = options.rawResponse;
80
+ this.cause = options.cause;
81
+ Object.setPrototypeOf(this, new.target.prototype);
82
+ }
66
83
  };
84
+ /**
85
+ * Thrown when template rendering or DTO validation fails.
86
+ */
67
87
  var TemplateError = class extends MailKitError {
68
- constructor(message) {
69
- super(message);
70
- this.name = "TemplateError";
71
- Object.setPrototypeOf(this, new.target.prototype);
72
- }
88
+ constructor(message) {
89
+ super(message);
90
+ this.name = "TemplateError";
91
+ Object.setPrototypeOf(this, new.target.prototype);
92
+ }
73
93
  };
74
94
 
75
- // src/renderers/utils/html-to-plaintext.ts
95
+ //#endregion
96
+ //#region src/renderers/utils/html-to-plaintext.ts
97
+ /**
98
+ * Decodes common HTML entities into their plain text equivalents.
99
+ */
76
100
  function decodeHtmlEntities(text) {
77
- return text.replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&quot;/gi, '"').replace(/&#39;/gi, "'").replace(/&copy;/gi, "\xA9").replace(/&reg;/gi, "\xAE").replace(/&trade;/gi, "\u2122");
101
+ return text.replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&quot;/gi, "\"").replace(/&#39;/gi, "'").replace(/&copy;/gi, "©").replace(/&reg;/gi, "®").replace(/&trade;/gi, "™");
78
102
  }
103
+ /**
104
+ * Strips HTML tags and normalizes whitespace into readable plain text.
105
+ * Converts <br>, <p>, and <div> into appropriate line breaks.
106
+ */
79
107
  function htmlToPlainText(html) {
80
- if (!html) return "";
81
- return decodeHtmlEntities(
82
- html.replace(/<br\s*\/?>/gi, "\n").replace(/<\/p>/gi, "\n\n").replace(/<\/div>/gi, "\n").replace(/<\/h[1-6]>/gi, "\n\n").replace(/<[^>]*>/g, "")
83
- ).replace(/[ \t]+/g, " ").replace(/\n\s*\n\s*\n+/g, "\n\n").trim();
108
+ if (!html) return "";
109
+ return decodeHtmlEntities(html.replace(/<br\s*\/?>/gi, "\n").replace(/<\/p>/gi, "\n\n").replace(/<\/div>/gi, "\n").replace(/<\/h[1-6]>/gi, "\n\n").replace(/<[^>]*>/g, "")).replace(/[ \t]+/g, " ").replace(/\n\s*\n\s*\n+/g, "\n\n").trim();
84
110
  }
85
111
 
86
- // src/renderers/default/default-renderer.ts
112
+ //#endregion
113
+ //#region src/renderers/default/default-renderer.ts
114
+ /**
115
+ * Validates whether a string is a valid HTTP or HTTPS URL.
116
+ */
87
117
  function isValidHttpUrl(urlString) {
88
- if (!urlString || typeof urlString !== "string") return false;
89
- try {
90
- const url = new URL(urlString.trim());
91
- return (url.protocol === "http:" || url.protocol === "https:") && url.hostname.length > 0;
92
- } catch {
93
- return false;
94
- }
118
+ if (!urlString || typeof urlString !== "string") return false;
119
+ try {
120
+ const url = new URL(urlString.trim());
121
+ return (url.protocol === "http:" || url.protocol === "https:") && url.hostname.length > 0;
122
+ } catch {
123
+ return false;
124
+ }
95
125
  }
126
+ /**
127
+ * Builds a plain-text fallback string from an email DTO.
128
+ */
96
129
  function buildPlainText(dto) {
97
- if (dto.noHtmlMessage) {
98
- return dto.noHtmlMessage;
99
- }
100
- const divider = "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500";
101
- const parts = [];
102
- if (dto.header) {
103
- parts.push(dto.header, divider);
104
- }
105
- if (dto.body) {
106
- parts.push(htmlToPlainText(dto.body));
107
- }
108
- if (dto.otpCode) {
109
- parts.push(`Verification Code: ${dto.otpCode}`);
110
- }
111
- if (dto.actionText && dto.actionUrl) {
112
- parts.push(`${dto.actionText}: ${dto.actionUrl}`);
113
- }
114
- if (dto.extraMessage) {
115
- parts.push(htmlToPlainText(dto.extraMessage));
116
- }
117
- if (dto.footer) {
118
- parts.push(`${divider}
119
- ${htmlToPlainText(dto.footer)}`);
120
- }
121
- return parts.join("\n\n");
130
+ if (dto.noHtmlMessage) return dto.noHtmlMessage;
131
+ const divider = "──────────────────────────────";
132
+ const parts = [];
133
+ if (dto.header) parts.push(dto.header, divider);
134
+ if (dto.body) parts.push(htmlToPlainText(dto.body));
135
+ if (dto.otpCode) parts.push(`Verification Code: ${dto.otpCode}`);
136
+ if (dto.actionText && dto.actionUrl) parts.push(`${dto.actionText}: ${dto.actionUrl}`);
137
+ if (dto.extraMessage) parts.push(htmlToPlainText(dto.extraMessage));
138
+ if (dto.footer) parts.push(`${divider}\n${htmlToPlainText(dto.footer)}`);
139
+ return parts.join("\n\n");
122
140
  }
141
+ /**
142
+ * Builds a responsive, styled HTML email document from an email DTO.
143
+ */
123
144
  function buildHtml(dto, options = {}) {
124
- const primaryColor = options.primaryColor || "#4f46e5";
125
- const fontFamily = options.fontFamily || "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
126
- const maxWidth = options.maxWidth || "600px";
127
- const parts = [
128
- `<!DOCTYPE html>`,
129
- `<html lang="en">`,
130
- `<head>`,
131
- `<meta charset="UTF-8">`,
132
- `<meta name="viewport" content="width=device-width, initial-scale=1.0">`,
133
- `<title>${dto.subject}</title>`,
134
- `</head>`,
135
- `<body style="margin:0;padding:24px 16px;background-color:#f9fafb;font-family:${fontFamily};color:#1f2937;line-height:1.6;">`,
136
- `<div style="max-width:${maxWidth};margin:0 auto;background-color:#ffffff;padding:32px 28px;border-radius:8px;box-shadow:0 1px 3px rgba(0,0,0,0.1);border:1px solid #f3f4f6;">`
137
- ];
138
- const logoCandidate = dto.logoUrl ?? options.logoUrl;
139
- if (logoCandidate && isValidHttpUrl(logoCandidate)) {
140
- const validLogo = logoCandidate.trim();
141
- parts.push(
142
- `<div style="margin-bottom:24px;text-align:center;">`,
143
- ` <img src="${validLogo}" alt="${dto.fromName || "Logo"}" style="max-height:48px;max-width:200px;height:auto;width:auto;display:inline-block;border:0;outline:none;text-decoration:none;" />`,
144
- `</div>`
145
- );
146
- }
147
- if (dto.imageUrl) {
148
- parts.push(
149
- `<div style="margin-bottom:24px;text-align:center;">`,
150
- ` <img src="${dto.imageUrl}" alt="Header" style="max-width:100%;height:auto;border-radius:6px;" />`,
151
- `</div>`
152
- );
153
- }
154
- if (dto.header) {
155
- parts.push(
156
- `<h2 style="margin:0 0 16px;font-size:1.5rem;font-weight:700;color:#111827;letter-spacing:-0.025em;">${dto.header}</h2>`
157
- );
158
- }
159
- if (dto.body) {
160
- parts.push(`<div style="margin:0 0 20px;font-size:1rem;color:#374151;">${dto.body}</div>`);
161
- }
162
- if (dto.otpCode) {
163
- parts.push(
164
- `<div style="margin:24px 0;padding:20px;background-color:#f3f4f6;border-radius:8px;text-align:center;">`,
165
- ` <span style="font-size:2rem;letter-spacing:0.5rem;font-weight:700;color:#111827;font-family:monospace;">${dto.otpCode}</span>`,
166
- `</div>`
167
- );
168
- }
169
- if (dto.actionUrl && dto.actionText) {
170
- parts.push(
171
- `<div style="margin:24px 0;text-align:center;">`,
172
- ` <a href="${dto.actionUrl}" style="display:inline-block;padding:12px 28px;background-color:${primaryColor};color:#ffffff;border-radius:6px;text-decoration:none;font-weight:600;font-size:1rem;text-align:center;box-sizing:border-box;">${dto.actionText}</a>`,
173
- `</div>`
174
- );
175
- }
176
- if (dto.extraMessage) {
177
- parts.push(
178
- `<div style="margin:20px 0 0;font-size:0.875rem;color:#6b7280;line-height:1.5;">${dto.extraMessage}</div>`
179
- );
180
- }
181
- if (dto.footer) {
182
- parts.push(
183
- `<div style="margin-top:32px;padding-top:20px;border-top:1px solid #e5e7eb;font-size:0.75rem;color:#9ca3af;text-align:center;">${dto.footer}</div>`
184
- );
185
- }
186
- parts.push(`</div>`, `</body>`, `</html>`);
187
- return parts.join("\n");
145
+ const primaryColor = options.primaryColor || "#4f46e5";
146
+ const fontFamily = options.fontFamily || "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
147
+ const maxWidth = options.maxWidth || "600px";
148
+ const parts = [
149
+ `<!DOCTYPE html>`,
150
+ `<html lang="en">`,
151
+ `<head>`,
152
+ `<meta charset="UTF-8">`,
153
+ `<meta name="viewport" content="width=device-width, initial-scale=1.0">`,
154
+ `<title>${dto.subject}</title>`,
155
+ `</head>`,
156
+ `<body style="margin:0;padding:24px 16px;background-color:#f9fafb;font-family:${fontFamily};color:#1f2937;line-height:1.6;">`,
157
+ `<div style="max-width:${maxWidth};margin:0 auto;background-color:#ffffff;padding:32px 28px;border-radius:8px;box-shadow:0 1px 3px rgba(0,0,0,0.1);border:1px solid #f3f4f6;">`
158
+ ];
159
+ const logoCandidate = dto.logoUrl ?? options.logoUrl;
160
+ if (logoCandidate && isValidHttpUrl(logoCandidate)) {
161
+ const validLogo = logoCandidate.trim();
162
+ parts.push(`<div style="margin-bottom:24px;text-align:center;">`, ` <img src="${validLogo}" alt="${dto.fromName || "Logo"}" style="max-height:48px;max-width:200px;height:auto;width:auto;display:inline-block;border:0;outline:none;text-decoration:none;" />`, `</div>`);
163
+ }
164
+ if (dto.imageUrl) parts.push(`<div style="margin-bottom:24px;text-align:center;">`, ` <img src="${dto.imageUrl}" alt="Header" style="max-width:100%;height:auto;border-radius:6px;" />`, `</div>`);
165
+ if (dto.header) parts.push(`<h2 style="margin:0 0 16px;font-size:1.5rem;font-weight:700;color:#111827;letter-spacing:-0.025em;">${dto.header}</h2>`);
166
+ if (dto.body) parts.push(`<div style="margin:0 0 20px;font-size:1rem;color:#374151;">${dto.body}</div>`);
167
+ if (dto.otpCode) parts.push(`<div style="margin:24px 0;padding:20px;background-color:#f3f4f6;border-radius:8px;text-align:center;">`, ` <span style="font-size:2rem;letter-spacing:0.5rem;font-weight:700;color:#111827;font-family:monospace;">${dto.otpCode}</span>`, `</div>`);
168
+ if (dto.actionUrl && dto.actionText) parts.push(`<div style="margin:24px 0;text-align:center;">`, ` <a href="${dto.actionUrl}" style="display:inline-block;padding:12px 28px;background-color:${primaryColor};color:#ffffff;border-radius:6px;text-decoration:none;font-weight:600;font-size:1rem;text-align:center;box-sizing:border-box;">${dto.actionText}</a>`, `</div>`);
169
+ if (dto.extraMessage) parts.push(`<div style="margin:20px 0 0;font-size:0.875rem;color:#6b7280;line-height:1.5;">${dto.extraMessage}</div>`);
170
+ if (dto.footer) parts.push(`<div style="margin-top:32px;padding-top:20px;border-top:1px solid #e5e7eb;font-size:0.75rem;color:#9ca3af;text-align:center;">${dto.footer}</div>`);
171
+ parts.push(`</div>`, `</body>`, `</html>`);
172
+ return parts.join("\n");
188
173
  }
174
+ /**
175
+ * Default HTML and plain-text email renderer for ts-mailkit.
176
+ */
189
177
  var DefaultEmailRenderer = class {
190
- options;
191
- constructor(options = {}) {
192
- this.options = options;
193
- }
194
- render(dto) {
195
- return {
196
- html: buildHtml(dto, this.options),
197
- text: buildPlainText(dto)
198
- };
199
- }
178
+ options;
179
+ constructor(options = {}) {
180
+ this.options = options;
181
+ }
182
+ render(dto) {
183
+ return {
184
+ html: buildHtml(dto, this.options),
185
+ text: buildPlainText(dto)
186
+ };
187
+ }
200
188
  };
201
189
 
202
- // src/core/client.ts
190
+ //#endregion
191
+ //#region src/core/client.ts
192
+ /**
193
+ * Main email client and orchestration service for ts-mailkit.
194
+ */
203
195
  var MailKit = class {
204
- transport;
205
- renderer;
206
- defaultFrom;
207
- defaultBrandName;
208
- brandNameResolver;
209
- constructor(options) {
210
- if (!options.transport) {
211
- throw new ConfigurationError("MailKit: A transport adapter (IEmailSender) is required.");
212
- }
213
- this.transport = options.transport;
214
- this.renderer = options.renderer ?? new DefaultEmailRenderer();
215
- this.defaultFrom = options.defaultFrom;
216
- this.defaultBrandName = options.defaultBrandName;
217
- this.brandNameResolver = options.brandNameResolver;
218
- }
219
- /**
220
- * Returns the underlying transport instance.
221
- */
222
- getTransport() {
223
- return this.transport;
224
- }
225
- /**
226
- * Renders an email DTO to HTML and plain text without dispatching.
227
- */
228
- async render(template) {
229
- return await this.renderer.render(template);
230
- }
231
- /**
232
- * Sends an email using a strongly-typed template DTO.
233
- *
234
- * Example:
235
- * ```ts
236
- * await mailer.send({
237
- * to: 'user@example.com',
238
- * template: myDto,
239
- * });
240
- * ```
241
- */
242
- async send(options) {
243
- const template = options.template;
244
- const recipientName = options.toName ?? template.userName;
245
- let resolvedFromName = options.fromName ?? template.fromName;
246
- if (!resolvedFromName && this.brandNameResolver) {
247
- resolvedFromName = await this.brandNameResolver();
248
- }
249
- if (!resolvedFromName) {
250
- resolvedFromName = this.defaultBrandName;
251
- }
252
- const rendered = await this.renderer.render(template);
253
- const plaintextBody = template.noHtmlMessage ?? rendered.text;
254
- let toRecipients;
255
- if (typeof options.to === "string" && recipientName) {
256
- toRecipients = { address: options.to, name: recipientName };
257
- } else {
258
- toRecipients = options.to;
259
- }
260
- let from = options.from ?? this.defaultFrom;
261
- if (resolvedFromName && from) {
262
- const normalizedFrom = normalizeRecipient(from);
263
- from = { address: normalizedFrom.address, name: resolvedFromName };
264
- }
265
- return await this.sendRaw({
266
- to: toRecipients,
267
- from,
268
- subject: template.subject,
269
- html: rendered.html,
270
- text: plaintextBody,
271
- cc: options.cc,
272
- bcc: options.bcc,
273
- replyTo: options.replyTo,
274
- attachments: options.attachments,
275
- headers: options.headers,
276
- tags: options.tags,
277
- metadata: options.metadata
278
- });
279
- }
280
- /**
281
- * Dispatches a raw, pre-rendered email directly through the transport.
282
- * If `options.text` is omitted, plain text is automatically derived from `options.html`.
283
- */
284
- async sendRaw(options) {
285
- const from = options.from ?? this.defaultFrom;
286
- const text = options.text ?? (options.html ? htmlToPlainText(options.html) : void 0);
287
- return await this.transport.send({
288
- ...options,
289
- from,
290
- text
291
- });
292
- }
196
+ transport;
197
+ renderer;
198
+ defaultFrom;
199
+ defaultBrandName;
200
+ brandNameResolver;
201
+ constructor(options) {
202
+ if (!options.transport) throw new ConfigurationError("MailKit: A transport adapter (IEmailSender) is required.");
203
+ this.transport = options.transport;
204
+ this.renderer = options.renderer ?? new DefaultEmailRenderer();
205
+ this.defaultFrom = options.defaultFrom;
206
+ this.defaultBrandName = options.defaultBrandName;
207
+ this.brandNameResolver = options.brandNameResolver;
208
+ }
209
+ /**
210
+ * Returns the underlying transport instance.
211
+ */
212
+ getTransport() {
213
+ return this.transport;
214
+ }
215
+ /**
216
+ * Renders an email DTO to HTML and plain text without dispatching.
217
+ */
218
+ async render(template) {
219
+ return await this.renderer.render(template);
220
+ }
221
+ /**
222
+ * Sends an email using a strongly-typed template DTO.
223
+ *
224
+ * Example:
225
+ * ```ts
226
+ * await mailer.sendMail({
227
+ * to: 'user@example.com',
228
+ * template: myDto,
229
+ * });
230
+ * ```
231
+ */
232
+ async sendMail(options) {
233
+ const template = options.template;
234
+ const recipientName = options.toName ?? template.userName;
235
+ const resolvedFromName = await this.resolveFromName(template, options.fromName);
236
+ const rendered = await this.renderer.render(template);
237
+ const plaintextBody = template.noHtmlMessage ?? rendered.text;
238
+ let toRecipients;
239
+ if (typeof options.to === "string" && recipientName) toRecipients = {
240
+ address: options.to,
241
+ name: recipientName
242
+ };
243
+ else toRecipients = options.to;
244
+ const from = this.applyFromName(options.from ?? this.defaultFrom, resolvedFromName);
245
+ return await this.sendRaw({
246
+ to: toRecipients,
247
+ from,
248
+ subject: template.subject,
249
+ html: rendered.html,
250
+ text: plaintextBody,
251
+ cc: options.cc,
252
+ bcc: options.bcc,
253
+ replyTo: options.replyTo,
254
+ attachments: options.attachments,
255
+ headers: options.headers,
256
+ tags: options.tags,
257
+ metadata: options.metadata
258
+ });
259
+ }
260
+ /**
261
+ * @deprecated Use {@link sendMail} instead.
262
+ */
263
+ async send(options) {
264
+ return await this.sendMail(options);
265
+ }
266
+ /**
267
+ * Sends a bulk email using a strongly-typed template DTO.
268
+ *
269
+ * The transport delivers an individual copy to each recipient, so
270
+ * recipients are not exposed to one another. Per-recipient personalization
271
+ * is available via {@link sendBulkKnownTemplate}.
272
+ *
273
+ * Example:
274
+ * ```ts
275
+ * await mailer.sendBulkMail({
276
+ * to: ['a@example.com', 'b@example.com'],
277
+ * template: myDto,
278
+ * });
279
+ * ```
280
+ */
281
+ async sendBulkMail(options) {
282
+ const transport = this.transport;
283
+ if (typeof transport.sendBulk !== "function") throw new ConfigurationError("MailKit: The configured transport does not support bulk sending (sendBulk).");
284
+ const template = options.template;
285
+ const resolvedFromName = await this.resolveFromName(template);
286
+ const rendered = await this.renderer.render(template);
287
+ const plaintextBody = template.noHtmlMessage ?? rendered.text;
288
+ const from = this.applyFromName(options.from ?? this.defaultFrom, resolvedFromName);
289
+ return await transport.sendBulk({
290
+ to: options.to,
291
+ from,
292
+ subject: template.subject,
293
+ html: rendered.html,
294
+ text: plaintextBody,
295
+ cc: options.cc,
296
+ bcc: options.bcc,
297
+ replyTo: options.replyTo,
298
+ attachments: options.attachments,
299
+ headers: options.headers,
300
+ tags: options.tags,
301
+ metadata: options.metadata,
302
+ trackClicks: options.trackClicks,
303
+ trackOpens: options.trackOpens
304
+ });
305
+ }
306
+ /**
307
+ * Sends a single email using a provider-side template.
308
+ */
309
+ async sendKnownTemplate(options) {
310
+ const transport = this.transport;
311
+ if (typeof transport.sendKnownTemplate !== "function") throw new ConfigurationError("MailKit: The configured transport does not support template sending (sendKnownTemplate).");
312
+ return await transport.sendKnownTemplate({
313
+ ...options,
314
+ from: options.from ?? this.defaultFrom
315
+ });
316
+ }
317
+ /**
318
+ * Sends a bulk email using a provider-side template with optional
319
+ * per-recipient merge data.
320
+ */
321
+ async sendBulkKnownTemplate(options) {
322
+ const transport = this.transport;
323
+ if (typeof transport.sendBulkKnownTemplate !== "function") throw new ConfigurationError("MailKit: The configured transport does not support bulk template sending (sendBulkKnownTemplate).");
324
+ return await transport.sendBulkKnownTemplate({
325
+ ...options,
326
+ from: options.from ?? this.defaultFrom
327
+ });
328
+ }
329
+ async resolveFromName(template, explicitFromName) {
330
+ let resolved = explicitFromName ?? template.fromName;
331
+ if (!resolved && this.brandNameResolver) resolved = await this.brandNameResolver();
332
+ if (!resolved) resolved = this.defaultBrandName;
333
+ return resolved;
334
+ }
335
+ applyFromName(from, fromName) {
336
+ if (fromName && from) return {
337
+ address: normalizeRecipient(from).address,
338
+ name: fromName
339
+ };
340
+ return from;
341
+ }
342
+ /**
343
+ * Dispatches a raw, pre-rendered email directly through the transport.
344
+ * If `options.text` is omitted, plain text is automatically derived from `options.html`.
345
+ */
346
+ async sendRaw(options) {
347
+ const from = options.from ?? this.defaultFrom;
348
+ const text = options.text ?? (options.html ? htmlToPlainText(options.html) : void 0);
349
+ return await this.transport.send({
350
+ ...options,
351
+ from,
352
+ text
353
+ });
354
+ }
293
355
  };
356
+ /**
357
+ * Convenience factory to create a MailKit client instance.
358
+ */
294
359
  function createMailKit(options) {
295
- return new MailKit(options);
360
+ return new MailKit(options);
296
361
  }
297
362
 
298
- // src/transports/zeptomail/zeptomail-sender.ts
299
- var ZeptoMailHttpSender = class {
300
- name = "zeptomail";
301
- apiUrl;
302
- authHeader;
303
- defaultFrom;
304
- fetchImpl;
305
- constructor(config) {
306
- if (!config.apiToken || typeof config.apiToken !== "string") {
307
- throw new ConfigurationError("ZeptoMailHttpSender: Missing or invalid apiToken.");
308
- }
309
- if (!config.from) {
310
- throw new ConfigurationError("ZeptoMailHttpSender: Missing required default from address.");
311
- }
312
- const host = (config.apiHost || "api.zeptomail.com").replace(/^https?:\/\//, "").replace(/\/+$/, "");
313
- this.apiUrl = `https://${host}/v1.1/email`;
314
- const token = config.apiToken.trim();
315
- this.authHeader = token.startsWith("Zoho-") ? token : `Zoho-enczapikey ${token}`;
316
- this.defaultFrom = normalizeRecipient(config.from);
317
- if (!this.defaultFrom.address) {
318
- throw new ConfigurationError("ZeptoMailHttpSender: Configured from address must not be empty.");
319
- }
320
- this.fetchImpl = config.fetch ?? globalThis.fetch;
321
- if (typeof this.fetchImpl !== "function") {
322
- throw new ConfigurationError(
323
- "ZeptoMailHttpSender: No global fetch implementation found. Pass a custom fetch to ZeptoMailHttpConfig if running on Node < 18."
324
- );
325
- }
326
- }
327
- /**
328
- * Dispatches an email using Zoho ZeptoMail API v1.1.
329
- */
330
- async send(options) {
331
- const toRecipients = normalizeRecipients(options.to);
332
- if (toRecipients.length === 0) {
333
- throw new TransportError("ZeptoMailHttpSender: At least one recipient (to) must be specified.", {
334
- transportName: this.name
335
- });
336
- }
337
- const resolvedFrom = options.from ? normalizeRecipient(options.from) : this.defaultFrom;
338
- const payload = {
339
- from: {
340
- address: resolvedFrom.address,
341
- name: resolvedFrom.name
342
- },
343
- to: toRecipients.map((r) => ({
344
- email_address: {
345
- address: r.address,
346
- name: r.name || ""
347
- }
348
- })),
349
- subject: options.subject,
350
- htmlbody: options.html,
351
- textbody: options.text
352
- };
353
- if (options.cc) {
354
- const ccList = normalizeRecipients(options.cc);
355
- if (ccList.length > 0) {
356
- payload.cc = ccList.map((r) => ({
357
- email_address: { address: r.address, name: r.name || "" }
358
- }));
359
- }
360
- }
361
- if (options.bcc) {
362
- const bccList = normalizeRecipients(options.bcc);
363
- if (bccList.length > 0) {
364
- payload.bcc = bccList.map((r) => ({
365
- email_address: { address: r.address, name: r.name || "" }
366
- }));
367
- }
368
- }
369
- if (options.replyTo) {
370
- const replyToList = normalizeRecipients(options.replyTo);
371
- if (replyToList.length > 0) {
372
- payload.reply_to = replyToList.map((r) => ({
373
- address: r.address,
374
- name: r.name
375
- }));
376
- }
377
- }
378
- if (options.attachments && options.attachments.length > 0) {
379
- payload.attachments = options.attachments.map((att) => {
380
- let contentBase64;
381
- if (typeof att.content === "string") {
382
- contentBase64 = att.content;
383
- } else {
384
- if (typeof Buffer !== "undefined") {
385
- contentBase64 = Buffer.from(att.content).toString("base64");
386
- } else {
387
- let binary = "";
388
- const bytes = new Uint8Array(att.content);
389
- for (let i = 0; i < bytes.byteLength; i++) {
390
- binary += String.fromCharCode(bytes[i]);
391
- }
392
- contentBase64 = btoa(binary);
393
- }
394
- }
395
- return {
396
- name: att.filename,
397
- content: contentBase64,
398
- mime_type: att.mimeType || att.contentType || "application/octet-stream",
399
- cid: att.cid
400
- };
401
- });
402
- }
403
- let response;
404
- try {
405
- response = await this.fetchImpl(this.apiUrl, {
406
- method: "POST",
407
- headers: {
408
- Accept: "application/json",
409
- "Content-Type": "application/json",
410
- Authorization: this.authHeader
411
- },
412
- body: JSON.stringify(payload)
413
- });
414
- } catch (err) {
415
- throw new TransportError(`ZeptoMailHttpSender: Network request failed: ${err instanceof Error ? err.message : String(err)}`, {
416
- transportName: this.name,
417
- cause: err
418
- });
419
- }
420
- const responseText = await response.text();
421
- let responseData;
422
- try {
423
- responseData = responseText ? JSON.parse(responseText) : {};
424
- } catch {
425
- responseData = { raw: responseText };
426
- }
427
- if (!response.ok) {
428
- const errorMessage = responseData?.error?.message || responseData?.message || `HTTP ${response.status}: ${responseText || response.statusText}`;
429
- throw new TransportError(`ZeptoMailHttpSender: Failed to send email - ${errorMessage}`, {
430
- transportName: this.name,
431
- statusCode: response.status,
432
- responseBody: responseText
433
- });
434
- }
435
- const messageId = responseData?.data?.[0]?.message_id;
436
- return {
437
- success: true,
438
- messageId,
439
- response: responseData
440
- };
441
- }
363
+ //#endregion
364
+ //#region src/transports/cpaas/cpaas-sender.ts
365
+ /**
366
+ * Zoho CPaaS (formerly ZeptoMail) transactional email HTTP transport adapter.
367
+ *
368
+ * Uses the standard global `fetch` API for zero-dependency, universal edge
369
+ * compatibility (Node.js, Bun, Deno, Cloudflare Workers).
370
+ *
371
+ * Supports:
372
+ * - `send` — single raw email (`POST /v1.1/email`)
373
+ * - `sendBulk` — batch raw email (`POST /v1.1/email/batch`)
374
+ * - `sendKnownTemplate` — single template email (`POST /v1.1/email/template`)
375
+ * - `sendBulkKnownTemplate` — batch template email (`POST /v1.1/email/template/batch`)
376
+ */
377
+ var CpaasHttpSender = class {
378
+ name = "cpaas";
379
+ apiBase;
380
+ authHeader;
381
+ defaultFrom;
382
+ preferTemplateAlias;
383
+ fetchImpl;
384
+ constructor(config) {
385
+ if (!config.apiToken || typeof config.apiToken !== "string") throw new ConfigurationError("CpaasHttpSender: Missing or invalid apiToken.");
386
+ if (!config.from) throw new ConfigurationError("CpaasHttpSender: Missing required default from address.");
387
+ const host = (config.apiHost || "cpaas.zoho.com").replace(/^https?:\/\//, "").replace(/\/+$/, "");
388
+ this.apiBase = `https://${host}/v1.1`;
389
+ const token = config.apiToken.trim();
390
+ this.authHeader = token.startsWith("Zoho-") ? token : `Zoho-enczapikey ${token}`;
391
+ this.defaultFrom = normalizeRecipient(config.from);
392
+ if (!this.defaultFrom.address) throw new ConfigurationError("CpaasHttpSender: Configured from address must not be empty.");
393
+ this.preferTemplateAlias = config.preferTemplateAlias ?? false;
394
+ const fetchImpl = config.fetch ?? globalThis.fetch;
395
+ if (typeof fetchImpl !== "function") throw new ConfigurationError("CpaasHttpSender: No global fetch implementation found. Pass a custom fetch to CpaasHttpConfig if running on Node < 18.");
396
+ this.fetchImpl = fetchImpl.bind(globalThis);
397
+ }
398
+ /**
399
+ * Dispatches a single raw email using Zoho CPaaS API.
400
+ */
401
+ async send(options) {
402
+ const payload = this.buildSendPayload(options);
403
+ return await this.post(`${this.apiBase}/email`, payload);
404
+ }
405
+ /**
406
+ * Dispatches a batch of a single raw email content to many recipients.
407
+ * The provider delivers an individual copy to each recipient.
408
+ */
409
+ async sendBulk(options) {
410
+ const payload = this.buildSendPayload(options);
411
+ return await this.post(`${this.apiBase}/email/batch`, payload);
412
+ }
413
+ /**
414
+ * Dispatches a single email using a provider-side template.
415
+ */
416
+ async sendKnownTemplate(options) {
417
+ const payload = this.buildTemplatePayload(options);
418
+ return await this.post(`${this.apiBase}/email/template`, payload);
419
+ }
420
+ /**
421
+ * Dispatches a batch of emails using a provider-side template, with
422
+ * optional per-recipient merge data.
423
+ */
424
+ async sendBulkKnownTemplate(options) {
425
+ const payload = this.buildBatchTemplatePayload(options);
426
+ return await this.post(`${this.apiBase}/email/template/batch`, payload);
427
+ }
428
+ buildSendPayload(options) {
429
+ const toRecipients = normalizeRecipients(options.to);
430
+ if (toRecipients.length === 0) throw new TransportError("CpaasHttpSender: At least one recipient (to) must be specified.", { transportName: this.name });
431
+ const resolvedFrom = options.from ? normalizeRecipient(options.from) : this.defaultFrom;
432
+ const payload = {
433
+ from: {
434
+ address: resolvedFrom.address,
435
+ name: resolvedFrom.name
436
+ },
437
+ to: toRecipients.map((r) => ({ email_address: {
438
+ address: r.address,
439
+ name: r.name || ""
440
+ } })),
441
+ subject: options.subject,
442
+ htmlbody: options.html,
443
+ textbody: options.text
444
+ };
445
+ this.applyCommon(payload, options);
446
+ return payload;
447
+ }
448
+ buildTemplatePayload(options) {
449
+ const toRecipients = normalizeRecipients(options.to);
450
+ if (toRecipients.length === 0) throw new TransportError("CpaasHttpSender: At least one recipient (to) must be specified.", { transportName: this.name });
451
+ const resolvedFrom = options.from ? normalizeRecipient(options.from) : this.defaultFrom;
452
+ const payload = {
453
+ ...this.templateRef(options.templateId),
454
+ from: {
455
+ address: resolvedFrom.address,
456
+ name: resolvedFrom.name
457
+ },
458
+ to: toRecipients.map((r) => ({ email_address: {
459
+ address: r.address,
460
+ name: r.name || ""
461
+ } }))
462
+ };
463
+ if (options.mergeInfo) payload.merge_info = options.mergeInfo;
464
+ this.applyCommon(payload, options);
465
+ return payload;
466
+ }
467
+ buildBatchTemplatePayload(options) {
468
+ if (!options.to || options.to.length === 0) throw new TransportError("CpaasHttpSender: At least one recipient (to) must be specified.", { transportName: this.name });
469
+ const resolvedFrom = options.from ? normalizeRecipient(options.from) : this.defaultFrom;
470
+ const payload = {
471
+ ...this.templateRef(options.templateId),
472
+ from: {
473
+ address: resolvedFrom.address,
474
+ name: resolvedFrom.name
475
+ },
476
+ to: options.to.map((r) => ({
477
+ email_address: {
478
+ address: r.address,
479
+ name: r.name || ""
480
+ },
481
+ ...r.mergeInfo ? { merge_info: r.mergeInfo } : {}
482
+ }))
483
+ };
484
+ this.applyCommon(payload, options);
485
+ return payload;
486
+ }
487
+ templateRef(templateId) {
488
+ return this.preferTemplateAlias ? { template_alias: templateId } : { template_key: templateId };
489
+ }
490
+ applyCommon(payload, options) {
491
+ if (options.cc) {
492
+ const ccList = normalizeRecipients(options.cc);
493
+ if (ccList.length > 0) payload.cc = ccList.map((r) => ({ email_address: {
494
+ address: r.address,
495
+ name: r.name || ""
496
+ } }));
497
+ }
498
+ if (options.bcc) {
499
+ const bccList = normalizeRecipients(options.bcc);
500
+ if (bccList.length > 0) payload.bcc = bccList.map((r) => ({ email_address: {
501
+ address: r.address,
502
+ name: r.name || ""
503
+ } }));
504
+ }
505
+ if (options.replyTo) {
506
+ const replyToList = normalizeRecipients(options.replyTo);
507
+ if (replyToList.length > 0) payload.reply_to = replyToList.map((r) => ({
508
+ address: r.address,
509
+ name: r.name
510
+ }));
511
+ }
512
+ if (options.attachments && options.attachments.length > 0) payload.attachments = options.attachments.map((att) => this.toAttachmentPayload(att));
513
+ if (options.trackClicks !== void 0) payload.track_clicks = options.trackClicks;
514
+ if (options.trackOpens !== void 0) payload.track_opens = options.trackOpens;
515
+ if (options.bounceAddress !== void 0) payload.bounce_address = options.bounceAddress;
516
+ if (options.clientReference !== void 0) payload.client_reference = options.clientReference;
517
+ }
518
+ toAttachmentPayload(att) {
519
+ let contentBase64;
520
+ if (typeof att.content === "string") contentBase64 = att.content;
521
+ else if (typeof Buffer !== "undefined") contentBase64 = Buffer.from(att.content).toString("base64");
522
+ else {
523
+ let binary = "";
524
+ const bytes = new Uint8Array(att.content);
525
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
526
+ contentBase64 = btoa(binary);
527
+ }
528
+ return {
529
+ name: att.filename,
530
+ content: contentBase64,
531
+ mime_type: att.mimeType || att.contentType || "application/octet-stream",
532
+ cid: att.cid
533
+ };
534
+ }
535
+ async post(url, payload) {
536
+ let response;
537
+ try {
538
+ response = await this.fetchImpl(url, {
539
+ method: "POST",
540
+ headers: {
541
+ Accept: "application/json",
542
+ "Content-Type": "application/json",
543
+ Authorization: this.authHeader
544
+ },
545
+ body: JSON.stringify(payload)
546
+ });
547
+ } catch (err) {
548
+ throw new TransportError(`CpaasHttpSender: Network request failed: ${err instanceof Error ? err.message : String(err)}`, {
549
+ transportName: this.name,
550
+ cause: err
551
+ });
552
+ }
553
+ const responseText = await response.text();
554
+ let responseData;
555
+ try {
556
+ responseData = responseText ? JSON.parse(responseText) : {};
557
+ } catch {
558
+ responseData = { raw: responseText };
559
+ }
560
+ if (!response.ok) {
561
+ const errorMessage = responseData?.data?.message || responseData?.error?.message || responseData?.message || `HTTP ${response.status}: ${responseText || response.statusText}`;
562
+ throw new TransportError(`CpaasHttpSender: Failed to send email - ${errorMessage}`, {
563
+ transportName: this.name,
564
+ statusCode: response.status,
565
+ responseBody: responseText,
566
+ rawResponse: responseData
567
+ });
568
+ }
569
+ return {
570
+ success: true,
571
+ messageId: responseData?.data?.[0]?.message_id,
572
+ rawResponse: responseData,
573
+ response: responseData
574
+ };
575
+ }
442
576
  };
443
577
 
444
- // src/transports/memory/memory-sender.ts
578
+ //#endregion
579
+ //#region src/transports/memory/memory-sender.ts
580
+ /**
581
+ * In-memory email sender for automated testing, local development, and CI environments.
582
+ * Captures all dispatched emails and provides inspection methods.
583
+ */
445
584
  var MemoryEmailSender = class {
446
- name = "memory";
447
- sentMails = [];
448
- nextId = 1;
449
- async send(options) {
450
- this.sentMails.push({ ...options });
451
- const messageId = `mem-${this.nextId++}-${Date.now()}`;
452
- return {
453
- success: true,
454
- messageId,
455
- response: { id: messageId }
456
- };
457
- }
458
- /**
459
- * Returns a copy of all emails sent through this transport instance.
460
- */
461
- getSentMails() {
462
- return [...this.sentMails];
463
- }
464
- /**
465
- * Returns the most recent email sent, or undefined if no emails have been sent.
466
- */
467
- getLastMail() {
468
- return this.sentMails.length > 0 ? { ...this.sentMails[this.sentMails.length - 1] } : void 0;
469
- }
470
- /**
471
- * Clears all recorded sent emails.
472
- */
473
- clear() {
474
- this.sentMails = [];
475
- }
476
- /**
477
- * Returns the total count of sent emails.
478
- */
479
- count() {
480
- return this.sentMails.length;
481
- }
585
+ name = "memory";
586
+ sentMails = [];
587
+ sentBulkMails = [];
588
+ sentTemplateMails = [];
589
+ sentBulkTemplateMails = [];
590
+ nextId = 1;
591
+ result(prefix) {
592
+ const id = this.nextId++;
593
+ const messageId = prefix ? `mem-${prefix}-${id}-${Date.now()}` : `mem-${id}-${Date.now()}`;
594
+ const rawResponse = { id: messageId };
595
+ return {
596
+ success: true,
597
+ messageId,
598
+ rawResponse,
599
+ response: rawResponse
600
+ };
601
+ }
602
+ async send(options) {
603
+ this.sentMails.push({ ...options });
604
+ return this.result();
605
+ }
606
+ async sendBulk(options) {
607
+ this.sentBulkMails.push({ ...options });
608
+ return this.result("bulk");
609
+ }
610
+ async sendKnownTemplate(options) {
611
+ this.sentTemplateMails.push({ ...options });
612
+ return this.result("tpl");
613
+ }
614
+ async sendBulkKnownTemplate(options) {
615
+ this.sentBulkTemplateMails.push({ ...options });
616
+ return this.result("bulk-tpl");
617
+ }
618
+ /**
619
+ * Returns a copy of all single emails sent through this transport instance.
620
+ */
621
+ getSentMails() {
622
+ return [...this.sentMails];
623
+ }
624
+ /**
625
+ * Returns the most recent single email sent, or undefined if none have been sent.
626
+ */
627
+ getLastMail() {
628
+ return this.sentMails.length > 0 ? { ...this.sentMails[this.sentMails.length - 1] } : void 0;
629
+ }
630
+ /**
631
+ * Returns a copy of all bulk emails sent through this transport instance.
632
+ */
633
+ getSentBulkMails() {
634
+ return [...this.sentBulkMails];
635
+ }
636
+ /**
637
+ * Returns a copy of all single template emails sent through this transport instance.
638
+ */
639
+ getSentTemplateMails() {
640
+ return [...this.sentTemplateMails];
641
+ }
642
+ /**
643
+ * Returns a copy of all bulk template emails sent through this transport instance.
644
+ */
645
+ getSentBulkTemplateMails() {
646
+ return [...this.sentBulkTemplateMails];
647
+ }
648
+ /**
649
+ * Clears all recorded emails.
650
+ */
651
+ clear() {
652
+ this.sentMails = [];
653
+ this.sentBulkMails = [];
654
+ this.sentTemplateMails = [];
655
+ this.sentBulkTemplateMails = [];
656
+ }
657
+ /**
658
+ * Returns the total count of single emails sent.
659
+ */
660
+ count() {
661
+ return this.sentMails.length;
662
+ }
482
663
  };
483
664
 
484
- // src/transports/console/console-sender.ts
665
+ //#endregion
666
+ //#region src/transports/console/console-sender.ts
667
+ /**
668
+ * Console logger transport that prints dispatched emails to stdout/stderr.
669
+ * Ideal for development and debugging.
670
+ */
485
671
  var ConsoleEmailSender = class {
486
- name = "console";
487
- log;
488
- includeHtml;
489
- nextId = 1;
490
- constructor(options = {}) {
491
- this.log = options.logger ?? console.log;
492
- this.includeHtml = options.includeHtml ?? false;
493
- }
494
- async send(options) {
495
- const to = normalizeRecipients(options.to).map((r) => r.name ? `${r.name} <${r.address}>` : r.address).join(", ");
496
- const from = options.from ? JSON.stringify(options.from) : "(default)";
497
- const messageId = `console-${this.nextId++}-${Date.now()}`;
498
- const separator = "\u2500".repeat(60);
499
- const lines = [
500
- `
501
- \u250C${separator}\u2510`,
502
- `\u2502 [ts-mailkit:console] DISPATCHED EMAIL (${messageId})`,
503
- `\u251C${separator}\u2524`,
504
- `\u2502 From: ${from}`,
505
- `\u2502 To: ${to}`,
506
- `\u2502 Subject: ${options.subject}`,
507
- `\u251C${separator}\u2524`
508
- ];
509
- if (options.text) {
510
- lines.push("\u2502 Text Body:");
511
- for (const line of options.text.split("\n")) {
512
- lines.push(`\u2502 ${line}`);
513
- }
514
- }
515
- if (this.includeHtml && options.html) {
516
- lines.push("\u2502 HTML Body:");
517
- for (const line of options.html.split("\n")) {
518
- lines.push(`\u2502 ${line}`);
519
- }
520
- }
521
- lines.push(`\u2514${separator}\u2518
522
- `);
523
- this.log(lines.join("\n"));
524
- return {
525
- success: true,
526
- messageId,
527
- response: { logged: true }
528
- };
529
- }
672
+ name = "console";
673
+ log;
674
+ includeHtml;
675
+ nextId = 1;
676
+ constructor(options = {}) {
677
+ this.log = options.logger ?? console.log;
678
+ this.includeHtml = options.includeHtml ?? false;
679
+ }
680
+ async send(options) {
681
+ return this.logDispatch({
682
+ kind: "EMAIL",
683
+ to: options.to,
684
+ from: options.from,
685
+ subject: options.subject,
686
+ text: options.text,
687
+ html: options.html
688
+ });
689
+ }
690
+ async sendBulk(options) {
691
+ return this.logDispatch({
692
+ kind: "BULK EMAIL",
693
+ to: options.to,
694
+ from: options.from,
695
+ subject: options.subject,
696
+ text: options.text,
697
+ html: options.html
698
+ });
699
+ }
700
+ async sendKnownTemplate(options) {
701
+ return this.logDispatch({
702
+ kind: "TEMPLATE EMAIL",
703
+ to: options.to,
704
+ from: options.from,
705
+ templateId: options.templateId
706
+ });
707
+ }
708
+ async sendBulkKnownTemplate(options) {
709
+ return this.logDispatch({
710
+ kind: "BULK TEMPLATE EMAIL",
711
+ to: options.to,
712
+ from: options.from,
713
+ templateId: options.templateId
714
+ });
715
+ }
716
+ logDispatch(entry) {
717
+ const to = normalizeRecipients(entry.to).map((r) => r.name ? `${r.name} <${r.address}>` : r.address).join(", ");
718
+ const from = entry.from ? JSON.stringify(entry.from) : "(default)";
719
+ const messageId = `console-${this.nextId++}-${Date.now()}`;
720
+ const separator = "─".repeat(60);
721
+ const lines = [
722
+ `\n┌${separator}┐`,
723
+ `│ [ts-mailkit:console] DISPATCHED ${entry.kind} (${messageId})`,
724
+ `├${separator}┤`,
725
+ `│ From: ${from}`,
726
+ `│ To: ${to}`
727
+ ];
728
+ if (entry.subject !== void 0) lines.push(`│ Subject: ${entry.subject}`);
729
+ if (entry.templateId !== void 0) lines.push(`│ Template: ${entry.templateId}`);
730
+ lines.push(`├${separator}┤`);
731
+ if (entry.text) {
732
+ lines.push("│ Text Body:");
733
+ for (const line of entry.text.split("\n")) lines.push(`│ ${line}`);
734
+ }
735
+ if (this.includeHtml && entry.html) {
736
+ lines.push("│ HTML Body:");
737
+ for (const line of entry.html.split("\n")) lines.push(`│ ${line}`);
738
+ }
739
+ lines.push(`└${separator}┘\n`);
740
+ this.log(lines.join("\n"));
741
+ const rawResponse = { logged: true };
742
+ return {
743
+ success: true,
744
+ messageId,
745
+ rawResponse,
746
+ response: rawResponse
747
+ };
748
+ }
530
749
  };
531
750
 
532
- // src/templates/factory.ts
533
- var DEFAULT_SECURITY_MESSAGE = "If you did not request this, please ignore this email or contact support if you have concerns.";
751
+ //#endregion
752
+ //#region src/templates/factory.ts
753
+ const DEFAULT_SECURITY_MESSAGE = "If you did not request this, please ignore this email or contact support if you have concerns.";
534
754
  function defaultFooter(brandName) {
535
- return `&copy; ${(/* @__PURE__ */ new Date()).getFullYear()} ${brandName}. All rights reserved.`;
755
+ return `&copy; ${(/* @__PURE__ */ new Date()).getFullYear()} ${brandName}. All rights reserved.`;
536
756
  }
537
- var EmailTemplateFactory = class _EmailTemplateFactory {
538
- defaultBrandName;
539
- defaultSecurityMessage;
540
- footerResolver;
541
- defaultLogoUrl;
542
- constructor(config = {}) {
543
- this.defaultBrandName = config.brandName || "Application";
544
- this.defaultSecurityMessage = config.securityMessage || DEFAULT_SECURITY_MESSAGE;
545
- this.defaultLogoUrl = config.logoUrl;
546
- if (typeof config.footer === "function") {
547
- this.footerResolver = config.footer;
548
- } else if (typeof config.footer === "string") {
549
- const fixedFooter = config.footer;
550
- this.footerResolver = () => fixedFooter;
551
- } else {
552
- this.footerResolver = defaultFooter;
553
- }
554
- }
555
- resolveBrand(override) {
556
- return override || this.defaultBrandName;
557
- }
558
- buildFooter(brandName) {
559
- return this.footerResolver(brandName);
560
- }
561
- /**
562
- * Welcome / email-verification email sent after registration.
563
- */
564
- createEmailVerification(params) {
565
- const { username, verificationUrl, otp, brandName } = params;
566
- const brand = this.resolveBrand(brandName);
567
- const body = `Hi ${username},<br/>Thank you for signing up. Use the code below or click the button to verify your email address.`;
568
- return {
569
- subject: "Verify Your Email Address",
570
- header: `Welcome to ${brand}!`,
571
- body,
572
- logoUrl: this.defaultLogoUrl,
573
- otpCode: otp,
574
- actionUrl: verificationUrl,
575
- actionText: "Verify Email",
576
- extraMessage: this.defaultSecurityMessage,
577
- footer: this.buildFooter(brand),
578
- userName: username,
579
- fromName: brand,
580
- noHtmlMessage: htmlToPlainText(body) + `
581
-
582
- Your verification code is: ${otp}
583
-
584
- Alternatively, verify here:
585
- ${verificationUrl}`
586
- };
587
- }
588
- /**
589
- * Password-reset email with an optional OTP code and action link.
590
- */
591
- createPasswordReset(params) {
592
- const { username, resetUrl, otp = "", brandName } = params;
593
- const brand = this.resolveBrand(brandName);
594
- const body = `Hi ${username},<br/>We received a request to reset your password. Use the OTP code below or click the button to proceed.`;
595
- const plainTextOtp = otp ? `
596
-
597
- Your OTP code is: ${otp}` : "";
598
- return {
599
- subject: "Password Reset Request",
600
- header: "Reset Your Password",
601
- body,
602
- logoUrl: this.defaultLogoUrl,
603
- otpCode: otp || void 0,
604
- actionUrl: resetUrl,
605
- actionText: "Reset Password",
606
- extraMessage: this.defaultSecurityMessage,
607
- footer: this.buildFooter(brand),
608
- userName: username,
609
- fromName: brand,
610
- noHtmlMessage: htmlToPlainText(body) + plainTextOtp + `
611
-
612
- Alternatively, you can use the following link to reset your password:
613
- ${resetUrl}`
614
- };
615
- }
616
- /**
617
- * Generic plain message email (no action button, no OTP).
618
- */
619
- createSimpleMessage(params) {
620
- const { subject, header, body, brandName } = params;
621
- const brand = this.resolveBrand(brandName);
622
- return {
623
- subject,
624
- header,
625
- body,
626
- logoUrl: this.defaultLogoUrl,
627
- footer: this.buildFooter(brand),
628
- fromName: brand,
629
- noHtmlMessage: htmlToPlainText(body)
630
- };
631
- }
632
- /**
633
- * Newsletter / announcement email with an optional hero image and CTA button.
634
- */
635
- createNewsLetter(params) {
636
- const { subject, header, body, imageUrl, actionUrl, actionText, brandName, logoUrl } = params;
637
- const brand = this.resolveBrand(brandName);
638
- let noHtmlMessage = htmlToPlainText(body);
639
- if (actionUrl) {
640
- noHtmlMessage += `
641
-
642
- ${actionText || "Learn more"}: ${actionUrl}`;
643
- }
644
- return {
645
- subject,
646
- header,
647
- body,
648
- logoUrl: logoUrl || this.defaultLogoUrl,
649
- imageUrl,
650
- actionUrl,
651
- actionText,
652
- footer: this.buildFooter(brand),
653
- fromName: brand,
654
- noHtmlMessage
655
- };
656
- }
657
- /**
658
- * Two-factor authentication email with OTP code and optional magic link.
659
- */
660
- create2FAEmail(params) {
661
- const { username, otp, magicLink = "", brandName } = params;
662
- const brand = this.resolveBrand(brandName);
663
- const body = `Hi ${username},<br/>Use the code below or click the button to complete your login.`;
664
- const plainLink = magicLink ? `
665
-
666
- Alternatively, verify here:
667
- ${magicLink}` : "";
668
- return {
669
- subject: "Your Login Verification Code",
670
- header: "Two-Factor Authentication",
671
- body,
672
- logoUrl: this.defaultLogoUrl,
673
- otpCode: otp,
674
- actionUrl: magicLink || void 0,
675
- actionText: magicLink ? "Verify Login" : void 0,
676
- extraMessage: this.defaultSecurityMessage,
677
- footer: this.buildFooter(brand),
678
- userName: username,
679
- fromName: brand,
680
- noHtmlMessage: htmlToPlainText(body) + `
757
+ /**
758
+ * Factory for creating pre-populated, type-safe email template DTOs.
759
+ */
760
+ var EmailTemplateFactory = class EmailTemplateFactory {
761
+ defaultBrandName;
762
+ defaultSecurityMessage;
763
+ footerResolver;
764
+ defaultLogoUrl;
765
+ constructor(config = {}) {
766
+ this.defaultBrandName = config.brandName || "Application";
767
+ this.defaultSecurityMessage = config.securityMessage || DEFAULT_SECURITY_MESSAGE;
768
+ this.defaultLogoUrl = config.logoUrl;
769
+ if (typeof config.footer === "function") this.footerResolver = config.footer;
770
+ else if (typeof config.footer === "string") {
771
+ const fixedFooter = config.footer;
772
+ this.footerResolver = () => fixedFooter;
773
+ } else this.footerResolver = defaultFooter;
774
+ }
775
+ resolveBrand(override) {
776
+ return override || this.defaultBrandName;
777
+ }
778
+ buildFooter(brandName) {
779
+ return this.footerResolver(brandName);
780
+ }
781
+ /**
782
+ * Welcome / email-verification email sent after registration.
783
+ */
784
+ createEmailVerification(params) {
785
+ const { username, verificationUrl, otp, brandName } = params;
786
+ const brand = this.resolveBrand(brandName);
787
+ const body = `Hi ${username},<br/>Thank you for signing up. Use the code below or click the button to verify your email address.`;
788
+ return {
789
+ subject: "Verify Your Email Address",
790
+ header: `Welcome to ${brand}!`,
791
+ body,
792
+ logoUrl: this.defaultLogoUrl,
793
+ otpCode: otp,
794
+ actionUrl: verificationUrl,
795
+ actionText: "Verify Email",
796
+ extraMessage: this.defaultSecurityMessage,
797
+ footer: this.buildFooter(brand),
798
+ userName: username,
799
+ fromName: brand,
800
+ noHtmlMessage: htmlToPlainText(body) + `\n\nYour verification code is: ${otp}\n\nAlternatively, verify here:\n${verificationUrl}`
801
+ };
802
+ }
803
+ /**
804
+ * Password-reset email with an optional OTP code and action link.
805
+ */
806
+ createPasswordReset(params) {
807
+ const { username, resetUrl, otp = "", brandName } = params;
808
+ const brand = this.resolveBrand(brandName);
809
+ const body = `Hi ${username},<br/>We received a request to reset your password. Use the OTP code below or click the button to proceed.`;
810
+ const plainTextOtp = otp ? `\n\nYour OTP code is: ${otp}` : "";
811
+ return {
812
+ subject: "Password Reset Request",
813
+ header: "Reset Your Password",
814
+ body,
815
+ logoUrl: this.defaultLogoUrl,
816
+ otpCode: otp || void 0,
817
+ actionUrl: resetUrl,
818
+ actionText: "Reset Password",
819
+ extraMessage: this.defaultSecurityMessage,
820
+ footer: this.buildFooter(brand),
821
+ userName: username,
822
+ fromName: brand,
823
+ noHtmlMessage: htmlToPlainText(body) + plainTextOtp + `\n\nAlternatively, you can use the following link to reset your password:\n${resetUrl}`
824
+ };
825
+ }
826
+ /**
827
+ * Generic plain message email (no action button, no OTP).
828
+ */
829
+ createSimpleMessage(params) {
830
+ const { subject, header, body, brandName } = params;
831
+ const brand = this.resolveBrand(brandName);
832
+ return {
833
+ subject,
834
+ header,
835
+ body,
836
+ logoUrl: this.defaultLogoUrl,
837
+ footer: this.buildFooter(brand),
838
+ fromName: brand,
839
+ noHtmlMessage: htmlToPlainText(body)
840
+ };
841
+ }
842
+ /**
843
+ * Newsletter / announcement email with an optional hero image and CTA button.
844
+ */
845
+ createNewsLetter(params) {
846
+ const { subject, header, body, imageUrl, actionUrl, actionText, brandName, logoUrl } = params;
847
+ const brand = this.resolveBrand(brandName);
848
+ let noHtmlMessage = htmlToPlainText(body);
849
+ if (actionUrl) noHtmlMessage += `\n\n${actionText || "Learn more"}: ${actionUrl}`;
850
+ return {
851
+ subject,
852
+ header,
853
+ body,
854
+ logoUrl: logoUrl || this.defaultLogoUrl,
855
+ imageUrl,
856
+ actionUrl,
857
+ actionText,
858
+ footer: this.buildFooter(brand),
859
+ fromName: brand,
860
+ noHtmlMessage
861
+ };
862
+ }
863
+ /**
864
+ * Two-factor authentication email with OTP code and optional magic link.
865
+ */
866
+ create2FAEmail(params) {
867
+ const { username, otp, magicLink = "", brandName } = params;
868
+ const brand = this.resolveBrand(brandName);
869
+ const body = `Hi ${username},<br/>Use the code below or click the button to complete your login.`;
870
+ const plainLink = magicLink ? `\n\nAlternatively, verify here:\n${magicLink}` : "";
871
+ return {
872
+ subject: "Your Login Verification Code",
873
+ header: "Two-Factor Authentication",
874
+ body,
875
+ logoUrl: this.defaultLogoUrl,
876
+ otpCode: otp,
877
+ actionUrl: magicLink || void 0,
878
+ actionText: magicLink ? "Verify Login" : void 0,
879
+ extraMessage: this.defaultSecurityMessage,
880
+ footer: this.buildFooter(brand),
881
+ userName: username,
882
+ fromName: brand,
883
+ noHtmlMessage: htmlToPlainText(body) + `\n\nYour verification code is: ${otp}` + plainLink
884
+ };
885
+ }
886
+ /**
887
+ * Magic link sign-in email (no OTP, button only).
888
+ */
889
+ createMagicLinkEmail(params) {
890
+ const { username, magicLink, brandName } = params;
891
+ const brand = this.resolveBrand(brandName);
892
+ const body = `Hi ${username},<br/>Click the button below to sign in. No password needed.`;
893
+ return {
894
+ subject: "Your Magic Link",
895
+ header: `Sign In to ${brand}`,
896
+ body,
897
+ logoUrl: this.defaultLogoUrl,
898
+ actionUrl: magicLink,
899
+ actionText: "Sign In",
900
+ extraMessage: this.defaultSecurityMessage,
901
+ footer: this.buildFooter(brand),
902
+ userName: username,
903
+ fromName: brand,
904
+ noHtmlMessage: htmlToPlainText(body) + `\n\nSign in here:\n${magicLink}`
905
+ };
906
+ }
907
+ static _defaultInstance;
908
+ static get defaultInstance() {
909
+ if (!this._defaultInstance) this._defaultInstance = new EmailTemplateFactory();
910
+ return this._defaultInstance;
911
+ }
912
+ static createEmailVerification(params) {
913
+ return this.defaultInstance.createEmailVerification(params);
914
+ }
915
+ static createPasswordReset(params) {
916
+ return this.defaultInstance.createPasswordReset(params);
917
+ }
918
+ static createSimpleMessage(params) {
919
+ return this.defaultInstance.createSimpleMessage(params);
920
+ }
921
+ static createNewsLetter(params) {
922
+ return this.defaultInstance.createNewsLetter(params);
923
+ }
924
+ static create2FAEmail(params) {
925
+ return this.defaultInstance.create2FAEmail(params);
926
+ }
927
+ static createMagicLinkEmail(params) {
928
+ return this.defaultInstance.createMagicLinkEmail(params);
929
+ }
930
+ };
681
931
 
682
- Your verification code is: ${otp}` + plainLink
683
- };
684
- }
685
- /**
686
- * Magic link sign-in email (no OTP, button only).
687
- */
688
- createMagicLinkEmail(params) {
689
- const { username, magicLink, brandName } = params;
690
- const brand = this.resolveBrand(brandName);
691
- const body = `Hi ${username},<br/>Click the button below to sign in. No password needed.`;
692
- return {
693
- subject: "Your Magic Link",
694
- header: `Sign In to ${brand}`,
695
- body,
696
- logoUrl: this.defaultLogoUrl,
697
- actionUrl: magicLink,
698
- actionText: "Sign In",
699
- extraMessage: this.defaultSecurityMessage,
700
- footer: this.buildFooter(brand),
701
- userName: username,
702
- fromName: brand,
703
- noHtmlMessage: htmlToPlainText(body) + `
932
+ //#endregion
933
+ //#region src/templates/template-builder.ts
934
+ /**
935
+ * Builds an upload-ready HTML template from the canonical {@link EmailTemplateDto}.
936
+ *
937
+ * The output can be uploaded to a messaging platform (Zoho CPaaS, SendGrid, etc.)
938
+ * as a provider-side template.
939
+ */
940
+ function buildHTMLTemplate(dto, options = {}) {
941
+ return buildHtml(dto, options);
942
+ }
943
+ /**
944
+ * Builds an upload-ready plain-text template from the canonical {@link EmailTemplateDto}.
945
+ */
946
+ function buildPlainTextTemplate(dto, _options) {
947
+ return buildPlainText(dto);
948
+ }
704
949
 
705
- Sign in here:
706
- ${magicLink}`
707
- };
708
- }
709
- // ─── Default Static Instance ──────────────────────────────────────────────
710
- static _defaultInstance;
711
- static get defaultInstance() {
712
- if (!this._defaultInstance) {
713
- this._defaultInstance = new _EmailTemplateFactory();
714
- }
715
- return this._defaultInstance;
716
- }
717
- static createEmailVerification(params) {
718
- return this.defaultInstance.createEmailVerification(params);
719
- }
720
- static createPasswordReset(params) {
721
- return this.defaultInstance.createPasswordReset(params);
722
- }
723
- static createSimpleMessage(params) {
724
- return this.defaultInstance.createSimpleMessage(params);
725
- }
726
- static createNewsLetter(params) {
727
- return this.defaultInstance.createNewsLetter(params);
728
- }
729
- static create2FAEmail(params) {
730
- return this.defaultInstance.create2FAEmail(params);
731
- }
732
- static createMagicLinkEmail(params) {
733
- return this.defaultInstance.createMagicLinkEmail(params);
734
- }
735
- };
736
- export {
737
- ConfigurationError,
738
- ConsoleEmailSender,
739
- DefaultEmailRenderer,
740
- EmailTemplateFactory,
741
- MailKit,
742
- MailKitError,
743
- MemoryEmailSender,
744
- TemplateError,
745
- TransportError,
746
- ZeptoMailHttpSender,
747
- buildHtml,
748
- buildPlainText,
749
- createMailKit,
750
- decodeHtmlEntities,
751
- htmlToPlainText,
752
- isValidHttpUrl,
753
- normalizeRecipient,
754
- normalizeRecipients,
755
- parseEmailAddress
756
- };
950
+ //#endregion
951
+ export { ConfigurationError, ConsoleEmailSender, CpaasHttpSender, CpaasHttpSender as ZeptoMailHttpSender, DefaultEmailRenderer, EmailTemplateFactory, MailKit, MailKitError, MemoryEmailSender, TemplateError, TransportError, buildHTMLTemplate, buildHtml, buildPlainText, buildPlainTextTemplate, createMailKit, decodeHtmlEntities, htmlToPlainText, isValidHttpUrl, normalizeRecipient, normalizeRecipients, parseEmailAddress };
757
952
  //# sourceMappingURL=index.js.map