ts-mailkit 2.0.0 → 2.0.1

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
@@ -1,757 +1,684 @@
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
+ cause;
71
+ constructor(message, options) {
72
+ super(message);
73
+ this.name = "TransportError";
74
+ this.transportName = options.transportName;
75
+ this.statusCode = options.statusCode;
76
+ this.responseBody = options.responseBody;
77
+ this.cause = options.cause;
78
+ Object.setPrototypeOf(this, new.target.prototype);
79
+ }
66
80
  };
81
+ /**
82
+ * Thrown when template rendering or DTO validation fails.
83
+ */
67
84
  var TemplateError = class extends MailKitError {
68
- constructor(message) {
69
- super(message);
70
- this.name = "TemplateError";
71
- Object.setPrototypeOf(this, new.target.prototype);
72
- }
85
+ constructor(message) {
86
+ super(message);
87
+ this.name = "TemplateError";
88
+ Object.setPrototypeOf(this, new.target.prototype);
89
+ }
73
90
  };
74
91
 
75
- // src/renderers/utils/html-to-plaintext.ts
92
+ //#endregion
93
+ //#region src/renderers/utils/html-to-plaintext.ts
94
+ /**
95
+ * Decodes common HTML entities into their plain text equivalents.
96
+ */
76
97
  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");
98
+ 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
99
  }
100
+ /**
101
+ * Strips HTML tags and normalizes whitespace into readable plain text.
102
+ * Converts <br>, <p>, and <div> into appropriate line breaks.
103
+ */
79
104
  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();
105
+ if (!html) return "";
106
+ 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
107
  }
85
108
 
86
- // src/renderers/default/default-renderer.ts
109
+ //#endregion
110
+ //#region src/renderers/default/default-renderer.ts
111
+ /**
112
+ * Validates whether a string is a valid HTTP or HTTPS URL.
113
+ */
87
114
  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
- }
115
+ if (!urlString || typeof urlString !== "string") return false;
116
+ try {
117
+ const url = new URL(urlString.trim());
118
+ return (url.protocol === "http:" || url.protocol === "https:") && url.hostname.length > 0;
119
+ } catch {
120
+ return false;
121
+ }
95
122
  }
123
+ /**
124
+ * Builds a plain-text fallback string from an email DTO.
125
+ */
96
126
  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");
127
+ if (dto.noHtmlMessage) return dto.noHtmlMessage;
128
+ const divider = "──────────────────────────────";
129
+ const parts = [];
130
+ if (dto.header) parts.push(dto.header, divider);
131
+ if (dto.body) parts.push(htmlToPlainText(dto.body));
132
+ if (dto.otpCode) parts.push(`Verification Code: ${dto.otpCode}`);
133
+ if (dto.actionText && dto.actionUrl) parts.push(`${dto.actionText}: ${dto.actionUrl}`);
134
+ if (dto.extraMessage) parts.push(htmlToPlainText(dto.extraMessage));
135
+ if (dto.footer) parts.push(`${divider}\n${htmlToPlainText(dto.footer)}`);
136
+ return parts.join("\n\n");
122
137
  }
138
+ /**
139
+ * Builds a responsive, styled HTML email document from an email DTO.
140
+ */
123
141
  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");
142
+ const primaryColor = options.primaryColor || "#4f46e5";
143
+ const fontFamily = options.fontFamily || "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
144
+ const maxWidth = options.maxWidth || "600px";
145
+ const parts = [
146
+ `<!DOCTYPE html>`,
147
+ `<html lang="en">`,
148
+ `<head>`,
149
+ `<meta charset="UTF-8">`,
150
+ `<meta name="viewport" content="width=device-width, initial-scale=1.0">`,
151
+ `<title>${dto.subject}</title>`,
152
+ `</head>`,
153
+ `<body style="margin:0;padding:24px 16px;background-color:#f9fafb;font-family:${fontFamily};color:#1f2937;line-height:1.6;">`,
154
+ `<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;">`
155
+ ];
156
+ const logoCandidate = dto.logoUrl ?? options.logoUrl;
157
+ if (logoCandidate && isValidHttpUrl(logoCandidate)) {
158
+ const validLogo = logoCandidate.trim();
159
+ 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>`);
160
+ }
161
+ 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>`);
162
+ 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>`);
163
+ if (dto.body) parts.push(`<div style="margin:0 0 20px;font-size:1rem;color:#374151;">${dto.body}</div>`);
164
+ 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>`);
165
+ 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>`);
166
+ if (dto.extraMessage) parts.push(`<div style="margin:20px 0 0;font-size:0.875rem;color:#6b7280;line-height:1.5;">${dto.extraMessage}</div>`);
167
+ 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>`);
168
+ parts.push(`</div>`, `</body>`, `</html>`);
169
+ return parts.join("\n");
188
170
  }
171
+ /**
172
+ * Default HTML and plain-text email renderer for ts-mailkit.
173
+ */
189
174
  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
- }
175
+ options;
176
+ constructor(options = {}) {
177
+ this.options = options;
178
+ }
179
+ render(dto) {
180
+ return {
181
+ html: buildHtml(dto, this.options),
182
+ text: buildPlainText(dto)
183
+ };
184
+ }
200
185
  };
201
186
 
202
- // src/core/client.ts
187
+ //#endregion
188
+ //#region src/core/client.ts
189
+ /**
190
+ * Main email client and orchestration service for ts-mailkit.
191
+ */
203
192
  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
- }
193
+ transport;
194
+ renderer;
195
+ defaultFrom;
196
+ defaultBrandName;
197
+ brandNameResolver;
198
+ constructor(options) {
199
+ if (!options.transport) throw new ConfigurationError("MailKit: A transport adapter (IEmailSender) is required.");
200
+ this.transport = options.transport;
201
+ this.renderer = options.renderer ?? new DefaultEmailRenderer();
202
+ this.defaultFrom = options.defaultFrom;
203
+ this.defaultBrandName = options.defaultBrandName;
204
+ this.brandNameResolver = options.brandNameResolver;
205
+ }
206
+ /**
207
+ * Returns the underlying transport instance.
208
+ */
209
+ getTransport() {
210
+ return this.transport;
211
+ }
212
+ /**
213
+ * Renders an email DTO to HTML and plain text without dispatching.
214
+ */
215
+ async render(template) {
216
+ return await this.renderer.render(template);
217
+ }
218
+ /**
219
+ * Sends an email using a strongly-typed template DTO.
220
+ *
221
+ * Example:
222
+ * ```ts
223
+ * await mailer.send({
224
+ * to: 'user@example.com',
225
+ * template: myDto,
226
+ * });
227
+ * ```
228
+ */
229
+ async send(options) {
230
+ const template = options.template;
231
+ const recipientName = options.toName ?? template.userName;
232
+ let resolvedFromName = options.fromName ?? template.fromName;
233
+ if (!resolvedFromName && this.brandNameResolver) resolvedFromName = await this.brandNameResolver();
234
+ if (!resolvedFromName) resolvedFromName = this.defaultBrandName;
235
+ const rendered = await this.renderer.render(template);
236
+ const plaintextBody = template.noHtmlMessage ?? rendered.text;
237
+ let toRecipients;
238
+ if (typeof options.to === "string" && recipientName) toRecipients = {
239
+ address: options.to,
240
+ name: recipientName
241
+ };
242
+ else toRecipients = options.to;
243
+ let from = options.from ?? this.defaultFrom;
244
+ if (resolvedFromName && from) from = {
245
+ address: normalizeRecipient(from).address,
246
+ name: resolvedFromName
247
+ };
248
+ return await this.sendRaw({
249
+ to: toRecipients,
250
+ from,
251
+ subject: template.subject,
252
+ html: rendered.html,
253
+ text: plaintextBody,
254
+ cc: options.cc,
255
+ bcc: options.bcc,
256
+ replyTo: options.replyTo,
257
+ attachments: options.attachments,
258
+ headers: options.headers,
259
+ tags: options.tags,
260
+ metadata: options.metadata
261
+ });
262
+ }
263
+ /**
264
+ * Dispatches a raw, pre-rendered email directly through the transport.
265
+ * If `options.text` is omitted, plain text is automatically derived from `options.html`.
266
+ */
267
+ async sendRaw(options) {
268
+ const from = options.from ?? this.defaultFrom;
269
+ const text = options.text ?? (options.html ? htmlToPlainText(options.html) : void 0);
270
+ return await this.transport.send({
271
+ ...options,
272
+ from,
273
+ text
274
+ });
275
+ }
293
276
  };
277
+ /**
278
+ * Convenience factory to create a MailKit client instance.
279
+ */
294
280
  function createMailKit(options) {
295
- return new MailKit(options);
281
+ return new MailKit(options);
296
282
  }
297
283
 
298
- // src/transports/zeptomail/zeptomail-sender.ts
284
+ //#endregion
285
+ //#region src/transports/zeptomail/zeptomail-sender.ts
286
+ /**
287
+ * ZeptoMail (Zoho Mail transactional email HTTP API) transport adapter.
288
+ *
289
+ * Designed for zero dependencies and universal edge compatibility (Node.js, Bun, Deno, Cloudflare Workers)
290
+ * by utilizing the standard global `fetch` API.
291
+ */
299
292
  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
- }
293
+ name = "zeptomail";
294
+ apiUrl;
295
+ authHeader;
296
+ defaultFrom;
297
+ fetchImpl;
298
+ constructor(config) {
299
+ if (!config.apiToken || typeof config.apiToken !== "string") throw new ConfigurationError("ZeptoMailHttpSender: Missing or invalid apiToken.");
300
+ if (!config.from) throw new ConfigurationError("ZeptoMailHttpSender: Missing required default from address.");
301
+ const host = (config.apiHost || "api.zeptomail.com").replace(/^https?:\/\//, "").replace(/\/+$/, "");
302
+ this.apiUrl = `https://${host}/v1.1/email`;
303
+ const token = config.apiToken.trim();
304
+ this.authHeader = token.startsWith("Zoho-") ? token : `Zoho-enczapikey ${token}`;
305
+ this.defaultFrom = normalizeRecipient(config.from);
306
+ if (!this.defaultFrom.address) throw new ConfigurationError("ZeptoMailHttpSender: Configured from address must not be empty.");
307
+ const fetchImpl = config.fetch ?? globalThis.fetch;
308
+ if (typeof fetchImpl !== "function") throw new ConfigurationError("ZeptoMailHttpSender: No global fetch implementation found. Pass a custom fetch to ZeptoMailHttpConfig if running on Node < 18.");
309
+ this.fetchImpl = fetchImpl.bind(globalThis);
310
+ }
311
+ /**
312
+ * Dispatches an email using Zoho ZeptoMail API v1.1.
313
+ */
314
+ async send(options) {
315
+ const toRecipients = normalizeRecipients(options.to);
316
+ if (toRecipients.length === 0) throw new TransportError("ZeptoMailHttpSender: At least one recipient (to) must be specified.", { transportName: this.name });
317
+ const resolvedFrom = options.from ? normalizeRecipient(options.from) : this.defaultFrom;
318
+ const payload = {
319
+ from: {
320
+ address: resolvedFrom.address,
321
+ name: resolvedFrom.name
322
+ },
323
+ to: toRecipients.map((r) => ({ email_address: {
324
+ address: r.address,
325
+ name: r.name || ""
326
+ } })),
327
+ subject: options.subject,
328
+ htmlbody: options.html,
329
+ textbody: options.text
330
+ };
331
+ if (options.cc) {
332
+ const ccList = normalizeRecipients(options.cc);
333
+ if (ccList.length > 0) payload.cc = ccList.map((r) => ({ email_address: {
334
+ address: r.address,
335
+ name: r.name || ""
336
+ } }));
337
+ }
338
+ if (options.bcc) {
339
+ const bccList = normalizeRecipients(options.bcc);
340
+ if (bccList.length > 0) payload.bcc = bccList.map((r) => ({ email_address: {
341
+ address: r.address,
342
+ name: r.name || ""
343
+ } }));
344
+ }
345
+ if (options.replyTo) {
346
+ const replyToList = normalizeRecipients(options.replyTo);
347
+ if (replyToList.length > 0) payload.reply_to = replyToList.map((r) => ({
348
+ address: r.address,
349
+ name: r.name
350
+ }));
351
+ }
352
+ if (options.attachments && options.attachments.length > 0) payload.attachments = options.attachments.map((att) => {
353
+ let contentBase64;
354
+ if (typeof att.content === "string") contentBase64 = att.content;
355
+ else if (typeof Buffer !== "undefined") contentBase64 = Buffer.from(att.content).toString("base64");
356
+ else {
357
+ let binary = "";
358
+ const bytes = new Uint8Array(att.content);
359
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
360
+ contentBase64 = btoa(binary);
361
+ }
362
+ return {
363
+ name: att.filename,
364
+ content: contentBase64,
365
+ mime_type: att.mimeType || att.contentType || "application/octet-stream",
366
+ cid: att.cid
367
+ };
368
+ });
369
+ let response;
370
+ try {
371
+ response = await this.fetchImpl(this.apiUrl, {
372
+ method: "POST",
373
+ headers: {
374
+ Accept: "application/json",
375
+ "Content-Type": "application/json",
376
+ Authorization: this.authHeader
377
+ },
378
+ body: JSON.stringify(payload)
379
+ });
380
+ } catch (err) {
381
+ throw new TransportError(`ZeptoMailHttpSender: Network request failed: ${err instanceof Error ? err.message : String(err)}`, {
382
+ transportName: this.name,
383
+ cause: err
384
+ });
385
+ }
386
+ const responseText = await response.text();
387
+ let responseData;
388
+ try {
389
+ responseData = responseText ? JSON.parse(responseText) : {};
390
+ } catch {
391
+ responseData = { raw: responseText };
392
+ }
393
+ if (!response.ok) {
394
+ const errorMessage = responseData?.error?.message || responseData?.message || `HTTP ${response.status}: ${responseText || response.statusText}`;
395
+ throw new TransportError(`ZeptoMailHttpSender: Failed to send email - ${errorMessage}`, {
396
+ transportName: this.name,
397
+ statusCode: response.status,
398
+ responseBody: responseText
399
+ });
400
+ }
401
+ return {
402
+ success: true,
403
+ messageId: responseData?.data?.[0]?.message_id,
404
+ response: responseData
405
+ };
406
+ }
442
407
  };
443
408
 
444
- // src/transports/memory/memory-sender.ts
409
+ //#endregion
410
+ //#region src/transports/memory/memory-sender.ts
411
+ /**
412
+ * In-memory email sender for automated testing, local development, and CI environments.
413
+ * Captures all dispatched emails and provides inspection methods.
414
+ */
445
415
  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
- }
416
+ name = "memory";
417
+ sentMails = [];
418
+ nextId = 1;
419
+ async send(options) {
420
+ this.sentMails.push({ ...options });
421
+ const messageId = `mem-${this.nextId++}-${Date.now()}`;
422
+ return {
423
+ success: true,
424
+ messageId,
425
+ response: { id: messageId }
426
+ };
427
+ }
428
+ /**
429
+ * Returns a copy of all emails sent through this transport instance.
430
+ */
431
+ getSentMails() {
432
+ return [...this.sentMails];
433
+ }
434
+ /**
435
+ * Returns the most recent email sent, or undefined if no emails have been sent.
436
+ */
437
+ getLastMail() {
438
+ return this.sentMails.length > 0 ? { ...this.sentMails[this.sentMails.length - 1] } : void 0;
439
+ }
440
+ /**
441
+ * Clears all recorded sent emails.
442
+ */
443
+ clear() {
444
+ this.sentMails = [];
445
+ }
446
+ /**
447
+ * Returns the total count of sent emails.
448
+ */
449
+ count() {
450
+ return this.sentMails.length;
451
+ }
482
452
  };
483
453
 
484
- // src/transports/console/console-sender.ts
454
+ //#endregion
455
+ //#region src/transports/console/console-sender.ts
456
+ /**
457
+ * Console logger transport that prints dispatched emails to stdout/stderr.
458
+ * Ideal for development and debugging.
459
+ */
485
460
  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
- }
461
+ name = "console";
462
+ log;
463
+ includeHtml;
464
+ nextId = 1;
465
+ constructor(options = {}) {
466
+ this.log = options.logger ?? console.log;
467
+ this.includeHtml = options.includeHtml ?? false;
468
+ }
469
+ async send(options) {
470
+ const to = normalizeRecipients(options.to).map((r) => r.name ? `${r.name} <${r.address}>` : r.address).join(", ");
471
+ const from = options.from ? JSON.stringify(options.from) : "(default)";
472
+ const messageId = `console-${this.nextId++}-${Date.now()}`;
473
+ const separator = "─".repeat(60);
474
+ const lines = [
475
+ `\n┌${separator}┐`,
476
+ `│ [ts-mailkit:console] DISPATCHED EMAIL (${messageId})`,
477
+ `├${separator}┤`,
478
+ `│ From: ${from}`,
479
+ `│ To: ${to}`,
480
+ `│ Subject: ${options.subject}`,
481
+ `├${separator}┤`
482
+ ];
483
+ if (options.text) {
484
+ lines.push("│ Text Body:");
485
+ for (const line of options.text.split("\n")) lines.push(`│ ${line}`);
486
+ }
487
+ if (this.includeHtml && options.html) {
488
+ lines.push("│ HTML Body:");
489
+ for (const line of options.html.split("\n")) lines.push(`│ ${line}`);
490
+ }
491
+ lines.push(`└${separator}┘\n`);
492
+ this.log(lines.join("\n"));
493
+ return {
494
+ success: true,
495
+ messageId,
496
+ response: { logged: true }
497
+ };
498
+ }
530
499
  };
531
500
 
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.";
501
+ //#endregion
502
+ //#region src/templates/factory.ts
503
+ const DEFAULT_SECURITY_MESSAGE = "If you did not request this, please ignore this email or contact support if you have concerns.";
534
504
  function defaultFooter(brandName) {
535
- return `&copy; ${(/* @__PURE__ */ new Date()).getFullYear()} ${brandName}. All rights reserved.`;
505
+ return `&copy; ${(/* @__PURE__ */ new Date()).getFullYear()} ${brandName}. All rights reserved.`;
536
506
  }
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) + `
681
-
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) + `
704
-
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
507
+ /**
508
+ * Factory for creating pre-populated, type-safe email template DTOs.
509
+ */
510
+ var EmailTemplateFactory = class EmailTemplateFactory {
511
+ defaultBrandName;
512
+ defaultSecurityMessage;
513
+ footerResolver;
514
+ defaultLogoUrl;
515
+ constructor(config = {}) {
516
+ this.defaultBrandName = config.brandName || "Application";
517
+ this.defaultSecurityMessage = config.securityMessage || DEFAULT_SECURITY_MESSAGE;
518
+ this.defaultLogoUrl = config.logoUrl;
519
+ if (typeof config.footer === "function") this.footerResolver = config.footer;
520
+ else if (typeof config.footer === "string") {
521
+ const fixedFooter = config.footer;
522
+ this.footerResolver = () => fixedFooter;
523
+ } else this.footerResolver = defaultFooter;
524
+ }
525
+ resolveBrand(override) {
526
+ return override || this.defaultBrandName;
527
+ }
528
+ buildFooter(brandName) {
529
+ return this.footerResolver(brandName);
530
+ }
531
+ /**
532
+ * Welcome / email-verification email sent after registration.
533
+ */
534
+ createEmailVerification(params) {
535
+ const { username, verificationUrl, otp, brandName } = params;
536
+ const brand = this.resolveBrand(brandName);
537
+ const body = `Hi ${username},<br/>Thank you for signing up. Use the code below or click the button to verify your email address.`;
538
+ return {
539
+ subject: "Verify Your Email Address",
540
+ header: `Welcome to ${brand}!`,
541
+ body,
542
+ logoUrl: this.defaultLogoUrl,
543
+ otpCode: otp,
544
+ actionUrl: verificationUrl,
545
+ actionText: "Verify Email",
546
+ extraMessage: this.defaultSecurityMessage,
547
+ footer: this.buildFooter(brand),
548
+ userName: username,
549
+ fromName: brand,
550
+ noHtmlMessage: htmlToPlainText(body) + `\n\nYour verification code is: ${otp}\n\nAlternatively, verify here:\n${verificationUrl}`
551
+ };
552
+ }
553
+ /**
554
+ * Password-reset email with an optional OTP code and action link.
555
+ */
556
+ createPasswordReset(params) {
557
+ const { username, resetUrl, otp = "", brandName } = params;
558
+ const brand = this.resolveBrand(brandName);
559
+ const body = `Hi ${username},<br/>We received a request to reset your password. Use the OTP code below or click the button to proceed.`;
560
+ const plainTextOtp = otp ? `\n\nYour OTP code is: ${otp}` : "";
561
+ return {
562
+ subject: "Password Reset Request",
563
+ header: "Reset Your Password",
564
+ body,
565
+ logoUrl: this.defaultLogoUrl,
566
+ otpCode: otp || void 0,
567
+ actionUrl: resetUrl,
568
+ actionText: "Reset Password",
569
+ extraMessage: this.defaultSecurityMessage,
570
+ footer: this.buildFooter(brand),
571
+ userName: username,
572
+ fromName: brand,
573
+ noHtmlMessage: htmlToPlainText(body) + plainTextOtp + `\n\nAlternatively, you can use the following link to reset your password:\n${resetUrl}`
574
+ };
575
+ }
576
+ /**
577
+ * Generic plain message email (no action button, no OTP).
578
+ */
579
+ createSimpleMessage(params) {
580
+ const { subject, header, body, brandName } = params;
581
+ const brand = this.resolveBrand(brandName);
582
+ return {
583
+ subject,
584
+ header,
585
+ body,
586
+ logoUrl: this.defaultLogoUrl,
587
+ footer: this.buildFooter(brand),
588
+ fromName: brand,
589
+ noHtmlMessage: htmlToPlainText(body)
590
+ };
591
+ }
592
+ /**
593
+ * Newsletter / announcement email with an optional hero image and CTA button.
594
+ */
595
+ createNewsLetter(params) {
596
+ const { subject, header, body, imageUrl, actionUrl, actionText, brandName, logoUrl } = params;
597
+ const brand = this.resolveBrand(brandName);
598
+ let noHtmlMessage = htmlToPlainText(body);
599
+ if (actionUrl) noHtmlMessage += `\n\n${actionText || "Learn more"}: ${actionUrl}`;
600
+ return {
601
+ subject,
602
+ header,
603
+ body,
604
+ logoUrl: logoUrl || this.defaultLogoUrl,
605
+ imageUrl,
606
+ actionUrl,
607
+ actionText,
608
+ footer: this.buildFooter(brand),
609
+ fromName: brand,
610
+ noHtmlMessage
611
+ };
612
+ }
613
+ /**
614
+ * Two-factor authentication email with OTP code and optional magic link.
615
+ */
616
+ create2FAEmail(params) {
617
+ const { username, otp, magicLink = "", brandName } = params;
618
+ const brand = this.resolveBrand(brandName);
619
+ const body = `Hi ${username},<br/>Use the code below or click the button to complete your login.`;
620
+ const plainLink = magicLink ? `\n\nAlternatively, verify here:\n${magicLink}` : "";
621
+ return {
622
+ subject: "Your Login Verification Code",
623
+ header: "Two-Factor Authentication",
624
+ body,
625
+ logoUrl: this.defaultLogoUrl,
626
+ otpCode: otp,
627
+ actionUrl: magicLink || void 0,
628
+ actionText: magicLink ? "Verify Login" : void 0,
629
+ extraMessage: this.defaultSecurityMessage,
630
+ footer: this.buildFooter(brand),
631
+ userName: username,
632
+ fromName: brand,
633
+ noHtmlMessage: htmlToPlainText(body) + `\n\nYour verification code is: ${otp}` + plainLink
634
+ };
635
+ }
636
+ /**
637
+ * Magic link sign-in email (no OTP, button only).
638
+ */
639
+ createMagicLinkEmail(params) {
640
+ const { username, magicLink, brandName } = params;
641
+ const brand = this.resolveBrand(brandName);
642
+ const body = `Hi ${username},<br/>Click the button below to sign in. No password needed.`;
643
+ return {
644
+ subject: "Your Magic Link",
645
+ header: `Sign In to ${brand}`,
646
+ body,
647
+ logoUrl: this.defaultLogoUrl,
648
+ actionUrl: magicLink,
649
+ actionText: "Sign In",
650
+ extraMessage: this.defaultSecurityMessage,
651
+ footer: this.buildFooter(brand),
652
+ userName: username,
653
+ fromName: brand,
654
+ noHtmlMessage: htmlToPlainText(body) + `\n\nSign in here:\n${magicLink}`
655
+ };
656
+ }
657
+ static _defaultInstance;
658
+ static get defaultInstance() {
659
+ if (!this._defaultInstance) this._defaultInstance = new EmailTemplateFactory();
660
+ return this._defaultInstance;
661
+ }
662
+ static createEmailVerification(params) {
663
+ return this.defaultInstance.createEmailVerification(params);
664
+ }
665
+ static createPasswordReset(params) {
666
+ return this.defaultInstance.createPasswordReset(params);
667
+ }
668
+ static createSimpleMessage(params) {
669
+ return this.defaultInstance.createSimpleMessage(params);
670
+ }
671
+ static createNewsLetter(params) {
672
+ return this.defaultInstance.createNewsLetter(params);
673
+ }
674
+ static create2FAEmail(params) {
675
+ return this.defaultInstance.create2FAEmail(params);
676
+ }
677
+ static createMagicLinkEmail(params) {
678
+ return this.defaultInstance.createMagicLinkEmail(params);
679
+ }
756
680
  };
681
+
682
+ //#endregion
683
+ export { ConfigurationError, ConsoleEmailSender, DefaultEmailRenderer, EmailTemplateFactory, MailKit, MailKitError, MemoryEmailSender, TemplateError, TransportError, ZeptoMailHttpSender, buildHtml, buildPlainText, createMailKit, decodeHtmlEntities, htmlToPlainText, isValidHttpUrl, normalizeRecipient, normalizeRecipients, parseEmailAddress };
757
684
  //# sourceMappingURL=index.js.map