@fabrika/email 0.9.0-dev.2 → 0.9.0-dev.21

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.
@@ -0,0 +1,136 @@
1
+ // Postmark's Email API (https://postmarkapp.com/developer/api/email-api), built from its documentation and verified on a
2
+ // live server in October 2026. It has no idempotency key; a 200 means Postmark took the message.
3
+
4
+ import { z } from 'zod'
5
+ import { type EmailProvider, parseProviderVariables } from './config.js'
6
+ import { base64Of } from './content.js'
7
+ import { EmailDeliveryError, type EmailMessage, type EmailSenderCapabilities, oneClickUnsubscribeHeaders } from './email.js'
8
+ import {
9
+ credentialVariable,
10
+ formatMailbox,
11
+ type HttpEmailRequest,
12
+ HttpEmailSender,
13
+ type HttpEmailSenderOptions,
14
+ isChannelName,
15
+ isCredential,
16
+ optionalVariable,
17
+ } from './http-sender.js'
18
+ import type { ProviderResponse } from './http.js'
19
+
20
+ const POSTMARK_EMAIL_URL = 'https://api.postmarkapp.com/email'
21
+ /** The ID Postmark suggests for a server's broadcast stream. */
22
+ const DEFAULT_BROADCAST_STREAM = 'broadcast'
23
+ const postmarkSuccessSchema = z.object({ MessageID: z.string(), ErrorCode: z.literal(0) })
24
+ /** A refusal's `ErrorCode` is a documented number; its `Message` is free text and is never read. */
25
+ const postmarkErrorSchema = z.object({ ErrorCode: z.number() })
26
+ /** Out of credits: sending resumes once the account has them again. */
27
+ const OUT_OF_CREDITS = 405
28
+ /** The sender signature is missing (400) or unconfirmed (401), or the account is pending approval (412, 413). */
29
+ const SENDER_NOT_ALLOWED: ReadonlySet<number> = new Set([400, 401, 412, 413])
30
+ /** Postmark counts the decoded bytes of every attachment together and takes fewer than 10 MiB; the bodies are apart. */
31
+ const POSTMARK_MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024 - 1
32
+ /** The extensions Postmark refuses an attachment for (ErrorCode 411), from its documentation. */
33
+ const FORBIDDEN_EXTENSIONS: readonly string[] =
34
+ 'vbs exe bin bat chm com cpl crt hlp hta inf ins isp jse lnk mdb pcd pif reg scr sct shs vbe vba wsf wsh wsl msc msi msp mst'.split(' ')
35
+
36
+ export interface PostmarkEmailSenderOptions extends HttpEmailSenderOptions {
37
+ /** A server token: it sends through that server's default transactional stream. */
38
+ readonly serverToken: string
39
+ /** The ID of the server's broadcast stream, which a `broadcast` message goes through; `broadcast` by default. */
40
+ readonly broadcastStream?: string
41
+ }
42
+
43
+ export class PostmarkEmailSender extends HttpEmailSender {
44
+ readonly capabilities: EmailSenderCapabilities = {
45
+ idempotent: false,
46
+ confirmation: 'sync',
47
+ maxBatch: 1,
48
+ listUnsubscribe: true,
49
+ maxAttachmentBytes: POSTMARK_MAX_ATTACHMENT_BYTES,
50
+ refusedAttachmentExtensions: FORBIDDEN_EXTENSIONS,
51
+ broadcast: true,
52
+ }
53
+ readonly #serverToken: string
54
+ readonly #broadcastStream: string
55
+
56
+ constructor(options: PostmarkEmailSenderOptions) {
57
+ if (!isCredential(options.serverToken)) {
58
+ throw new EmailDeliveryError('Postmark server token is invalid', { code: 'invalid_configuration' })
59
+ }
60
+ const broadcastStream = options.broadcastStream ?? DEFAULT_BROADCAST_STREAM
61
+ if (!isChannelName(broadcastStream)) {
62
+ throw new EmailDeliveryError('Postmark broadcast stream is invalid', { code: 'invalid_configuration' })
63
+ }
64
+ super({ label: 'Postmark', provider: 'postmark' }, options)
65
+ this.#serverToken = options.serverToken
66
+ this.#broadcastStream = broadcastStream
67
+ }
68
+
69
+ protected request(message: EmailMessage): HttpEmailRequest {
70
+ const attachments = message.attachments ?? []
71
+ return {
72
+ url: POSTMARK_EMAIL_URL,
73
+ headers: { 'X-Postmark-Server-Token': this.#serverToken, Accept: 'application/json' },
74
+ body: {
75
+ From: formatMailbox(this.from.address, message.fromName ?? this.from.name),
76
+ To: message.to,
77
+ Subject: message.subject,
78
+ TextBody: message.text,
79
+ // Postmark pauses a server whose transactional stream carries promotional mail.
80
+ ...(message.broadcast === true ? { MessageStream: this.#broadcastStream } : {}),
81
+ ...(message.html === undefined ? {} : { HtmlBody: message.html }),
82
+ ...(message.replyTo === undefined ? {} : { ReplyTo: message.replyTo }),
83
+ ...(message.unsubscribeUrl === undefined
84
+ ? {}
85
+ : { Headers: Object.entries(oneClickUnsubscribeHeaders(message.unsubscribeUrl)).map(([Name, Value]) => ({ Name, Value })) }),
86
+ ...(attachments.length === 0
87
+ ? {}
88
+ : {
89
+ Attachments: attachments.map((attachment) => ({
90
+ Name: attachment.filename,
91
+ Content: base64Of(attachment.content),
92
+ ContentType: attachment.contentType,
93
+ })),
94
+ }),
95
+ },
96
+ }
97
+ }
98
+
99
+ protected messageId(response: ProviderResponse): string | undefined {
100
+ return postmarkSuccessSchema.safeParse(response.body).data?.MessageID
101
+ }
102
+
103
+ protected override refusal(response: ProviderResponse): EmailDeliveryError | undefined {
104
+ const status = response.status
105
+ const code = postmarkErrorSchema.safeParse(response.body).data?.ErrorCode
106
+ if (status !== 422 || code === undefined) return undefined
107
+ if (code === OUT_OF_CREDITS) {
108
+ return new EmailDeliveryError('Postmark account is out of credits', { code: 'quota_exceeded', httpStatus: status })
109
+ }
110
+ if (SENDER_NOT_ALLOWED.has(code)) {
111
+ return new EmailDeliveryError(`Postmark refused the sender or the account (${code})`, { code: 'provider_unauthorized', httpStatus: status })
112
+ }
113
+ return undefined
114
+ }
115
+ }
116
+
117
+ const postmarkVariablesSchema = z.object({
118
+ FABRIKA_EMAIL_POSTMARK_SERVER_TOKEN: credentialVariable,
119
+ FABRIKA_EMAIL_POSTMARK_BROADCAST_STREAM: optionalVariable(isChannelName),
120
+ })
121
+
122
+ export const postmarkEmailProvider: EmailProvider = {
123
+ variables: [
124
+ { name: 'FABRIKA_EMAIL_POSTMARK_SERVER_TOKEN', secret: true, required: true },
125
+ { name: 'FABRIKA_EMAIL_POSTMARK_BROADCAST_STREAM', secret: false, required: false },
126
+ ],
127
+ create({ from, env, fetch }) {
128
+ const variables = parseProviderVariables(postmarkVariablesSchema, env)
129
+ return new PostmarkEmailSender({
130
+ serverToken: variables.FABRIKA_EMAIL_POSTMARK_SERVER_TOKEN,
131
+ broadcastStream: variables.FABRIKA_EMAIL_POSTMARK_BROADCAST_STREAM,
132
+ from,
133
+ fetch,
134
+ })
135
+ },
136
+ }
package/src/providers.ts CHANGED
@@ -1,9 +1,43 @@
1
- import type { EmailProviderRegistry } from './config.js'
1
+ import { ahaSendEmailProvider } from './ahasend.js'
2
+ import { brevoEmailProvider } from './brevo.js'
3
+ import { cloudflareEmailProvider } from './cloudflare.js'
4
+ import type { EmailProviderRegistry, EmailProviderVariable } from './config.js'
5
+ import { lettermintEmailProvider } from './lettermint.js'
6
+ import { postmarkEmailProvider } from './postmark.js'
2
7
  import { resendEmailProvider } from './resend.js'
3
8
  import { smartEmailingEmailProvider } from './smartemailing.js'
4
9
 
5
- /** The providers `FABRIKA_EMAIL_PROVIDER` can name in a stock installation. Memory and Directory are composition inputs. */
10
+ /**
11
+ * The providers `FABRIKA_EMAIL_PROVIDER` can name in a stock installation, sorted by name: the order every help text
12
+ * and refusal lists them in. Memory and Directory are composition inputs.
13
+ */
6
14
  export const builtinEmailProviders = {
15
+ ahasend: ahaSendEmailProvider,
16
+ brevo: brevoEmailProvider,
17
+ cloudflare: cloudflareEmailProvider,
18
+ lettermint: lettermintEmailProvider,
19
+ postmark: postmarkEmailProvider,
7
20
  resend: resendEmailProvider,
8
21
  smartemailing: smartEmailingEmailProvider,
9
22
  } satisfies EmailProviderRegistry
23
+
24
+ /** Every built-in provider's own variables, in registry order: what the installers write and the workflow passes on. */
25
+ export const builtinEmailProviderVariables: readonly EmailProviderVariable[] = Object.values(builtinEmailProviders).flatMap((provider) =>
26
+ provider.variables
27
+ )
28
+
29
+ /**
30
+ * The first framework release whose registry holds each built-in provider. An application on an older release builds
31
+ * its sender from its own registry, so it cannot be handed one it lacks; Control refuses that deploy. `null`: every
32
+ * release that sends through the installation (`mailer: 'installation'`, from 0.5.0) holds it. A new provider names
33
+ * the release after the newest one published without it.
34
+ */
35
+ export const builtinEmailProviderSince = {
36
+ ahasend: '0.8.2',
37
+ brevo: '0.9.0-dev.17',
38
+ cloudflare: '0.9.0',
39
+ lettermint: '0.8.2',
40
+ postmark: '0.8.2',
41
+ resend: null,
42
+ smartemailing: null,
43
+ } as const satisfies Record<keyof typeof builtinEmailProviders, string | null>
package/src/resend.ts CHANGED
@@ -1,80 +1,65 @@
1
1
  import { z } from 'zod'
2
- import { type EmailProvider, type EmailSenderIdentity, parseProviderVariables } from './config.js'
2
+ import { type EmailProvider, parseProviderVariables } from './config.js'
3
3
  import { base64Of } from './content.js'
4
+ import { EmailDeliveryError, type EmailMessage, type EmailSenderCapabilities, oneClickUnsubscribeHeaders } from './email.js'
4
5
  import {
5
- EmailDeliveryError,
6
- type EmailDeliveryResult,
7
- type EmailFetch,
8
- type EmailMessage,
9
- type EmailSender,
10
- type EmailSenderCapabilities,
11
- oneClickUnsubscribeHeaders,
12
- } from './email.js'
13
- import { parseTimeout, postToProvider, type ProviderResponse } from './http.js'
14
- import { isValidEmailSenderIdentity, isVisibleAscii, validateEmailAttachments, validateEmailMessage } from './validation.js'
6
+ credentialVariable,
7
+ formatMailbox,
8
+ type HttpEmailRequest,
9
+ HttpEmailSender,
10
+ type HttpEmailSenderOptions,
11
+ isCredential,
12
+ } from './http-sender.js'
13
+ import type { ProviderResponse } from './http.js'
15
14
 
16
15
  const RESEND_EMAILS_URL = 'https://api.resend.com/emails'
17
16
  const LABEL = 'Resend'
18
- const resendSuccessSchema = z.object({ id: z.string().min(1) })
17
+ const BROADCAST_TAG = { name: 'category', value: 'broadcast' }
18
+ const resendSuccessSchema = z.object({ id: z.string() })
19
19
  const resendErrorSchema = z.object({ name: z.string() })
20
20
  const QUOTA_ERRORS: ReadonlySet<string> = new Set(['daily_quota_exceeded', 'monthly_quota_exceeded'])
21
- /** RFC 5322 specials a display name may still hold after validation; any of them makes the name a quoted string. */
22
- const DISPLAY_NAME_SPECIALS = /[()[\]:;@,.]/
23
21
  /** Resend refuses a message over 40 MB once its attachments are base64; 25 MiB of bytes leaves room for the rest. */
24
22
  const RESEND_MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024
25
23
 
26
- export interface ResendEmailSenderOptions {
24
+ export interface ResendEmailSenderOptions extends HttpEmailSenderOptions {
27
25
  readonly apiKey: string
28
- readonly from: EmailSenderIdentity
29
- readonly fetch?: EmailFetch
30
- readonly timeoutMs?: number
31
26
  }
32
27
 
33
- export class ResendEmailSender implements EmailSender {
28
+ export class ResendEmailSender extends HttpEmailSender {
34
29
  readonly capabilities: EmailSenderCapabilities = {
35
30
  idempotent: true,
36
31
  confirmation: 'sync',
37
32
  maxBatch: 1,
38
33
  listUnsubscribe: true,
39
34
  maxAttachmentBytes: RESEND_MAX_ATTACHMENT_BYTES,
35
+ // Resend takes one-to-one marketing mail through this API, with consent and an unsubscribe; it has no channel apart.
36
+ broadcast: true,
40
37
  }
41
38
  readonly #apiKey: string
42
- readonly #from: EmailSenderIdentity
43
- readonly #fetch: EmailFetch
44
- readonly #timeoutMs: number
45
39
 
46
40
  constructor(options: ResendEmailSenderOptions) {
47
- if (!validApiKey(options.apiKey)) {
41
+ if (!isCredential(options.apiKey)) {
48
42
  throw new EmailDeliveryError('Resend API key is invalid', { code: 'invalid_configuration' })
49
43
  }
50
- if (!isValidEmailSenderIdentity(options.from)) {
51
- throw new EmailDeliveryError('Resend sender is invalid', { code: 'invalid_configuration' })
52
- }
53
-
44
+ super({ label: LABEL, provider: 'resend' }, options)
54
45
  this.#apiKey = options.apiKey
55
- this.#from = options.from
56
- this.#fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init))
57
- this.#timeoutMs = parseTimeout(LABEL, options.timeoutMs)
58
46
  }
59
47
 
60
- async send(message: EmailMessage, signal: AbortSignal): Promise<EmailDeliveryResult> {
61
- validateEmailMessage(message)
62
- validateEmailAttachments(message, this.capabilities, LABEL)
48
+ protected request(message: EmailMessage): HttpEmailRequest {
63
49
  const attachments = message.attachments ?? []
64
-
65
- const response = await postToProvider({
66
- label: LABEL,
67
- fetch: this.#fetch,
50
+ return {
68
51
  url: RESEND_EMAILS_URL,
69
52
  headers: { Authorization: `Bearer ${this.#apiKey}`, 'Idempotency-Key': message.idempotencyKey },
70
53
  body: {
71
- from: formatMailbox(this.#from.address, message.fromName ?? this.#from.name),
54
+ from: formatMailbox(this.from.address, message.fromName ?? this.from.name),
72
55
  to: message.to,
73
56
  subject: message.subject,
74
57
  text: message.text,
75
58
  ...(message.html === undefined ? {} : { html: message.html }),
76
59
  ...(message.replyTo === undefined ? {} : { reply_to: message.replyTo }),
77
60
  ...(message.unsubscribeUrl === undefined ? {} : { headers: oneClickUnsubscribeHeaders(message.unsubscribeUrl) }),
61
+ // Tagged, so the account's logs and webhooks tell broadcast mail from transactional.
62
+ ...(message.broadcast === true ? { tags: [BROADCAST_TAG] } : {}),
78
63
  ...(attachments.length === 0
79
64
  ? {}
80
65
  : {
@@ -85,22 +70,37 @@ export class ResendEmailSender implements EmailSender {
85
70
  })),
86
71
  }),
87
72
  },
88
- signal,
89
- timeoutMs: this.#timeoutMs,
90
- })
73
+ }
74
+ }
91
75
 
92
- if (!response.ok) throw responseError(response)
76
+ protected messageId(response: ProviderResponse): string | undefined {
77
+ return resendSuccessSchema.safeParse(response.body).data?.id
78
+ }
93
79
 
94
- const parsed = resendSuccessSchema.safeParse(response.body)
95
- if (!parsed.success) {
96
- throw new EmailDeliveryError('Resend returned an invalid success response', { code: 'malformed_response', httpStatus: response.status })
80
+ protected override refusal(response: ProviderResponse): EmailDeliveryError | undefined {
81
+ const status = response.status
82
+ const name = resendErrorSchema.safeParse(response.body).data?.name
83
+ if (status === 401 || status === 403) {
84
+ // A 403 is also an unverified sender domain.
85
+ return new EmailDeliveryError(`Resend refused the credentials or the sender (${status})`, { code: 'provider_unauthorized', httpStatus: status })
97
86
  }
98
-
99
- return { status: 'accepted', provider: 'resend', messageId: parsed.data.id }
87
+ if (status === 409 && name === 'concurrent_idempotent_requests') {
88
+ return new EmailDeliveryError('A matching Resend request is still in progress', { code: 'request_in_progress', httpStatus: status })
89
+ }
90
+ if (status === 409 && name === 'invalid_idempotent_request') {
91
+ return new EmailDeliveryError('Resend already accepted a different message under this idempotency key', {
92
+ code: 'idempotency_conflict',
93
+ httpStatus: status,
94
+ })
95
+ }
96
+ if (status === 429 && name !== undefined && QUOTA_ERRORS.has(name)) {
97
+ return new EmailDeliveryError('Resend sending quota exceeded', { code: 'quota_exceeded', httpStatus: status })
98
+ }
99
+ return undefined
100
100
  }
101
101
  }
102
102
 
103
- const resendVariablesSchema = z.object({ FABRIKA_EMAIL_RESEND_API_KEY: z.string().refine(validApiKey) })
103
+ const resendVariablesSchema = z.object({ FABRIKA_EMAIL_RESEND_API_KEY: credentialVariable })
104
104
 
105
105
  export const resendEmailProvider: EmailProvider = {
106
106
  variables: [{ name: 'FABRIKA_EMAIL_RESEND_API_KEY', secret: true, required: true }],
@@ -109,40 +109,3 @@ export const resendEmailProvider: EmailProvider = {
109
109
  return new ResendEmailSender({ apiKey: variables.FABRIKA_EMAIL_RESEND_API_KEY, from, fetch })
110
110
  },
111
111
  }
112
-
113
- function responseError(response: ProviderResponse): EmailDeliveryError {
114
- const status = response.status
115
- const parsed = resendErrorSchema.safeParse(response.body)
116
- const name = parsed.success ? parsed.data.name : undefined
117
- if (status === 401 || status === 403) {
118
- return new EmailDeliveryError(`Resend refused the credentials or the sender (${status})`, { code: 'provider_unauthorized', httpStatus: status })
119
- }
120
- if (status === 409 && name === 'concurrent_idempotent_requests') {
121
- return new EmailDeliveryError('A matching Resend request is still in progress', { code: 'request_in_progress', httpStatus: status })
122
- }
123
- if (status === 409 && name === 'invalid_idempotent_request') {
124
- return new EmailDeliveryError('Resend already accepted a different message under this idempotency key', {
125
- code: 'idempotency_conflict',
126
- httpStatus: status,
127
- })
128
- }
129
- if (status === 429 && name !== undefined && QUOTA_ERRORS.has(name)) {
130
- return new EmailDeliveryError('Resend sending quota exceeded', { code: 'quota_exceeded', httpStatus: status })
131
- }
132
- if (status === 429) {
133
- return new EmailDeliveryError('Resend rate limit exceeded', { code: 'rate_limited', httpStatus: status })
134
- }
135
- if (status >= 500) {
136
- return new EmailDeliveryError('Resend is unavailable', { code: 'provider_unavailable', httpStatus: status })
137
- }
138
- return new EmailDeliveryError(`Resend rejected the request (${status})`, { code: 'provider_rejected', httpStatus: status })
139
- }
140
-
141
- function formatMailbox(address: string, name: string | undefined): string {
142
- if (name === undefined) return address
143
- return DISPLAY_NAME_SPECIALS.test(name) ? `"${name}" <${address}>` : `${name} <${address}>`
144
- }
145
-
146
- function validApiKey(value: string): boolean {
147
- return value.length > 0 && isVisibleAscii(value)
148
- }
@@ -2,83 +2,66 @@
2
2
  // verified only against a stubbed fetch. It has no idempotency key, and a 201 only queues the request.
3
3
 
4
4
  import { z } from 'zod'
5
- import { type EmailProvider, type EmailSenderIdentity, parseProviderVariables } from './config.js'
5
+ import { type EmailProvider, parseProviderVariables } from './config.js'
6
+ import { EmailDeliveryError, type EmailMessage, type EmailSenderCapabilities } from './email.js'
6
7
  import {
7
- EmailDeliveryError,
8
- type EmailDeliveryResult,
9
- type EmailFetch,
10
- type EmailMessage,
11
- type EmailSender,
12
- type EmailSenderCapabilities,
13
- } from './email.js'
14
- import { parseTimeout, postToProvider } from './http.js'
15
- import { isValidEmailSenderIdentity, isVisibleAscii, validateEmailAttachments, validateEmailMessage } from './validation.js'
8
+ credentialVariable,
9
+ type HttpEmailRequest,
10
+ HttpEmailSender,
11
+ type HttpEmailSenderOptions,
12
+ isCredential,
13
+ optionalVariable,
14
+ } from './http-sender.js'
15
+ import type { ProviderResponse } from './http.js'
16
16
 
17
17
  const SMARTEMAILING_SEND_URL = 'https://app.smartemailing.cz/api/v3/send/transactional-emails-bulk'
18
- const LABEL = 'SmartEmailing'
19
18
  const DEFAULT_TAG = 'fabrika'
20
19
  const TAG_PATTERN = /^[A-Za-z0-9_-]{1,64}$/
21
- const smartEmailingSuccessSchema = z.object({ data: z.tuple([z.object({ id: z.string().min(1) })]) })
20
+ const smartEmailingSuccessSchema = z.object({ data: z.tuple([z.object({ id: z.string() })]) })
22
21
 
23
- export interface SmartEmailingEmailSenderOptions {
22
+ export interface SmartEmailingEmailSenderOptions extends HttpEmailSenderOptions {
24
23
  /** The account's user name or e-mail: the first half of the Basic credential. */
25
24
  readonly username: string
26
25
  readonly apiKey: string
27
- readonly from: EmailSenderIdentity
28
26
  /** Groups the messages in SmartEmailing's statistics. */
29
27
  readonly tag?: string
30
- readonly fetch?: EmailFetch
31
- readonly timeoutMs?: number
32
28
  }
33
29
 
34
- export class SmartEmailingEmailSender implements EmailSender {
35
- /** The API takes up to five tasks a request, but `send` carries one. */
30
+ /** Its error body's `message` is free text that may quote the request, so a refusal is classified by status alone. */
31
+ export class SmartEmailingEmailSender extends HttpEmailSender {
32
+ /**
33
+ * The API takes up to five tasks a request, but `send` carries one. Its API documents no message headers, so a
34
+ * one-click unsubscribe is refused rather than sent without one.
35
+ */
36
36
  readonly capabilities: EmailSenderCapabilities = { idempotent: false, confirmation: 'queued', maxBatch: 1 }
37
37
  readonly #authorization: string
38
- readonly #from: EmailSenderIdentity
39
38
  readonly #tag: string
40
- readonly #fetch: EmailFetch
41
- readonly #timeoutMs: number
42
39
 
43
40
  constructor(options: SmartEmailingEmailSenderOptions) {
44
41
  if (!validUsername(options.username)) {
45
42
  throw new EmailDeliveryError('SmartEmailing username is invalid', { code: 'invalid_configuration' })
46
43
  }
47
- if (!validApiKey(options.apiKey)) {
44
+ if (!isCredential(options.apiKey)) {
48
45
  throw new EmailDeliveryError('SmartEmailing API key is invalid', { code: 'invalid_configuration' })
49
46
  }
50
- if (!isValidEmailSenderIdentity(options.from)) {
51
- throw new EmailDeliveryError('SmartEmailing sender is invalid', { code: 'invalid_configuration' })
52
- }
47
+ super({ label: 'SmartEmailing', provider: 'smartemailing' }, options)
53
48
  const tag = options.tag ?? DEFAULT_TAG
54
49
  if (!TAG_PATTERN.test(tag)) {
55
50
  throw new EmailDeliveryError('SmartEmailing tag is invalid', { code: 'invalid_configuration' })
56
51
  }
57
52
 
58
53
  this.#authorization = `Basic ${btoa(`${options.username}:${options.apiKey}`)}`
59
- this.#from = options.from
60
54
  this.#tag = tag
61
- this.#fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init))
62
- this.#timeoutMs = parseTimeout(LABEL, options.timeoutMs)
63
55
  }
64
56
 
65
- async send(message: EmailMessage, signal: AbortSignal): Promise<EmailDeliveryResult> {
66
- validateEmailMessage(message)
67
- // Its API documents no message headers, so a one-click unsubscribe is refused rather than sent without one.
68
- if (message.unsubscribeUrl !== undefined) {
69
- throw new EmailDeliveryError('SmartEmailing cannot write the List-Unsubscribe headers', { code: 'invalid_message' })
70
- }
71
- validateEmailAttachments(message, this.capabilities, LABEL)
72
-
73
- const senderName = message.fromName ?? this.#from.name
74
- const response = await postToProvider({
75
- label: LABEL,
76
- fetch: this.#fetch,
57
+ protected request(message: EmailMessage): HttpEmailRequest {
58
+ const senderName = message.fromName ?? this.from.name
59
+ return {
77
60
  url: SMARTEMAILING_SEND_URL,
78
61
  headers: { Authorization: this.#authorization },
79
62
  body: {
80
63
  sender_credentials: {
81
- from: this.#from.address,
64
+ from: this.from.address,
82
65
  ...(senderName === undefined ? {} : { sender_name: senderName }),
83
66
  ...(message.replyTo === undefined ? {} : { reply_to: message.replyTo }),
84
67
  },
@@ -91,28 +74,18 @@ export class SmartEmailingEmailSender implements EmailSender {
91
74
  },
92
75
  tasks: [{ recipient: { emailaddress: message.to } }],
93
76
  },
94
- signal,
95
- timeoutMs: this.#timeoutMs,
96
- })
97
-
98
- // The error body's `message` is free text that may quote the request, so only the status is classified.
99
- if (!response.ok) throw responseError(response.status)
100
-
101
- const parsed = smartEmailingSuccessSchema.safeParse(response.body)
102
- if (!parsed.success) {
103
- throw new EmailDeliveryError('SmartEmailing returned an invalid success response', { code: 'malformed_response', httpStatus: response.status })
104
77
  }
78
+ }
105
79
 
106
- return { status: 'accepted', provider: 'smartemailing', messageId: parsed.data.data[0].id }
80
+ protected messageId(response: ProviderResponse): string | undefined {
81
+ return smartEmailingSuccessSchema.safeParse(response.body).data?.data[0].id
107
82
  }
108
83
  }
109
84
 
110
85
  const smartEmailingVariablesSchema = z.object({
111
86
  FABRIKA_EMAIL_SMARTEMAILING_USERNAME: z.string().refine(validUsername),
112
- FABRIKA_EMAIL_SMARTEMAILING_API_KEY: z.string().refine(validApiKey),
113
- FABRIKA_EMAIL_SMARTEMAILING_TAG: z.string().optional().transform((value) => (value === '' ? undefined : value)).refine((value) =>
114
- value === undefined || TAG_PATTERN.test(value)
115
- ),
87
+ FABRIKA_EMAIL_SMARTEMAILING_API_KEY: credentialVariable,
88
+ FABRIKA_EMAIL_SMARTEMAILING_TAG: optionalVariable((value) => TAG_PATTERN.test(value)),
116
89
  })
117
90
 
118
91
  export const smartEmailingEmailProvider: EmailProvider = {
@@ -133,23 +106,6 @@ export const smartEmailingEmailProvider: EmailProvider = {
133
106
  },
134
107
  }
135
108
 
136
- function responseError(status: number): EmailDeliveryError {
137
- if (status === 401 || status === 403) {
138
- return new EmailDeliveryError(`SmartEmailing refused the credentials (${status})`, { code: 'provider_unauthorized', httpStatus: status })
139
- }
140
- if (status === 429) {
141
- return new EmailDeliveryError('SmartEmailing rate limit exceeded', { code: 'rate_limited', httpStatus: status })
142
- }
143
- if (status >= 500) {
144
- return new EmailDeliveryError('SmartEmailing is unavailable', { code: 'provider_unavailable', httpStatus: status })
145
- }
146
- return new EmailDeliveryError(`SmartEmailing rejected the request (${status})`, { code: 'provider_rejected', httpStatus: status })
147
- }
148
-
149
109
  function validUsername(value: string): boolean {
150
- return validApiKey(value) && !value.includes(':')
151
- }
152
-
153
- function validApiKey(value: string): boolean {
154
- return value.length > 0 && isVisibleAscii(value)
110
+ return isCredential(value) && !value.includes(':')
155
111
  }
package/src/validation.ts CHANGED
@@ -64,6 +64,7 @@ export function validateEmailMessage(message: EmailMessage): void {
64
64
  if (message.replyTo !== undefined && !isValidEmailAddress(message.replyTo)) throw invalidMessage('Email reply-to address is invalid')
65
65
  if (message.fromName !== undefined && !isValidEmailDisplayName(message.fromName)) throw invalidMessage('Email sender name is invalid')
66
66
  if (message.unsubscribeUrl !== undefined && !isUnsubscribeUrl(message.unsubscribeUrl)) throw invalidMessage('Email unsubscribe URL is invalid')
67
+ if (message.broadcast === true && message.unsubscribeUrl === undefined) throw invalidMessage('A broadcast email needs an unsubscribe URL')
67
68
  const attachments = message.attachments ?? []
68
69
  if (attachments.length > MAX_EMAIL_ATTACHMENTS) throw invalidMessage(`Email has more than ${MAX_EMAIL_ATTACHMENTS} attachments`)
69
70
  for (const attachment of attachments) {
@@ -73,15 +74,45 @@ export function validateEmailMessage(message: EmailMessage): void {
73
74
  }
74
75
 
75
76
  /**
76
- * Refuses a message whose attachments `capabilities` does not carry: any attachment where the transport sends none, or
77
- * more bytes together than its `maxAttachmentBytes`. `label` names the transport in the message.
77
+ * Refuses a message whose attachments `capabilities` does not carry: any attachment where the transport sends none,
78
+ * more bytes together than its `maxAttachmentBytes`, or a file whose extension it refuses or does not list in
79
+ * `attachmentExtensions`. `label` names the transport in the message.
78
80
  */
79
81
  export function validateEmailAttachments(message: EmailMessage, capabilities: EmailSenderCapabilities, label: string): void {
80
- if ((message.attachments ?? []).length === 0) return
82
+ const attachments = message.attachments ?? []
83
+ if (attachments.length === 0) return
81
84
  const limit = capabilities.maxAttachmentBytes
82
85
  if (limit === undefined) throw invalidMessage(`${label} sends no attachments`)
83
86
  const bytes = attachmentBytes(message)
84
87
  if (bytes > limit) throw invalidMessage(`Email attachments have ${bytes} bytes, more than the ${limit} ${label} sends`)
88
+ const refused = capabilities.refusedAttachmentExtensions ?? []
89
+ const allowed = capabilities.attachmentExtensions
90
+ const refusedType = (filename: string): boolean => {
91
+ const extension = extensionOf(filename)
92
+ return refused.includes(extension) || (allowed !== undefined && !allowed.includes(extension))
93
+ }
94
+ if (attachments.some((attachment) => refusedType(attachment.filename))) throw invalidMessage(`${label} sends no attachment of this file type`)
95
+ }
96
+
97
+ /** Refuses a `broadcast` message where the transport sends none. */
98
+ export function validateEmailBroadcast(message: EmailMessage, capabilities: EmailSenderCapabilities, label: string): void {
99
+ if (message.broadcast === true && capabilities.broadcast !== true) throw invalidMessage(`${label} sends no broadcast email`)
100
+ }
101
+
102
+ /** Refuses a text or HTML body shorter than the transport's `minBodyLength`, counted in characters once trimmed. */
103
+ export function validateEmailBodies(message: EmailMessage, capabilities: EmailSenderCapabilities, label: string): void {
104
+ const min = capabilities.minBodyLength
105
+ if (min === undefined) return
106
+ const short = (body: string): boolean => [...body.trim()].length < min
107
+ if (short(message.text) || (message.html !== undefined && short(message.html))) {
108
+ throw invalidMessage(`${label} sends no body shorter than ${min} characters`)
109
+ }
110
+ }
111
+
112
+ /** The extension after the last dot, lowercase; empty without one. */
113
+ export function extensionOf(filename: string): string {
114
+ const dot = filename.lastIndexOf('.')
115
+ return dot < 0 ? '' : filename.slice(dot + 1).toLowerCase()
85
116
  }
86
117
 
87
118
  /** The most files one message carries. */
@@ -0,0 +1,26 @@
1
+ import { type EmailProvider } from './config.js';
2
+ import { EmailDeliveryError, type EmailMessage, type EmailSenderCapabilities } from './email.js';
3
+ import { type HttpEmailRequest, HttpEmailSender, type HttpEmailSenderOptions } from './http-sender.js';
4
+ import type { ProviderResponse } from './http.js';
5
+ export interface AhaSendEmailSenderOptions extends HttpEmailSenderOptions {
6
+ /** An API key v2, scoped to `messages:send:{domain}` at least. */
7
+ readonly apiKey: string;
8
+ /** The account the key belongs to: the path of every request. */
9
+ readonly accountId: string;
10
+ /**
11
+ * The address a `broadcast` message is sent from, on a domain the account has configured as a Marketing domain:
12
+ * AhaSend's terms allow marketing mail through the API from such a domain only. Without it, a broadcast is refused.
13
+ */
14
+ readonly broadcastFrom?: string;
15
+ }
16
+ /** A refusal's body is one free-text `message`, so only the status is read. */
17
+ export declare class AhaSendEmailSender extends HttpEmailSender {
18
+ #private;
19
+ /** `broadcast` only with `broadcastFrom`. */
20
+ readonly capabilities: EmailSenderCapabilities;
21
+ constructor(options: AhaSendEmailSenderOptions);
22
+ protected request(message: EmailMessage): Promise<HttpEmailRequest>;
23
+ protected messageId(response: ProviderResponse): string | undefined;
24
+ protected refusal(response: ProviderResponse): EmailDeliveryError | undefined;
25
+ }
26
+ export declare const ahaSendEmailProvider: EmailProvider;
@@ -0,0 +1,19 @@
1
+ import { type EmailProvider } from './config.js';
2
+ import { EmailDeliveryError, type EmailMessage, type EmailSenderCapabilities } from './email.js';
3
+ import { type HttpEmailRequest, HttpEmailSender, type HttpEmailSenderOptions } from './http-sender.js';
4
+ import type { ProviderResponse } from './http.js';
5
+ export interface BrevoEmailSenderOptions extends HttpEmailSenderOptions {
6
+ /** An API key (v3) of the account. */
7
+ readonly apiKey: string;
8
+ }
9
+ export declare class BrevoEmailSender extends HttpEmailSender {
10
+ #private;
11
+ readonly capabilities: EmailSenderCapabilities;
12
+ constructor(options: BrevoEmailSenderOptions);
13
+ protected request(message: EmailMessage): Promise<HttpEmailRequest>;
14
+ protected messageId(response: ProviderResponse): string | undefined;
15
+ protected refusal(response: ProviderResponse): EmailDeliveryError | undefined;
16
+ }
17
+ /** A plain text as the HTML body Brevo requires: every character escaped, each line break a `<br>`. */
18
+ export declare function brevoHtmlOfText(text: string): string;
19
+ export declare const brevoEmailProvider: EmailProvider;