@postxl/generators 1.25.0 → 1.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/backend-actions/actions.generator.d.ts +11 -0
- package/dist/backend-actions/actions.generator.js.map +1 -1
- package/dist/backend-actions/generators/actions-module.generator.js +11 -3
- package/dist/backend-actions/generators/actions-module.generator.js.map +1 -1
- package/dist/backend-actions/generators/dispatcher-service.generator.js +12 -4
- package/dist/backend-actions/generators/dispatcher-service.generator.js.map +1 -1
- package/dist/backend-core/backend.generator.js +1 -0
- package/dist/backend-core/backend.generator.js.map +1 -1
- package/dist/backend-mail/generators/conditional-files.d.ts +17 -0
- package/dist/backend-mail/generators/conditional-files.js +850 -0
- package/dist/backend-mail/generators/conditional-files.js.map +1 -0
- package/dist/backend-mail/generators/env-config.generator.d.ts +16 -0
- package/dist/backend-mail/generators/env-config.generator.js +201 -0
- package/dist/backend-mail/generators/env-config.generator.js.map +1 -0
- package/dist/backend-mail/generators/mail.service.generator.d.ts +11 -0
- package/dist/backend-mail/generators/mail.service.generator.js +253 -0
- package/dist/backend-mail/generators/mail.service.generator.js.map +1 -0
- package/dist/backend-mail/index.d.ts +5 -0
- package/dist/backend-mail/index.js +41 -0
- package/dist/backend-mail/index.js.map +1 -0
- package/dist/backend-mail/mail.generator.d.ts +79 -0
- package/dist/backend-mail/mail.generator.js +167 -0
- package/dist/backend-mail/mail.generator.js.map +1 -0
- package/dist/backend-mail/template/src/adapters/log.adapter.ts +14 -0
- package/dist/backend-mail/template/src/adapters/mail-adapter.interface.ts +27 -0
- package/dist/backend-mail/template/src/mail.config.ts +55 -0
- package/dist/backend-mail/template/src/mail.module.ts +37 -0
- package/dist/backend-mail/template/src/mail.service.test.ts +195 -0
- package/dist/backend-mail/template/src/mail.types.ts +67 -0
- package/dist/backend-mail/template/src/templates/simple.renderer.test.ts +160 -0
- package/dist/backend-mail/template/src/templates/simple.renderer.ts +171 -0
- package/dist/backend-mail/template/src/templates/template-renderer.interface.ts +5 -0
- package/dist/backend-mail/template/tsconfig.lib.json +10 -0
- package/dist/generators.js +2 -0
- package/dist/generators.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +6 -2
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,850 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Content for the optional adapter / renderer source files.
|
|
4
|
+
*
|
|
5
|
+
* These files are emitted to the generated project only when the matching
|
|
6
|
+
* adapter or renderer is enabled via `configureBackendMailGenerator`.
|
|
7
|
+
* Keeping them as plain string constants (rather than in the `template/`
|
|
8
|
+
* folder) means the generator never copies files the project will not
|
|
9
|
+
* compile and lets us gate both file emission and `package.json`
|
|
10
|
+
* dependencies on the same boolean.
|
|
11
|
+
*/
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
exports.emailmdRendererTestSource = exports.emailmdRendererSource = exports.smtpAdapterTestSource = exports.smtpAdapterSource = exports.graphAdapterTestSource = exports.graphAdapterSource = exports.sesAdapterSource = void 0;
|
|
14
|
+
exports.sesAdapterSource = `import { SendEmailCommand, SESClient } from '@aws-sdk/client-ses'
|
|
15
|
+
import { Logger } from '@nestjs/common'
|
|
16
|
+
|
|
17
|
+
import type { IMailAdapter, MailPayload, MailSendResult, MailSendResultErrorStatus } from './mail-adapter.interface'
|
|
18
|
+
|
|
19
|
+
export type SesAdapterConfig = {
|
|
20
|
+
region: string
|
|
21
|
+
useCredentials: boolean
|
|
22
|
+
accessKey?: string
|
|
23
|
+
secretAccessKey?: string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const SES_INVALID_ADDRESS_ERRORS = new Set([
|
|
27
|
+
'InvalidParameterValue',
|
|
28
|
+
'InvalidParameterCombination',
|
|
29
|
+
'InvalidEmailAddress',
|
|
30
|
+
'MailFromDomainNotVerifiedException',
|
|
31
|
+
])
|
|
32
|
+
|
|
33
|
+
export class SesAdapter implements IMailAdapter {
|
|
34
|
+
private readonly logger = new Logger(SesAdapter.name)
|
|
35
|
+
private readonly client: SESClient
|
|
36
|
+
|
|
37
|
+
constructor(config: SesAdapterConfig) {
|
|
38
|
+
this.client = new SESClient({
|
|
39
|
+
region: config.region,
|
|
40
|
+
credentials: config.useCredentials
|
|
41
|
+
? {
|
|
42
|
+
accessKeyId: config.accessKey ?? '',
|
|
43
|
+
secretAccessKey: config.secretAccessKey ?? '',
|
|
44
|
+
}
|
|
45
|
+
: undefined,
|
|
46
|
+
})
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
public async send(payload: MailPayload): Promise<MailSendResult> {
|
|
50
|
+
try {
|
|
51
|
+
const result = await this.client.send(
|
|
52
|
+
new SendEmailCommand({
|
|
53
|
+
Source: payload.from,
|
|
54
|
+
Destination: {
|
|
55
|
+
ToAddresses: [payload.to],
|
|
56
|
+
BccAddresses: payload.bcc ?? [],
|
|
57
|
+
},
|
|
58
|
+
Message: {
|
|
59
|
+
Subject: { Charset: 'UTF-8', Data: payload.subject },
|
|
60
|
+
Body: {
|
|
61
|
+
Html: { Charset: 'UTF-8', Data: payload.html },
|
|
62
|
+
Text: { Charset: 'UTF-8', Data: payload.text ?? '' },
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
}),
|
|
66
|
+
)
|
|
67
|
+
return { success: true, status: 'sent', details: result.MessageId }
|
|
68
|
+
} catch (error) {
|
|
69
|
+
const status = classifySesError(error)
|
|
70
|
+
const message = describeError(error)
|
|
71
|
+
if (status === 'errorInvalidEmail') {
|
|
72
|
+
this.logger.warn(\`SES rejected invalid address: \${message}\`)
|
|
73
|
+
} else if (status === 'errorRejected') {
|
|
74
|
+
this.logger.warn(\`SES rejected mail: \${message}\`)
|
|
75
|
+
} else {
|
|
76
|
+
this.logger.error(\`SES send failed: \${message}\`, error instanceof Error ? error.stack : undefined)
|
|
77
|
+
}
|
|
78
|
+
return { success: false, status, details: message }
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function classifySesError(error: unknown): MailSendResultErrorStatus {
|
|
84
|
+
if (!(error instanceof Error)) {
|
|
85
|
+
return 'errorOther'
|
|
86
|
+
}
|
|
87
|
+
if (SES_INVALID_ADDRESS_ERRORS.has(error.name)) {
|
|
88
|
+
return 'errorInvalidEmail'
|
|
89
|
+
}
|
|
90
|
+
if (error.name === 'MessageRejected') {
|
|
91
|
+
return 'errorRejected'
|
|
92
|
+
}
|
|
93
|
+
return 'errorOther'
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function describeError(error: unknown): string {
|
|
97
|
+
return error instanceof Error ? \`\${error.name}: \${error.message}\` : String(error)
|
|
98
|
+
}
|
|
99
|
+
`;
|
|
100
|
+
exports.graphAdapterSource = `import { Logger } from '@nestjs/common'
|
|
101
|
+
|
|
102
|
+
import type { IMailAdapter, MailPayload, MailSendResult, MailSendResultErrorStatus } from './mail-adapter.interface'
|
|
103
|
+
|
|
104
|
+
export type GraphAdapterConfig = {
|
|
105
|
+
tenantId: string
|
|
106
|
+
clientId: string
|
|
107
|
+
clientSecret: string
|
|
108
|
+
/** The mailbox user ID or UPN the app sends as. e.g. "noreply@skaile.ai" */
|
|
109
|
+
senderUserId: string
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
type GraphTokenResponse = {
|
|
113
|
+
access_token: string
|
|
114
|
+
expires_in: number
|
|
115
|
+
token_type: string
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
type GraphErrorBody = {
|
|
119
|
+
error?: {
|
|
120
|
+
code?: string
|
|
121
|
+
message?: string
|
|
122
|
+
innerError?: unknown
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
type CachedToken = {
|
|
127
|
+
accessToken: string
|
|
128
|
+
/** Absolute epoch-ms timestamp when this token should be considered expired. */
|
|
129
|
+
expiresAt: number
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Token responses sometimes come back with jittered expiries; refresh a minute
|
|
134
|
+
* early so a request mid-flight cannot race past the hard expiry boundary.
|
|
135
|
+
*/
|
|
136
|
+
const TOKEN_REFRESH_SKEW_MS = 60_000
|
|
137
|
+
|
|
138
|
+
type FetchLike = typeof fetch
|
|
139
|
+
|
|
140
|
+
export class GraphAdapter implements IMailAdapter {
|
|
141
|
+
private readonly logger = new Logger(GraphAdapter.name)
|
|
142
|
+
private readonly fetchImpl: FetchLike
|
|
143
|
+
private cachedToken: CachedToken | null = null
|
|
144
|
+
|
|
145
|
+
constructor(
|
|
146
|
+
private readonly config: GraphAdapterConfig,
|
|
147
|
+
fetchImpl: FetchLike = fetch,
|
|
148
|
+
) {
|
|
149
|
+
this.fetchImpl = fetchImpl
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
public async send(payload: MailPayload): Promise<MailSendResult> {
|
|
153
|
+
let token: string
|
|
154
|
+
try {
|
|
155
|
+
token = await this.getAccessToken()
|
|
156
|
+
} catch (error) {
|
|
157
|
+
const message = describeError(error)
|
|
158
|
+
this.logger.error(\`Graph token acquisition failed: \${message}\`, error instanceof Error ? error.stack : undefined)
|
|
159
|
+
return { success: false, status: 'errorOther', details: message }
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const senderUserId = encodeURIComponent(this.config.senderUserId)
|
|
163
|
+
const url = \`https://graph.microsoft.com/v1.0/users/\${senderUserId}/sendMail\`
|
|
164
|
+
|
|
165
|
+
const body = {
|
|
166
|
+
message: {
|
|
167
|
+
subject: payload.subject,
|
|
168
|
+
from: { emailAddress: { address: payload.from } },
|
|
169
|
+
toRecipients: [{ emailAddress: { address: payload.to } }],
|
|
170
|
+
bccRecipients: (payload.bcc ?? []).map((address) => ({ emailAddress: { address } })),
|
|
171
|
+
body: {
|
|
172
|
+
contentType: 'HTML',
|
|
173
|
+
content: payload.html,
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
saveToSentItems: false,
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
let response: Response
|
|
180
|
+
try {
|
|
181
|
+
response = await this.fetchImpl(url, {
|
|
182
|
+
method: 'POST',
|
|
183
|
+
headers: {
|
|
184
|
+
Authorization: \`Bearer \${token}\`,
|
|
185
|
+
'Content-Type': 'application/json',
|
|
186
|
+
},
|
|
187
|
+
body: JSON.stringify(body),
|
|
188
|
+
})
|
|
189
|
+
} catch (error) {
|
|
190
|
+
const message = describeError(error)
|
|
191
|
+
this.logger.error(\`Graph send network failure: \${message}\`, error instanceof Error ? error.stack : undefined)
|
|
192
|
+
return { success: false, status: 'errorOther', details: message }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (response.status === 202) {
|
|
196
|
+
return { success: true, status: 'sent' }
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const rawBody = await response.text().catch(() => '')
|
|
200
|
+
const parsedBody = parseGraphErrorBody(rawBody)
|
|
201
|
+
const retryAfter = response.headers.get('retry-after')
|
|
202
|
+
const status = classifyGraphError(response.status, parsedBody)
|
|
203
|
+
const details = formatGraphErrorDetails({ response, parsedBody, rawBody, retryAfter })
|
|
204
|
+
|
|
205
|
+
if (status === 'errorInvalidEmail') {
|
|
206
|
+
this.logger.warn(\`Graph rejected invalid address: \${details}\`)
|
|
207
|
+
} else if (status === 'errorRejected') {
|
|
208
|
+
this.logger.warn(\`Graph rejected mail: \${details}\`)
|
|
209
|
+
} else {
|
|
210
|
+
this.logger.error(\`Graph send failed: \${details}\`)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return { success: false, status, details }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
private async getAccessToken(): Promise<string> {
|
|
217
|
+
const now = Date.now()
|
|
218
|
+
if (this.cachedToken && this.cachedToken.expiresAt > now) {
|
|
219
|
+
return this.cachedToken.accessToken
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const tokenUrl = \`https://login.microsoftonline.com/\${encodeURIComponent(this.config.tenantId)}/oauth2/v2.0/token\`
|
|
223
|
+
const params = new URLSearchParams({
|
|
224
|
+
client_id: this.config.clientId,
|
|
225
|
+
client_secret: this.config.clientSecret,
|
|
226
|
+
scope: 'https://graph.microsoft.com/.default',
|
|
227
|
+
grant_type: 'client_credentials',
|
|
228
|
+
})
|
|
229
|
+
|
|
230
|
+
const response = await this.fetchImpl(tokenUrl, {
|
|
231
|
+
method: 'POST',
|
|
232
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
233
|
+
body: params.toString(),
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
if (!response.ok) {
|
|
237
|
+
const rawBody = await response.text().catch(() => '')
|
|
238
|
+
throw new Error(\`Graph token endpoint returned \${response.status}: \${rawBody || response.statusText}\`)
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const json = (await response.json()) as GraphTokenResponse
|
|
242
|
+
if (typeof json.access_token !== 'string' || typeof json.expires_in !== 'number') {
|
|
243
|
+
throw new Error('Graph token endpoint returned malformed response')
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
this.cachedToken = {
|
|
247
|
+
accessToken: json.access_token,
|
|
248
|
+
expiresAt: Date.now() + json.expires_in * 1000 - TOKEN_REFRESH_SKEW_MS,
|
|
249
|
+
}
|
|
250
|
+
return this.cachedToken.accessToken
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function parseGraphErrorBody(raw: string): GraphErrorBody | null {
|
|
255
|
+
if (raw.length === 0) {
|
|
256
|
+
return null
|
|
257
|
+
}
|
|
258
|
+
try {
|
|
259
|
+
return JSON.parse(raw) as GraphErrorBody
|
|
260
|
+
} catch {
|
|
261
|
+
return null
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Maps Microsoft Graph send-mail failures onto our adapter-agnostic status
|
|
267
|
+
* enum. \`errorInvalidEmail\` is only used for \`ErrorInvalidRecipients\` since
|
|
268
|
+
* that is the one Graph error code that unambiguously points at a malformed
|
|
269
|
+
* recipient. \`MessageSubmissionBlocked\` is the explicit "message was
|
|
270
|
+
* rejected" signal (tenant policy, DLP, etc.); every other 4xx/5xx bucket
|
|
271
|
+
* is \`errorOther\`.
|
|
272
|
+
*/
|
|
273
|
+
export function classifyGraphError(statusCode: number, body: GraphErrorBody | null): MailSendResultErrorStatus {
|
|
274
|
+
const code = body?.error?.code
|
|
275
|
+
if (code === 'ErrorInvalidRecipients') {
|
|
276
|
+
return 'errorInvalidEmail'
|
|
277
|
+
}
|
|
278
|
+
if (code === 'MessageSubmissionBlocked' && statusCode >= 400 && statusCode < 500) {
|
|
279
|
+
return 'errorRejected'
|
|
280
|
+
}
|
|
281
|
+
return 'errorOther'
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function formatGraphErrorDetails({
|
|
285
|
+
response,
|
|
286
|
+
parsedBody,
|
|
287
|
+
rawBody,
|
|
288
|
+
retryAfter,
|
|
289
|
+
}: {
|
|
290
|
+
response: Response
|
|
291
|
+
parsedBody: GraphErrorBody | null
|
|
292
|
+
rawBody: string
|
|
293
|
+
retryAfter: string | null
|
|
294
|
+
}): string {
|
|
295
|
+
const parts: string[] = [\`HTTP \${response.status}\`]
|
|
296
|
+
const code = parsedBody?.error?.code
|
|
297
|
+
const message = parsedBody?.error?.message
|
|
298
|
+
if (code) {
|
|
299
|
+
parts.push(code)
|
|
300
|
+
}
|
|
301
|
+
if (message) {
|
|
302
|
+
parts.push(message)
|
|
303
|
+
} else if (!code && rawBody.length > 0) {
|
|
304
|
+
parts.push(rawBody)
|
|
305
|
+
}
|
|
306
|
+
if (response.status === 429 && retryAfter) {
|
|
307
|
+
parts.push(\`retry-after=\${retryAfter}\`)
|
|
308
|
+
}
|
|
309
|
+
return parts.join(': ')
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function describeError(error: unknown): string {
|
|
313
|
+
return error instanceof Error ? \`\${error.name}: \${error.message}\` : String(error)
|
|
314
|
+
}
|
|
315
|
+
`;
|
|
316
|
+
exports.graphAdapterTestSource = `import { describe, expect, it, jest } from '@jest/globals'
|
|
317
|
+
|
|
318
|
+
import { classifyGraphError, GraphAdapter } from './graph.adapter'
|
|
319
|
+
|
|
320
|
+
type FetchLike = typeof fetch
|
|
321
|
+
|
|
322
|
+
function jsonResponse(status: number, body: unknown, headers: Record<string, string> = {}): Response {
|
|
323
|
+
return new Response(JSON.stringify(body), {
|
|
324
|
+
status,
|
|
325
|
+
headers: { 'content-type': 'application/json', ...headers },
|
|
326
|
+
})
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function tokenResponse(overrides: Partial<{ access_token: string; expires_in: number }> = {}): Response {
|
|
330
|
+
return jsonResponse(200, {
|
|
331
|
+
access_token: 'token-abc',
|
|
332
|
+
expires_in: 3600,
|
|
333
|
+
token_type: 'Bearer',
|
|
334
|
+
...overrides,
|
|
335
|
+
})
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function createConfig() {
|
|
339
|
+
return {
|
|
340
|
+
tenantId: 'tenant-1',
|
|
341
|
+
clientId: 'client-1',
|
|
342
|
+
clientSecret: 'secret-1',
|
|
343
|
+
senderUserId: 'noreply@example.com',
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
describe('classifyGraphError', () => {
|
|
348
|
+
it('returns errorInvalidEmail for ErrorInvalidRecipients', () => {
|
|
349
|
+
expect(classifyGraphError(400, { error: { code: 'ErrorInvalidRecipients', message: 'bad' } })).toBe(
|
|
350
|
+
'errorInvalidEmail',
|
|
351
|
+
)
|
|
352
|
+
})
|
|
353
|
+
|
|
354
|
+
it('returns errorRejected for 4xx MessageSubmissionBlocked', () => {
|
|
355
|
+
expect(classifyGraphError(403, { error: { code: 'MessageSubmissionBlocked', message: 'blocked' } })).toBe(
|
|
356
|
+
'errorRejected',
|
|
357
|
+
)
|
|
358
|
+
})
|
|
359
|
+
|
|
360
|
+
it('returns errorOther for generic 401/403', () => {
|
|
361
|
+
expect(classifyGraphError(401, { error: { code: 'InvalidAuthenticationToken' } })).toBe('errorOther')
|
|
362
|
+
expect(classifyGraphError(403, { error: { code: 'Forbidden' } })).toBe('errorOther')
|
|
363
|
+
})
|
|
364
|
+
|
|
365
|
+
it('returns errorOther for 429 throttling', () => {
|
|
366
|
+
expect(classifyGraphError(429, { error: { code: 'TooManyRequests' } })).toBe('errorOther')
|
|
367
|
+
})
|
|
368
|
+
|
|
369
|
+
it('returns errorOther for 5xx responses', () => {
|
|
370
|
+
expect(classifyGraphError(500, { error: { code: 'InternalServerError' } })).toBe('errorOther')
|
|
371
|
+
expect(classifyGraphError(503, null)).toBe('errorOther')
|
|
372
|
+
})
|
|
373
|
+
})
|
|
374
|
+
|
|
375
|
+
describe('GraphAdapter', () => {
|
|
376
|
+
const payload = {
|
|
377
|
+
from: 'noreply@example.com',
|
|
378
|
+
to: 'user@example.com',
|
|
379
|
+
bcc: ['admin@example.com'],
|
|
380
|
+
subject: 'Hi there',
|
|
381
|
+
html: '<p>hello</p>',
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
it('acquires a token, posts sendMail, and returns success on 202', async () => {
|
|
385
|
+
const fetchMock = jest.fn() as jest.MockedFunction<FetchLike>
|
|
386
|
+
fetchMock.mockResolvedValueOnce(tokenResponse())
|
|
387
|
+
fetchMock.mockResolvedValueOnce(new Response(null, { status: 202 }))
|
|
388
|
+
|
|
389
|
+
const adapter = new GraphAdapter(createConfig(), fetchMock)
|
|
390
|
+
const result = await adapter.send(payload)
|
|
391
|
+
|
|
392
|
+
expect(result).toEqual({ success: true, status: 'sent' })
|
|
393
|
+
expect(fetchMock).toHaveBeenCalledTimes(2)
|
|
394
|
+
|
|
395
|
+
const [tokenUrl, tokenInit] = fetchMock.mock.calls[0]!
|
|
396
|
+
expect(tokenUrl).toBe('https://login.microsoftonline.com/tenant-1/oauth2/v2.0/token')
|
|
397
|
+
expect(tokenInit?.method).toBe('POST')
|
|
398
|
+
expect((tokenInit?.body as string) ?? '').toContain('grant_type=client_credentials')
|
|
399
|
+
expect((tokenInit?.body as string) ?? '').toContain('scope=https%3A%2F%2Fgraph.microsoft.com%2F.default')
|
|
400
|
+
|
|
401
|
+
const [sendUrl, sendInit] = fetchMock.mock.calls[1]!
|
|
402
|
+
expect(sendUrl).toBe('https://graph.microsoft.com/v1.0/users/noreply%40example.com/sendMail')
|
|
403
|
+
expect(sendInit?.method).toBe('POST')
|
|
404
|
+
const headers = sendInit?.headers as Record<string, string>
|
|
405
|
+
expect(headers.Authorization).toBe('Bearer token-abc')
|
|
406
|
+
expect(headers['Content-Type']).toBe('application/json')
|
|
407
|
+
expect(JSON.parse(sendInit?.body as string)).toEqual({
|
|
408
|
+
message: {
|
|
409
|
+
subject: 'Hi there',
|
|
410
|
+
from: { emailAddress: { address: 'noreply@example.com' } },
|
|
411
|
+
toRecipients: [{ emailAddress: { address: 'user@example.com' } }],
|
|
412
|
+
bccRecipients: [{ emailAddress: { address: 'admin@example.com' } }],
|
|
413
|
+
body: { contentType: 'HTML', content: '<p>hello</p>' },
|
|
414
|
+
},
|
|
415
|
+
saveToSentItems: false,
|
|
416
|
+
})
|
|
417
|
+
})
|
|
418
|
+
|
|
419
|
+
it('caches the access token across send calls', async () => {
|
|
420
|
+
const fetchMock = jest.fn() as jest.MockedFunction<FetchLike>
|
|
421
|
+
fetchMock.mockResolvedValueOnce(tokenResponse())
|
|
422
|
+
fetchMock.mockResolvedValueOnce(new Response(null, { status: 202 }))
|
|
423
|
+
fetchMock.mockResolvedValueOnce(new Response(null, { status: 202 }))
|
|
424
|
+
|
|
425
|
+
const adapter = new GraphAdapter(createConfig(), fetchMock)
|
|
426
|
+
await adapter.send(payload)
|
|
427
|
+
await adapter.send(payload)
|
|
428
|
+
|
|
429
|
+
// Token fetched once, sendMail called twice.
|
|
430
|
+
expect(fetchMock).toHaveBeenCalledTimes(3)
|
|
431
|
+
const urls = fetchMock.mock.calls.map((call) => call[0])
|
|
432
|
+
expect(urls.filter((u) => String(u).includes('/oauth2/v2.0/token'))).toHaveLength(1)
|
|
433
|
+
})
|
|
434
|
+
|
|
435
|
+
it('maps 400 ErrorInvalidRecipients to errorInvalidEmail', async () => {
|
|
436
|
+
const fetchMock = jest.fn() as jest.MockedFunction<FetchLike>
|
|
437
|
+
fetchMock.mockResolvedValueOnce(tokenResponse())
|
|
438
|
+
fetchMock.mockResolvedValueOnce(
|
|
439
|
+
jsonResponse(400, { error: { code: 'ErrorInvalidRecipients', message: 'Invalid recipient' } }),
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
const adapter = new GraphAdapter(createConfig(), fetchMock)
|
|
443
|
+
const result = await adapter.send(payload)
|
|
444
|
+
|
|
445
|
+
expect(result.success).toBe(false)
|
|
446
|
+
if (result.success) {
|
|
447
|
+
throw new Error('unreachable')
|
|
448
|
+
}
|
|
449
|
+
expect(result.status).toBe('errorInvalidEmail')
|
|
450
|
+
expect(result.details).toContain('ErrorInvalidRecipients')
|
|
451
|
+
expect(result.details).toContain('Invalid recipient')
|
|
452
|
+
})
|
|
453
|
+
|
|
454
|
+
it('maps 4xx MessageSubmissionBlocked to errorRejected', async () => {
|
|
455
|
+
const fetchMock = jest.fn() as jest.MockedFunction<FetchLike>
|
|
456
|
+
fetchMock.mockResolvedValueOnce(tokenResponse())
|
|
457
|
+
fetchMock.mockResolvedValueOnce(
|
|
458
|
+
jsonResponse(403, { error: { code: 'MessageSubmissionBlocked', message: 'Blocked by policy' } }),
|
|
459
|
+
)
|
|
460
|
+
|
|
461
|
+
const adapter = new GraphAdapter(createConfig(), fetchMock)
|
|
462
|
+
const result = await adapter.send(payload)
|
|
463
|
+
|
|
464
|
+
expect(result.success).toBe(false)
|
|
465
|
+
if (result.success) {
|
|
466
|
+
throw new Error('unreachable')
|
|
467
|
+
}
|
|
468
|
+
expect(result.status).toBe('errorRejected')
|
|
469
|
+
expect(result.details).toContain('MessageSubmissionBlocked')
|
|
470
|
+
})
|
|
471
|
+
|
|
472
|
+
it('maps 401/403 auth failures to errorOther', async () => {
|
|
473
|
+
const fetchMock = jest.fn() as jest.MockedFunction<FetchLike>
|
|
474
|
+
fetchMock.mockResolvedValueOnce(tokenResponse())
|
|
475
|
+
fetchMock.mockResolvedValueOnce(
|
|
476
|
+
jsonResponse(401, { error: { code: 'InvalidAuthenticationToken', message: 'unauth' } }),
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
const adapter = new GraphAdapter(createConfig(), fetchMock)
|
|
480
|
+
const result = await adapter.send(payload)
|
|
481
|
+
|
|
482
|
+
expect(result.success).toBe(false)
|
|
483
|
+
if (result.success) {
|
|
484
|
+
throw new Error('unreachable')
|
|
485
|
+
}
|
|
486
|
+
expect(result.status).toBe('errorOther')
|
|
487
|
+
expect(result.details).toContain('HTTP 401')
|
|
488
|
+
})
|
|
489
|
+
|
|
490
|
+
it('maps 429 to errorOther and includes retry-after in details', async () => {
|
|
491
|
+
const fetchMock = jest.fn() as jest.MockedFunction<FetchLike>
|
|
492
|
+
fetchMock.mockResolvedValueOnce(tokenResponse())
|
|
493
|
+
fetchMock.mockResolvedValueOnce(
|
|
494
|
+
jsonResponse(429, { error: { code: 'TooManyRequests', message: 'slow down' } }, { 'retry-after': '30' }),
|
|
495
|
+
)
|
|
496
|
+
|
|
497
|
+
const adapter = new GraphAdapter(createConfig(), fetchMock)
|
|
498
|
+
const result = await adapter.send(payload)
|
|
499
|
+
|
|
500
|
+
expect(result.success).toBe(false)
|
|
501
|
+
if (result.success) {
|
|
502
|
+
throw new Error('unreachable')
|
|
503
|
+
}
|
|
504
|
+
expect(result.status).toBe('errorOther')
|
|
505
|
+
expect(result.details).toContain('retry-after=30')
|
|
506
|
+
})
|
|
507
|
+
|
|
508
|
+
it('maps 5xx to errorOther', async () => {
|
|
509
|
+
const fetchMock = jest.fn() as jest.MockedFunction<FetchLike>
|
|
510
|
+
fetchMock.mockResolvedValueOnce(tokenResponse())
|
|
511
|
+
fetchMock.mockResolvedValueOnce(jsonResponse(500, { error: { code: 'InternalServerError', message: 'boom' } }))
|
|
512
|
+
|
|
513
|
+
const adapter = new GraphAdapter(createConfig(), fetchMock)
|
|
514
|
+
const result = await adapter.send(payload)
|
|
515
|
+
|
|
516
|
+
expect(result.success).toBe(false)
|
|
517
|
+
if (result.success) {
|
|
518
|
+
throw new Error('unreachable')
|
|
519
|
+
}
|
|
520
|
+
expect(result.status).toBe('errorOther')
|
|
521
|
+
expect(result.details).toContain('HTTP 500')
|
|
522
|
+
})
|
|
523
|
+
|
|
524
|
+
it('returns errorOther when token acquisition fails', async () => {
|
|
525
|
+
const fetchMock = jest.fn() as jest.MockedFunction<FetchLike>
|
|
526
|
+
fetchMock.mockResolvedValueOnce(new Response('unauthorized', { status: 401 }))
|
|
527
|
+
|
|
528
|
+
const adapter = new GraphAdapter(createConfig(), fetchMock)
|
|
529
|
+
const result = await adapter.send(payload)
|
|
530
|
+
|
|
531
|
+
expect(result.success).toBe(false)
|
|
532
|
+
if (result.success) {
|
|
533
|
+
throw new Error('unreachable')
|
|
534
|
+
}
|
|
535
|
+
expect(result.status).toBe('errorOther')
|
|
536
|
+
expect(fetchMock).toHaveBeenCalledTimes(1)
|
|
537
|
+
})
|
|
538
|
+
})
|
|
539
|
+
`;
|
|
540
|
+
exports.smtpAdapterSource = `/** Runtime verified on Node 24; Bun: untested. */
|
|
541
|
+
import { Logger } from '@nestjs/common'
|
|
542
|
+
import nodemailer, { type Transporter } from 'nodemailer'
|
|
543
|
+
|
|
544
|
+
import type { IMailAdapter, MailPayload, MailSendResult, MailSendResultErrorStatus } from './mail-adapter.interface'
|
|
545
|
+
|
|
546
|
+
export type SmtpAdapterConfig = {
|
|
547
|
+
host: string
|
|
548
|
+
port: number
|
|
549
|
+
secure: boolean
|
|
550
|
+
user: string
|
|
551
|
+
password: string
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
type NodemailerTransportOptions = {
|
|
555
|
+
host: string
|
|
556
|
+
port: number
|
|
557
|
+
secure: boolean
|
|
558
|
+
auth?: { user: string; pass: string }
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/**
|
|
562
|
+
* Builds the nodemailer \`createTransport\` options from our adapter config.
|
|
563
|
+
*
|
|
564
|
+
* Exported so the auth-gating logic can be unit-tested directly - passing a
|
|
565
|
+
* partial credential pair (only user, only password) must result in auth
|
|
566
|
+
* being omitted entirely rather than sent with an empty field.
|
|
567
|
+
*/
|
|
568
|
+
export function buildSmtpTransportOptions(config: SmtpAdapterConfig): NodemailerTransportOptions {
|
|
569
|
+
const hasAuth = config.user.length > 0 && config.password.length > 0
|
|
570
|
+
return {
|
|
571
|
+
host: config.host,
|
|
572
|
+
port: config.port,
|
|
573
|
+
secure: config.secure,
|
|
574
|
+
auth: hasAuth ? { user: config.user, pass: config.password } : undefined,
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
export class SmtpAdapter implements IMailAdapter {
|
|
579
|
+
private readonly logger = new Logger(SmtpAdapter.name)
|
|
580
|
+
private readonly transporter: Transporter
|
|
581
|
+
|
|
582
|
+
constructor(config: SmtpAdapterConfig, transporter?: Transporter) {
|
|
583
|
+
this.transporter = transporter ?? nodemailer.createTransport(buildSmtpTransportOptions(config))
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
public async send(payload: MailPayload): Promise<MailSendResult> {
|
|
587
|
+
try {
|
|
588
|
+
const info = (await this.transporter.sendMail({
|
|
589
|
+
from: payload.from,
|
|
590
|
+
to: payload.to,
|
|
591
|
+
bcc: payload.bcc,
|
|
592
|
+
subject: payload.subject,
|
|
593
|
+
html: payload.html,
|
|
594
|
+
text: payload.text,
|
|
595
|
+
})) as { messageId?: string }
|
|
596
|
+
return { success: true, status: 'sent', details: info.messageId }
|
|
597
|
+
} catch (error) {
|
|
598
|
+
const classified = classifySmtpError(error)
|
|
599
|
+
const message = describeError(error)
|
|
600
|
+
if (classified === 'errorRejected') {
|
|
601
|
+
this.logger.warn(\`SMTP rejected mail: \${message}\`)
|
|
602
|
+
} else if (classified === 'errorInvalidEmail') {
|
|
603
|
+
this.logger.warn(\`SMTP invalid address: \${message}\`)
|
|
604
|
+
} else {
|
|
605
|
+
this.logger.error(\`SMTP send failed: \${message}\`, error instanceof Error ? error.stack : undefined)
|
|
606
|
+
}
|
|
607
|
+
return { success: false, status: classified, details: message }
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* Maps nodemailer / SMTP errors onto our adapter-agnostic status enum.
|
|
614
|
+
*
|
|
615
|
+
* \`errorInvalidEmail\` is reserved for errors that unambiguously point at a
|
|
616
|
+
* malformed or syntactically-invalid address (EENVELOPE, EMESSAGE, and the
|
|
617
|
+
* classic 501/553 response codes).
|
|
618
|
+
*
|
|
619
|
+
* Every other 5xx response is bucketed into \`errorRejected\`. Note that this
|
|
620
|
+
* deliberately groups "recipient does not exist" (550 mailbox unavailable)
|
|
621
|
+
* together with "your account is blocked" (550 spam-related) - SMTP does
|
|
622
|
+
* not give us enough signal to tell them apart reliably, and splitting them
|
|
623
|
+
* would make the enum less stable. Callers needing that distinction should
|
|
624
|
+
* inspect the \`details\` string.
|
|
625
|
+
*/
|
|
626
|
+
function classifySmtpError(error: unknown): MailSendResultErrorStatus {
|
|
627
|
+
if (!(error instanceof Error)) {
|
|
628
|
+
return 'errorOther'
|
|
629
|
+
}
|
|
630
|
+
const code = (error as Error & { code?: string; responseCode?: number }).code
|
|
631
|
+
const responseCode = (error as Error & { responseCode?: number }).responseCode
|
|
632
|
+
if (code === 'EENVELOPE' || code === 'EMESSAGE' || responseCode === 501 || responseCode === 553) {
|
|
633
|
+
return 'errorInvalidEmail'
|
|
634
|
+
}
|
|
635
|
+
if (responseCode && responseCode >= 500 && responseCode < 600) {
|
|
636
|
+
return 'errorRejected'
|
|
637
|
+
}
|
|
638
|
+
return 'errorOther'
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
function describeError(error: unknown): string {
|
|
642
|
+
if (error instanceof Error) {
|
|
643
|
+
const withCode = error as Error & { code?: string; responseCode?: number }
|
|
644
|
+
const codeTag = withCode.code ?? (withCode.responseCode ? String(withCode.responseCode) : error.name)
|
|
645
|
+
return \`\${codeTag}: \${error.message}\`
|
|
646
|
+
}
|
|
647
|
+
return String(error)
|
|
648
|
+
}
|
|
649
|
+
`;
|
|
650
|
+
exports.smtpAdapterTestSource = `import { describe, expect, it, jest } from '@jest/globals'
|
|
651
|
+
import type { Transporter } from 'nodemailer'
|
|
652
|
+
|
|
653
|
+
import { buildSmtpTransportOptions, SmtpAdapter } from './smtp.adapter'
|
|
654
|
+
|
|
655
|
+
function createSpyTransporter(): { transporter: Transporter; sendMail: jest.Mock } {
|
|
656
|
+
const sendMail = jest.fn(() => Promise.resolve({ messageId: 'msg-123' }))
|
|
657
|
+
const transporter = { sendMail } as unknown as Transporter
|
|
658
|
+
return { transporter, sendMail }
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
describe('buildSmtpTransportOptions', () => {
|
|
662
|
+
const base = { host: 'smtp.example.com', port: 587, secure: false }
|
|
663
|
+
|
|
664
|
+
it('includes auth when both user and password are set', () => {
|
|
665
|
+
expect(buildSmtpTransportOptions({ ...base, user: 'alice', password: 'secret' })).toEqual({
|
|
666
|
+
...base,
|
|
667
|
+
auth: { user: 'alice', pass: 'secret' },
|
|
668
|
+
})
|
|
669
|
+
})
|
|
670
|
+
|
|
671
|
+
it('omits auth entirely when only user is set', () => {
|
|
672
|
+
expect(buildSmtpTransportOptions({ ...base, user: 'alice', password: '' }).auth).toBeUndefined()
|
|
673
|
+
})
|
|
674
|
+
|
|
675
|
+
it('omits auth entirely when only password is set', () => {
|
|
676
|
+
expect(buildSmtpTransportOptions({ ...base, user: '', password: 'secret' }).auth).toBeUndefined()
|
|
677
|
+
})
|
|
678
|
+
|
|
679
|
+
it('omits auth entirely when neither is set', () => {
|
|
680
|
+
expect(buildSmtpTransportOptions({ ...base, user: '', password: '' }).auth).toBeUndefined()
|
|
681
|
+
})
|
|
682
|
+
})
|
|
683
|
+
|
|
684
|
+
describe('SmtpAdapter', () => {
|
|
685
|
+
it('marshals the payload through the transporter and returns success with the messageId', async () => {
|
|
686
|
+
const { transporter, sendMail } = createSpyTransporter()
|
|
687
|
+
const adapter = new SmtpAdapter({ host: 'unused', port: 587, secure: false, user: '', password: '' }, transporter)
|
|
688
|
+
|
|
689
|
+
const result = await adapter.send({
|
|
690
|
+
from: 'noreply@example.com',
|
|
691
|
+
to: 'user@example.com',
|
|
692
|
+
bcc: ['admin@example.com'],
|
|
693
|
+
subject: 'Hi there',
|
|
694
|
+
html: '<p>hello</p>',
|
|
695
|
+
text: 'hello',
|
|
696
|
+
})
|
|
697
|
+
|
|
698
|
+
expect(result.success).toBe(true)
|
|
699
|
+
if (!result.success) {
|
|
700
|
+
throw new Error('unreachable')
|
|
701
|
+
}
|
|
702
|
+
expect(result.status).toBe('sent')
|
|
703
|
+
expect(result.details).toBe('msg-123')
|
|
704
|
+
|
|
705
|
+
expect(sendMail).toHaveBeenCalledTimes(1)
|
|
706
|
+
expect(sendMail).toHaveBeenCalledWith({
|
|
707
|
+
from: 'noreply@example.com',
|
|
708
|
+
to: 'user@example.com',
|
|
709
|
+
bcc: ['admin@example.com'],
|
|
710
|
+
subject: 'Hi there',
|
|
711
|
+
html: '<p>hello</p>',
|
|
712
|
+
text: 'hello',
|
|
713
|
+
})
|
|
714
|
+
})
|
|
715
|
+
|
|
716
|
+
it('classifies invalid-address errors and returns a serialized details string', async () => {
|
|
717
|
+
const invalidErr = Object.assign(new Error('Bad recipient'), { code: 'EENVELOPE', responseCode: 501 })
|
|
718
|
+
const sendMail = jest.fn(() => Promise.reject(invalidErr))
|
|
719
|
+
const adapter = new SmtpAdapter({ host: 'unused', port: 587, secure: false, user: '', password: '' }, {
|
|
720
|
+
sendMail,
|
|
721
|
+
} as unknown as Transporter)
|
|
722
|
+
|
|
723
|
+
const result = await adapter.send({
|
|
724
|
+
from: 'noreply@example.com',
|
|
725
|
+
to: 'bad',
|
|
726
|
+
subject: 'x',
|
|
727
|
+
html: '<p>x</p>',
|
|
728
|
+
})
|
|
729
|
+
|
|
730
|
+
expect(result).toEqual({
|
|
731
|
+
success: false,
|
|
732
|
+
status: 'errorInvalidEmail',
|
|
733
|
+
details: 'EENVELOPE: Bad recipient',
|
|
734
|
+
})
|
|
735
|
+
})
|
|
736
|
+
|
|
737
|
+
it('classifies 5xx rejects as errorRejected', async () => {
|
|
738
|
+
const rejected = Object.assign(new Error('Mailbox unavailable'), { responseCode: 550 })
|
|
739
|
+
const sendMail = jest.fn(() => Promise.reject(rejected))
|
|
740
|
+
const adapter = new SmtpAdapter({ host: 'unused', port: 587, secure: false, user: '', password: '' }, {
|
|
741
|
+
sendMail,
|
|
742
|
+
} as unknown as Transporter)
|
|
743
|
+
|
|
744
|
+
const result = await adapter.send({
|
|
745
|
+
from: 'noreply@example.com',
|
|
746
|
+
to: 'user@example.com',
|
|
747
|
+
subject: 'x',
|
|
748
|
+
html: '<p>x</p>',
|
|
749
|
+
})
|
|
750
|
+
|
|
751
|
+
expect(result.success).toBe(false)
|
|
752
|
+
if (result.success) {
|
|
753
|
+
throw new Error('unreachable')
|
|
754
|
+
}
|
|
755
|
+
expect(result.status).toBe('errorRejected')
|
|
756
|
+
expect(result.details).toBe('550: Mailbox unavailable')
|
|
757
|
+
})
|
|
758
|
+
})
|
|
759
|
+
`;
|
|
760
|
+
exports.emailmdRendererSource = `import { Logger } from '@nestjs/common'
|
|
761
|
+
import { render } from 'emailmd'
|
|
762
|
+
|
|
763
|
+
import { htmlEscape, stripTags, substituteVariables, substituteVariablesRaw } from './simple.renderer'
|
|
764
|
+
import type { ITemplateRenderer, RenderedMail } from './template-renderer.interface'
|
|
765
|
+
|
|
766
|
+
export class EmailmdRenderer implements ITemplateRenderer {
|
|
767
|
+
private readonly logger = new Logger(EmailmdRenderer.name)
|
|
768
|
+
|
|
769
|
+
public render(source: string, data: Record<string, unknown>): RenderedMail {
|
|
770
|
+
const substituted = substituteVariables(source, data)
|
|
771
|
+
try {
|
|
772
|
+
const { html, text } = render(substituted)
|
|
773
|
+
return { html, text }
|
|
774
|
+
} catch (error) {
|
|
775
|
+
// \`emailmd\` is a pre-1.0 package that parses markdown via MJML;
|
|
776
|
+
// malformed input, internal MJML bugs, or upstream API churn can
|
|
777
|
+
// surface as thrown errors. Swallowing them would lose the mail, but
|
|
778
|
+
// letting them propagate through the dispatcher would fail the
|
|
779
|
+
// action with a confusing stack trace. Log + fall back to a simple
|
|
780
|
+
// escaped HTML + raw plain-text render so the mail still goes out.
|
|
781
|
+
const message = error instanceof Error ? \`\${error.name}: \${error.message}\` : String(error)
|
|
782
|
+
this.logger.warn(\`emailmd render failed, falling back to plain text: \${message}\`)
|
|
783
|
+
const rawText = stripTags(substituteVariablesRaw(source, data))
|
|
784
|
+
return {
|
|
785
|
+
html: \`<pre>\${htmlEscape(rawText)}</pre>\`,
|
|
786
|
+
text: rawText,
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
`;
|
|
792
|
+
exports.emailmdRendererTestSource = `import { describe, expect, it, jest } from '@jest/globals'
|
|
793
|
+
|
|
794
|
+
jest.mock('emailmd', () => ({
|
|
795
|
+
render: jest.fn(),
|
|
796
|
+
}))
|
|
797
|
+
|
|
798
|
+
import { render as emailmdRender } from 'emailmd'
|
|
799
|
+
|
|
800
|
+
import { EmailmdRenderer } from './emailmd.renderer'
|
|
801
|
+
|
|
802
|
+
const mockedRender = emailmdRender as unknown as jest.Mock
|
|
803
|
+
|
|
804
|
+
describe('EmailmdRenderer', () => {
|
|
805
|
+
it('returns the emailmd render output on success', () => {
|
|
806
|
+
mockedRender.mockReturnValueOnce({
|
|
807
|
+
html: '<html><body>Hello</body></html>',
|
|
808
|
+
text: 'Hello',
|
|
809
|
+
meta: {},
|
|
810
|
+
})
|
|
811
|
+
|
|
812
|
+
const renderer = new EmailmdRenderer()
|
|
813
|
+
const result = renderer.render('Hello {{name}}', { name: 'Ada' })
|
|
814
|
+
|
|
815
|
+
expect(result).toEqual({
|
|
816
|
+
html: '<html><body>Hello</body></html>',
|
|
817
|
+
text: 'Hello',
|
|
818
|
+
})
|
|
819
|
+
expect(mockedRender).toHaveBeenCalledWith('Hello Ada')
|
|
820
|
+
})
|
|
821
|
+
|
|
822
|
+
it('falls back to a plaintext render when emailmd throws', () => {
|
|
823
|
+
mockedRender.mockImplementationOnce(() => {
|
|
824
|
+
throw new Error('MJML parse error')
|
|
825
|
+
})
|
|
826
|
+
|
|
827
|
+
const renderer = new EmailmdRenderer()
|
|
828
|
+
const result = renderer.render('Hello {{name}}', { name: 'Ada' })
|
|
829
|
+
|
|
830
|
+
expect(result.text).toBe('Hello Ada')
|
|
831
|
+
expect(result.html).toBe('<pre>Hello Ada</pre>')
|
|
832
|
+
})
|
|
833
|
+
|
|
834
|
+
it('preserves raw characters in fallback text and escapes them in fallback html', () => {
|
|
835
|
+
mockedRender.mockImplementationOnce(() => {
|
|
836
|
+
throw new Error('boom')
|
|
837
|
+
})
|
|
838
|
+
|
|
839
|
+
const renderer = new EmailmdRenderer()
|
|
840
|
+
const result = renderer.render('Plain {{name}}', { name: '<script>alert(1)</script>' })
|
|
841
|
+
|
|
842
|
+
// Text body is the plain-text MIME part — stripTags removes the
|
|
843
|
+
// literal \`<script>\` wrapper and \`alert(1)\` survives.
|
|
844
|
+
expect(result.text).toBe('Plain alert(1)')
|
|
845
|
+
// HTML body wraps the text in \`<pre>\` with all angle brackets escaped.
|
|
846
|
+
expect(result.html).toBe('<pre>Plain alert(1)</pre>')
|
|
847
|
+
})
|
|
848
|
+
})
|
|
849
|
+
`;
|
|
850
|
+
//# sourceMappingURL=conditional-files.js.map
|