@prunellejs/mail 0.7.2 → 0.7.3

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 (3) hide show
  1. package/package.json +2 -2
  2. package/src/mime.ts +163 -0
  3. package/src/smtp.ts +100 -211
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/mail",
3
- "version": "0.7.2",
3
+ "version": "0.7.3",
4
4
  "description": "Zero-dependency email delivery (JSX/TSX templates, SMTP/SMTPS, Resend, Postmark, MAIL_URL, @prunellejs/jobs retries) and dev outbox/preview plugin for Prunelle",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -21,6 +21,6 @@
21
21
  "directory": "packages/plugin-mail"
22
22
  },
23
23
  "peerDependencies": {
24
- "prunelle": "^0.7.2"
24
+ "prunelle": "^0.7.3"
25
25
  }
26
26
  }
package/src/mime.ts ADDED
@@ -0,0 +1,163 @@
1
+ // RFC 5322 / RFC 2047 / RFC 2045 MIME message formatting and RFC 5321 DATA dot-stuffing.
2
+
3
+ import type { SentMail } from './types'
4
+ import { assertNoHeaderInjection } from './types'
5
+
6
+ const NON_ASCII_RE = /[^\x20-\x7E]/
7
+ const WHITESPACE_OR_ANGLE_RE = /[\s<>]/
8
+
9
+ // An encoded word is at most 75 characters; 42 bytes make 56 base64 chars + 12 wrapper chars = 68, fitting after `Reply-To: ` within 78.
10
+ const ENCODED_WORD_MAX_BYTES = 42
11
+ const HEADER_LINE_MAX = 78
12
+ const QP_LINE_MAX = 76
13
+ const HEADER_TOKEN_RE = /([ \t]*)([^ \t]+)/g
14
+ const ANGLE_ADDRESS_RE = /^\s*(.*?)\s*(<[^<>]+>)\s*$/
15
+ const QUOTED_NAME_RE = /^"(.*)"$/
16
+
17
+ export function validateEhloHost(value: string): string {
18
+ assertNoHeaderInjection(value, 'ehloHost')
19
+ if (value.length === 0 || WHITESPACE_OR_ANGLE_RE.test(value))
20
+ throw new RangeError('@prunellejs/mail (smtp): `ehloHost` must be a non-empty hostname without whitespace or angle brackets')
21
+ return value
22
+ }
23
+
24
+ /** Splits non-ASCII text into space-separated RFC 2047 encoded words, never cutting a UTF-8 sequence. */
25
+ function encodeRfc2047(value: string): string {
26
+ if (!NON_ASCII_RE.test(value))
27
+ return value
28
+ const words: string[] = []
29
+ let chunk = ''
30
+ let chunkBytes = 0
31
+ for (const char of value) {
32
+ const bytes = Buffer.byteLength(char, 'utf8')
33
+ if (chunkBytes + bytes > ENCODED_WORD_MAX_BYTES) {
34
+ words.push(chunk)
35
+ chunk = ''
36
+ chunkBytes = 0
37
+ }
38
+ chunk += char
39
+ chunkBytes += bytes
40
+ }
41
+ words.push(chunk)
42
+ return words.map(word => `=?UTF-8?B?${Buffer.from(word, 'utf8').toString('base64')}?=`).join(' ')
43
+ }
44
+
45
+ /** Encodes the display name of `Name <addr>` when it is not ASCII; anything else is returned as it is. */
46
+ function encodeAddressHeader(address: string): string {
47
+ const match = ANGLE_ADDRESS_RE.exec(address)
48
+ if (match === null || !NON_ASCII_RE.test(match[1]!))
49
+ return address
50
+ const name = match[1]!.replace(QUOTED_NAME_RE, '$1').replace(/\\(.)/g, '$1')
51
+ return `${encodeRfc2047(name)} ${match[2]!}`
52
+ }
53
+
54
+ /** Folds a header at whitespace so no line passes 78 characters (RFC 5322 §2.2.3); a token longer than that stays whole. */
55
+ function foldHeader(name: string, value: string): string {
56
+ if (value.length === 0)
57
+ return `${name}:`
58
+ const rest = ` ${value}`
59
+ const lines: string[] = []
60
+ let line = `${name}:`
61
+ let hasToken = false
62
+ let lastIndex = 0
63
+ for (const match of rest.matchAll(HEADER_TOKEN_RE)) {
64
+ const ws = match[1]!
65
+ const token = match[2]!
66
+ lastIndex = match.index! + match[0]!.length
67
+ if (hasToken && ws.length > 0 && line.length + ws.length + token.length > HEADER_LINE_MAX) {
68
+ lines.push(line)
69
+ line = `${ws}${token}`
70
+ }
71
+ else {
72
+ line += `${ws}${token}`
73
+ }
74
+ hasToken = true
75
+ }
76
+ if (lastIndex < rest.length)
77
+ line += rest.slice(lastIndex)
78
+ lines.push(line)
79
+ return lines.join('\r\n')
80
+ }
81
+
82
+ function quotedPrintableLine(line: string): string {
83
+ const bytes = Buffer.from(line, 'utf8')
84
+ const out: string[] = []
85
+ let current = ''
86
+ for (const [i, byte] of bytes.entries()) {
87
+ const isLast = i === bytes.length - 1
88
+ const literal = (byte >= 33 && byte <= 126 && byte !== 61) || ((byte === 32 || byte === 9) && !isLast)
89
+ const token = literal ? String.fromCharCode(byte) : `=${byte.toString(16).toUpperCase().padStart(2, '0')}`
90
+ const fits = isLast ? current.length + token.length <= QP_LINE_MAX : current.length + token.length < QP_LINE_MAX
91
+ if (!fits) {
92
+ out.push(`${current}=`)
93
+ current = ''
94
+ }
95
+ current += token
96
+ }
97
+ out.push(current)
98
+ return out.join('\r\n')
99
+ }
100
+
101
+ function normalizeCrlf(text: string): string {
102
+ return text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').replace(/\n/g, '\r\n')
103
+ }
104
+
105
+ /** RFC 2045 quoted-printable: 7-bit, lines of at most 76 characters with soft breaks, so the body needs neither 8BITMIME nor a line under 998. */
106
+ function encodeQuotedPrintable(text: string): string {
107
+ return normalizeCrlf(text).split('\r\n').map(quotedPrintableLine).join('\r\n')
108
+ }
109
+
110
+ /** Applies RFC 5321 §4.5.2 dot-stuffing and appends the terminating `\r\n.\r\n`. */
111
+ export function dotStuffSmtpData(rawMessage: string): string {
112
+ const normalized = normalizeCrlf(rawMessage)
113
+ const stuffed = normalized.replace(/(^|\r\n)\./g, '$1..')
114
+ return stuffed.endsWith('\r\n') ? `${stuffed}.\r\n` : `${stuffed}\r\n.\r\n`
115
+ }
116
+
117
+ /** Builds an RFC 5322 + MIME message (using `multipart/alternative` when both `text` and `html` are present). */
118
+ export function buildMimeMessage(mail: SentMail, domain = 'localhost'): string {
119
+ const safeDomain = validateEhloHost(domain)
120
+ for (const [label, value] of [['from', mail.from], ['replyTo', mail.replyTo ?? ''], ['subject', mail.subject], ['id', mail.id], ...mail.to.map(to => ['to', to] as const)] as const)
121
+ assertNoHeaderInjection(value, label)
122
+ const headers = [
123
+ foldHeader('From', encodeAddressHeader(mail.from)),
124
+ foldHeader('To', mail.to.map(encodeAddressHeader).join(', ')),
125
+ ...(mail.replyTo !== undefined ? [foldHeader('Reply-To', encodeAddressHeader(mail.replyTo))] : []),
126
+ foldHeader('Subject', encodeRfc2047(mail.subject)),
127
+ `Date: ${new Date(mail.sentAt).toUTCString()}`,
128
+ `Message-ID: <${mail.id}@${safeDomain}>`,
129
+ 'MIME-Version: 1.0',
130
+ ]
131
+
132
+ const hasText = mail.text !== undefined
133
+ const hasHtml = mail.html !== undefined
134
+
135
+ if (hasText && hasHtml) {
136
+ const boundary = `----=_PruMail_${mail.id.replace(/[^A-Za-z0-9]/g, '')}`
137
+ headers.push(`Content-Type: multipart/alternative; boundary="${boundary}"`)
138
+ return [
139
+ headers.join('\r\n'),
140
+ '',
141
+ `--${boundary}`,
142
+ 'Content-Type: text/plain; charset=utf-8',
143
+ 'Content-Transfer-Encoding: quoted-printable',
144
+ '',
145
+ encodeQuotedPrintable(mail.text!),
146
+ `--${boundary}`,
147
+ 'Content-Type: text/html; charset=utf-8',
148
+ 'Content-Transfer-Encoding: quoted-printable',
149
+ '',
150
+ encodeQuotedPrintable(mail.html!),
151
+ `--${boundary}--`,
152
+ '',
153
+ ].join('\r\n')
154
+ }
155
+
156
+ if (hasHtml) {
157
+ headers.push('Content-Type: text/html; charset=utf-8', 'Content-Transfer-Encoding: quoted-printable')
158
+ return `${headers.join('\r\n')}\r\n\r\n${encodeQuotedPrintable(mail.html!)}\r\n`
159
+ }
160
+
161
+ headers.push('Content-Type: text/plain; charset=utf-8', 'Content-Transfer-Encoding: quoted-printable')
162
+ return `${headers.join('\r\n')}\r\n\r\n${encodeQuotedPrintable(mail.text ?? '')}\r\n`
163
+ }
package/src/smtp.ts CHANGED
@@ -4,7 +4,10 @@
4
4
  import type { Socket, SocketHandler, TLSOptions } from 'bun'
5
5
  import type { MailTransport, SentMail } from './types'
6
6
  import { isLoopbackHost } from 'prunelle/internal/server'
7
- import { assertNoHeaderInjection, extractEmailAddress } from './types'
7
+ import { buildMimeMessage, dotStuffSmtpData, validateEhloHost } from './mime'
8
+ import { extractEmailAddress } from './types'
9
+
10
+ export { buildMimeMessage, dotStuffSmtpData } from './mime'
8
11
 
9
12
  export interface SmtpOptions {
10
13
  host: string
@@ -43,152 +46,6 @@ const DEFAULT_SMTP_CONNECTIONS = 4
43
46
  const MAX_REPLY_BYTES = 64 * 1024
44
47
  const MAX_QUEUED_REPLIES = 100
45
48
  const SMTP_LINE_RE = /^(\d{3})([ -])(.*)$/
46
- const NON_ASCII_RE = /[^\x20-\x7E]/
47
- const WHITESPACE_OR_ANGLE_RE = /[\s<>]/
48
-
49
- function validateEhloHost(value: string): string {
50
- assertNoHeaderInjection(value, 'ehloHost')
51
- if (value.length === 0 || WHITESPACE_OR_ANGLE_RE.test(value))
52
- throw new RangeError('@prunellejs/mail (smtp): `ehloHost` must be a non-empty hostname without whitespace or angle brackets')
53
- return value
54
- }
55
-
56
- // An encoded word is at most 75 characters: 45 bytes of text make 60 base64 characters plus the 12 of `=?UTF-8?B?` and `?=`.
57
- const ENCODED_WORD_MAX_BYTES = 45
58
- const HEADER_LINE_MAX = 78
59
- const QP_LINE_MAX = 76
60
- const ANGLE_ADDRESS_RE = /^\s*(.*?)\s*(<[^<>]+>)\s*$/
61
- const QUOTED_NAME_RE = /^"(.*)"$/
62
-
63
- /** Splits non-ASCII text into space-separated RFC 2047 encoded words, never cutting a UTF-8 sequence. */
64
- function encodeRfc2047(value: string): string {
65
- if (!NON_ASCII_RE.test(value))
66
- return value
67
- const words: string[] = []
68
- let chunk = ''
69
- let chunkBytes = 0
70
- for (const char of value) {
71
- const bytes = Buffer.byteLength(char, 'utf8')
72
- if (chunkBytes + bytes > ENCODED_WORD_MAX_BYTES) {
73
- words.push(chunk)
74
- chunk = ''
75
- chunkBytes = 0
76
- }
77
- chunk += char
78
- chunkBytes += bytes
79
- }
80
- words.push(chunk)
81
- return words.map(word => `=?UTF-8?B?${Buffer.from(word, 'utf8').toString('base64')}?=`).join(' ')
82
- }
83
-
84
- /** Encodes the display name of `Name <addr>` when it is not ASCII; anything else is returned as it is. */
85
- function encodeAddressHeader(address: string): string {
86
- const match = ANGLE_ADDRESS_RE.exec(address)
87
- if (match === null || !NON_ASCII_RE.test(match[1]!))
88
- return address
89
- const name = match[1]!.replace(QUOTED_NAME_RE, '$1').replace(/\\(.)/g, '$1')
90
- return `${encodeRfc2047(name)} ${match[2]!}`
91
- }
92
-
93
- /** Folds a header at whitespace so no line passes 78 characters (RFC 5322 §2.2.3); a token longer than that stays whole. */
94
- function foldHeader(name: string, value: string): string {
95
- const lines: string[] = []
96
- let line = `${name}:`
97
- for (const token of value.split(' ')) {
98
- if (line.length + 1 + token.length > HEADER_LINE_MAX) {
99
- lines.push(line)
100
- line = ` ${token}`
101
- }
102
- else {
103
- line += ` ${token}`
104
- }
105
- }
106
- lines.push(line)
107
- return lines.join('\r\n')
108
- }
109
-
110
- function quotedPrintableLine(line: string): string {
111
- const bytes = Buffer.from(line, 'utf8')
112
- const out: string[] = []
113
- let current = ''
114
- for (const [i, byte] of bytes.entries()) {
115
- const isLast = i === bytes.length - 1
116
- const literal = (byte >= 33 && byte <= 126 && byte !== 61) || ((byte === 32 || byte === 9) && !isLast)
117
- const token = literal ? String.fromCharCode(byte) : `=${byte.toString(16).toUpperCase().padStart(2, '0')}`
118
- const fits = isLast ? current.length + token.length <= QP_LINE_MAX : current.length + token.length < QP_LINE_MAX
119
- if (!fits) {
120
- out.push(`${current}=`)
121
- current = ''
122
- }
123
- current += token
124
- }
125
- out.push(current)
126
- return out.join('\r\n')
127
- }
128
-
129
- /** RFC 2045 quoted-printable: 7-bit, lines of at most 76 characters with soft breaks, so the body needs neither 8BITMIME nor a line under 998. */
130
- function encodeQuotedPrintable(text: string): string {
131
- return normalizeCrlf(text).split('\r\n').map(quotedPrintableLine).join('\r\n')
132
- }
133
-
134
- function normalizeCrlf(text: string): string {
135
- return text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').replace(/\n/g, '\r\n')
136
- }
137
-
138
- /** Applies RFC 5321 §4.5.2 dot-stuffing and appends the terminating `\r\n.\r\n`. */
139
- export function dotStuffSmtpData(rawMessage: string): string {
140
- const normalized = normalizeCrlf(rawMessage)
141
- const stuffed = normalized.replace(/(^|\r\n)\./g, '$1..')
142
- return stuffed.endsWith('\r\n') ? `${stuffed}.\r\n` : `${stuffed}\r\n.\r\n`
143
- }
144
-
145
- /** Builds an RFC 5322 + MIME message (using `multipart/alternative` when both `text` and `html` are present). */
146
- export function buildMimeMessage(mail: SentMail, domain = 'localhost'): string {
147
- const safeDomain = validateEhloHost(domain)
148
- for (const [label, value] of [['from', mail.from], ['replyTo', mail.replyTo ?? ''], ['subject', mail.subject], ['id', mail.id], ...mail.to.map(to => ['to', to] as const)] as const)
149
- assertNoHeaderInjection(value, label)
150
- const headers = [
151
- foldHeader('From', encodeAddressHeader(mail.from)),
152
- foldHeader('To', mail.to.map(encodeAddressHeader).join(', ')),
153
- ...(mail.replyTo !== undefined ? [foldHeader('Reply-To', encodeAddressHeader(mail.replyTo))] : []),
154
- foldHeader('Subject', encodeRfc2047(mail.subject)),
155
- `Date: ${new Date(mail.sentAt).toUTCString()}`,
156
- `Message-ID: <${mail.id}@${safeDomain}>`,
157
- 'MIME-Version: 1.0',
158
- ]
159
-
160
- const hasText = mail.text !== undefined
161
- const hasHtml = mail.html !== undefined
162
-
163
- if (hasText && hasHtml) {
164
- const boundary = `----=_PruMail_${mail.id.replace(/[^A-Za-z0-9]/g, '')}`
165
- headers.push(`Content-Type: multipart/alternative; boundary="${boundary}"`)
166
- return [
167
- headers.join('\r\n'),
168
- '',
169
- `--${boundary}`,
170
- 'Content-Type: text/plain; charset=utf-8',
171
- 'Content-Transfer-Encoding: quoted-printable',
172
- '',
173
- encodeQuotedPrintable(mail.text!),
174
- `--${boundary}`,
175
- 'Content-Type: text/html; charset=utf-8',
176
- 'Content-Transfer-Encoding: quoted-printable',
177
- '',
178
- encodeQuotedPrintable(mail.html!),
179
- `--${boundary}--`,
180
- '',
181
- ].join('\r\n')
182
- }
183
-
184
- if (hasHtml) {
185
- headers.push('Content-Type: text/html; charset=utf-8', 'Content-Transfer-Encoding: quoted-printable')
186
- return `${headers.join('\r\n')}\r\n\r\n${encodeQuotedPrintable(mail.html!)}\r\n`
187
- }
188
-
189
- headers.push('Content-Type: text/plain; charset=utf-8', 'Content-Transfer-Encoding: quoted-printable')
190
- return `${headers.join('\r\n')}\r\n\r\n${encodeQuotedPrintable(mail.text ?? '')}\r\n`
191
- }
192
49
 
193
50
  interface PendingRead {
194
51
  resolve: (res: SmtpResponse) => void
@@ -202,15 +59,24 @@ interface PendingDrain {
202
59
  timer: ReturnType<typeof setTimeout>
203
60
  }
204
61
 
62
+ interface QueuedResponse {
63
+ res: SmtpResponse
64
+ bytes: number
65
+ }
66
+
67
+ const EMPTY_BYTES = new Uint8Array(0)
68
+
205
69
  class SmtpConnection {
206
70
  private socket: Socket<undefined> | undefined
207
- private buffer = ''
71
+ private rawBuffer: Uint8Array = EMPTY_BYTES
208
72
  private multiCode: number | undefined
209
73
  private multiLines: string[] = []
210
- private readonly responses: SmtpResponse[] = []
74
+ private readonly responses: QueuedResponse[] = []
211
75
  private unexpectedLines = 0
212
76
  private replyBytes = 0
77
+ private currentReplyBytes = 0
213
78
  private generation = 0
79
+ private pendingConnect: { reject: (err: Error) => void, timer: ReturnType<typeof setTimeout> } | undefined
214
80
  private pendingRead: PendingRead | undefined
215
81
  private pendingDrain: PendingDrain | undefined
216
82
  private pendingHandshake: { resolve: () => void, reject: (err: Error) => void, timer: ReturnType<typeof setTimeout> } | undefined
@@ -221,12 +87,13 @@ class SmtpConnection {
221
87
  constructor(private readonly timeoutMs: number) {}
222
88
 
223
89
  private resetParser(): void {
224
- this.buffer = ''
90
+ this.rawBuffer = EMPTY_BYTES
225
91
  this.multiCode = undefined
226
92
  this.multiLines = []
227
93
  this.responses.length = 0
228
94
  this.unexpectedLines = 0
229
95
  this.replyBytes = 0
96
+ this.currentReplyBytes = 0
230
97
  this.decoder = new TextDecoder()
231
98
  }
232
99
 
@@ -235,7 +102,7 @@ class SmtpConnection {
235
102
  data: (_socket, chunk) => {
236
103
  if (gen !== this.generation)
237
104
  return
238
- this.onChunk(this.decoder.decode(chunk, { stream: true }))
105
+ this.onChunk(chunk)
239
106
  },
240
107
  drain: () => {
241
108
  if (gen !== this.generation)
@@ -279,84 +146,99 @@ class SmtpConnection {
279
146
  }
280
147
  }
281
148
 
282
- private onChunk(text: string): void {
283
- this.replyBytes += text.length
284
- if (this.replyBytes > MAX_REPLY_BYTES || this.responses.length > MAX_QUEUED_REPLIES) {
285
- this.fail(new Error(`@prunellejs/mail (smtp): the server's reply passed ${MAX_REPLY_BYTES} bytes, so the connection was dropped`))
286
- this.close()
149
+ private dropLimit(message: string): void {
150
+ this.responses.length = 0
151
+ this.replyBytes = 0
152
+ this.currentReplyBytes = 0
153
+ this.fail(new Error(message))
154
+ this.close()
155
+ }
156
+
157
+ private onChunk(chunk: Uint8Array): void {
158
+ this.replyBytes += chunk.byteLength
159
+ if (this.replyBytes > MAX_REPLY_BYTES) {
160
+ this.dropLimit(`@prunellejs/mail (smtp): the server's reply passed ${MAX_REPLY_BYTES} bytes, so the connection was dropped`)
287
161
  return
288
162
  }
289
- this.buffer += text
290
- for (;;) {
291
- const nl = this.buffer.indexOf('\n')
163
+ const data = this.rawBuffer.length === 0 ? chunk : Buffer.concat([this.rawBuffer, chunk])
164
+ let offset = 0
165
+ while (!this.closed) {
166
+ const nl = data.indexOf(0x0a, offset)
292
167
  if (nl === -1)
293
168
  break
294
- const line = this.buffer.slice(0, nl).replace(/\r$/, '')
295
- this.buffer = this.buffer.slice(nl + 1)
296
- this.parseLine(line)
169
+ const lineBytes = nl + 1 - offset
170
+ const end = nl > offset && data[nl - 1] === 0x0d ? nl - 1 : nl
171
+ const line = this.decoder.decode(data.subarray(offset, end))
172
+ offset = nl + 1
173
+ this.parseLine(line, lineBytes)
297
174
  }
175
+ this.rawBuffer = this.closed || offset >= data.length ? EMPTY_BYTES : Uint8Array.from(data.subarray(offset))
298
176
  }
299
177
 
300
- private parseLine(line: string): void {
178
+ private parseLine(line: string, lineBytes: number): void {
301
179
  const match = SMTP_LINE_RE.exec(line)
302
180
  if (match === null) {
303
- if (this.multiCode !== undefined)
181
+ if (this.multiCode !== undefined) {
182
+ this.currentReplyBytes += lineBytes
304
183
  this.multiLines.push(line)
305
- else
184
+ }
185
+ else {
306
186
  this.unexpectedLines++
187
+ }
307
188
  return
308
189
  }
309
190
  const code = Number(match[1])
310
191
  const sep = match[2]
311
192
  const msg = match[3] ?? ''
193
+ this.currentReplyBytes += lineBytes
312
194
  if (sep === '-') {
313
195
  this.multiCode = code
314
196
  this.multiLines.push(msg)
315
197
  return
316
198
  }
317
199
  const lines = this.multiCode === code ? [...this.multiLines, msg] : [msg]
200
+ const bytes = this.currentReplyBytes
318
201
  this.multiCode = undefined
319
202
  this.multiLines = []
320
- this.deliverResponse({ code, lines })
203
+ this.currentReplyBytes = 0
204
+ this.deliverResponse({ code, lines }, bytes)
321
205
  }
322
206
 
323
- private deliverResponse(res: SmtpResponse): void {
324
- this.replyBytes = 0
207
+ private deliverResponse(res: SmtpResponse, bytes: number): void {
325
208
  const waiter = this.pendingRead
326
209
  if (waiter !== undefined) {
210
+ this.replyBytes = Math.max(0, this.replyBytes - bytes)
327
211
  this.pendingRead = undefined
328
212
  clearTimeout(waiter.timer)
329
213
  waiter.resolve(res)
330
214
  return
331
215
  }
332
- this.responses.push(res)
216
+ if (this.responses.length >= MAX_QUEUED_REPLIES) {
217
+ this.dropLimit(`@prunellejs/mail (smtp): the server queued more than ${MAX_QUEUED_REPLIES} replies, so the connection was dropped`)
218
+ return
219
+ }
220
+ this.responses.push({ res, bytes })
333
221
  }
334
222
 
335
223
  private fail(err: Error): void {
336
224
  if (this.fatalError === undefined)
337
225
  this.fatalError = err
338
- const r = this.pendingRead
339
- if (r !== undefined) {
340
- this.pendingRead = undefined
341
- clearTimeout(r.timer)
342
- r.reject(err)
343
- }
344
- const d = this.pendingDrain
345
- if (d !== undefined) {
346
- this.pendingDrain = undefined
347
- clearTimeout(d.timer)
348
- d.reject(err)
349
- }
350
- const h = this.pendingHandshake
351
- if (h !== undefined) {
352
- this.pendingHandshake = undefined
353
- clearTimeout(h.timer)
354
- h.reject(err)
226
+ for (const waiter of [this.pendingConnect, this.pendingRead, this.pendingDrain, this.pendingHandshake]) {
227
+ if (waiter !== undefined) {
228
+ clearTimeout(waiter.timer)
229
+ waiter.reject(err)
230
+ }
355
231
  }
232
+ this.pendingConnect = undefined
233
+ this.pendingRead = undefined
234
+ this.pendingDrain = undefined
235
+ this.pendingHandshake = undefined
356
236
  }
357
237
 
358
238
  async connect(host: string, port: number, tls: TLSOptions | false): Promise<void> {
359
- let timedOut = false
239
+ if (this.closed || this.fatalError !== undefined)
240
+ throw this.fatalError ?? new Error('@prunellejs/mail (smtp): connection closed')
241
+ let aborted = false
360
242
  const gen = this.generation
361
243
  const connectPromise = Bun.connect<undefined>({
362
244
  hostname: host,
@@ -364,15 +246,22 @@ class SmtpConnection {
364
246
  tls: tls === false ? false : tls,
365
247
  socket: this.makeHandler(gen),
366
248
  })
367
- let timer: ReturnType<typeof setTimeout> | undefined
368
- const timeoutPromise = new Promise<never>((_, reject) => {
369
- timer = setTimeout(() => {
370
- timedOut = true
249
+ const waiterPromise = new Promise<never>((_, reject) => {
250
+ const timer = setTimeout(() => {
251
+ aborted = true
252
+ this.pendingConnect = undefined
371
253
  reject(new Error(`@prunellejs/mail (smtp): connect timed out after ${this.timeoutMs}ms`))
372
254
  }, this.timeoutMs)
255
+ this.pendingConnect = {
256
+ reject: (err) => {
257
+ aborted = true
258
+ reject(err)
259
+ },
260
+ timer,
261
+ }
373
262
  })
374
263
  try {
375
- const sock = await Promise.race([connectPromise, timeoutPromise])
264
+ const sock = await Promise.race([connectPromise, waiterPromise])
376
265
  if (this.closed) {
377
266
  sock.end()
378
267
  throw this.fatalError ?? new Error('@prunellejs/mail (smtp): connection closed')
@@ -380,7 +269,7 @@ class SmtpConnection {
380
269
  this.socket = sock
381
270
  }
382
271
  catch (err) {
383
- if (timedOut) {
272
+ if (aborted) {
384
273
  this.generation++
385
274
  // Close a late-resolving socket and swallow late rejections so none become unhandled.
386
275
  void connectPromise.then(
@@ -393,17 +282,17 @@ class SmtpConnection {
393
282
  throw err
394
283
  }
395
284
  finally {
396
- if (timer !== undefined)
397
- clearTimeout(timer)
285
+ if (this.pendingConnect !== undefined) {
286
+ clearTimeout(this.pendingConnect.timer)
287
+ this.pendingConnect = undefined
288
+ }
398
289
  }
399
290
  }
400
291
 
401
292
  async upgradeTls(tls: TLSOptions): Promise<void> {
402
293
  if (this.socket === undefined)
403
294
  throw new Error('@prunellejs/mail (smtp): socket is not connected')
404
- const trailingBytes = this.decoder.decode()
405
- const hasBufferedPlaintext = trailingBytes.length > 0
406
- || this.buffer.length > 0
295
+ const hasBufferedPlaintext = this.rawBuffer.length > 0
407
296
  || this.responses.length > 0
408
297
  || this.multiCode !== undefined
409
298
  || this.multiLines.length > 0
@@ -426,8 +315,11 @@ class SmtpConnection {
426
315
  }
427
316
 
428
317
  readResponse(): Promise<SmtpResponse> {
429
- if (this.responses.length > 0)
430
- return Promise.resolve(this.responses.shift()!)
318
+ if (this.responses.length > 0) {
319
+ const next = this.responses.shift()!
320
+ this.replyBytes = Math.max(0, this.replyBytes - next.bytes)
321
+ return Promise.resolve(next.res)
322
+ }
431
323
  if (this.fatalError !== undefined)
432
324
  return Promise.reject(this.fatalError)
433
325
  return new Promise<SmtpResponse>((resolve, reject) => {
@@ -472,6 +364,7 @@ class SmtpConnection {
472
364
 
473
365
  /** Ends the send: whatever waits on this connection fails with `err`. */
474
366
  abort(err: Error): void {
367
+ this.responses.length = 0
475
368
  this.fail(err)
476
369
  this.close()
477
370
  }
@@ -479,18 +372,14 @@ class SmtpConnection {
479
372
  close(): void {
480
373
  this.closed = true
481
374
  this.generation++
482
- if (this.pendingRead !== undefined) {
483
- clearTimeout(this.pendingRead.timer)
484
- this.pendingRead = undefined
485
- }
486
- if (this.pendingDrain !== undefined) {
487
- clearTimeout(this.pendingDrain.timer)
488
- this.pendingDrain = undefined
489
- }
490
- if (this.pendingHandshake !== undefined) {
491
- clearTimeout(this.pendingHandshake.timer)
492
- this.pendingHandshake = undefined
375
+ for (const waiter of [this.pendingConnect, this.pendingRead, this.pendingDrain, this.pendingHandshake]) {
376
+ if (waiter !== undefined)
377
+ clearTimeout(waiter.timer)
493
378
  }
379
+ this.pendingConnect = undefined
380
+ this.pendingRead = undefined
381
+ this.pendingDrain = undefined
382
+ this.pendingHandshake = undefined
494
383
  if (this.socket !== undefined) {
495
384
  this.socket.end()
496
385
  this.socket = undefined