@prunellejs/mail 0.0.0-stage → 0.5.2

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/llms.txt ADDED
@@ -0,0 +1,76 @@
1
+ # @prunellejs/mail Reference
2
+
3
+ > Zero-dependency email delivery with JSX/TSX templates (auto HTML + plain text), email-safe components, native SMTP/SMTPS/STARTTLS, Resend, Postmark, `MAIL_URL`, `@prunellejs/jobs` retry integration, and a dev-only outbox + template preview.
4
+
5
+ ## Imports
6
+
7
+ - `@prunellejs/mail`:
8
+ - Core: `createMailer`, `renderMail`, `htmlToText`, `MailNotConfiguredError`
9
+ - Transports: `smtp`, `resend`, `postmark`, `transportFromUrl`, `buildMimeMessage`, `dotStuffSmtpData`
10
+ - Components: `Email`, `Section`, `Heading`, `Text`, `Button`, `Divider`, `Footer`, `Link`
11
+ - Types: `Mailer`, `MailerOptions`, `MailPreviewOptions`, `MailPreviewEntry`, `MailPreviewRegisterOptions`, `MailRetryOptions`, `MailMessage`, `MailBody`, `RenderedMail`, `RenderedMailPreview`, `SentMail`, `MailAddress`, `MailTransport`, `SmtpOptions`, `ResendOptions`, `PostmarkOptions`, `EmailProps`, `SectionProps`, `HeadingProps`, `TextProps`, `ButtonProps`, `DividerProps`, `FooterProps`, `LinkProps`, `TextAlign`.
12
+
13
+ ## Setup (`createMailer(options?)`)
14
+
15
+ `createMailer()` returns a single object that is both the `PrunellePlugin` (register in `prunelle.config.ts`) and the handle routes/actions call `mail.send()` on:
16
+
17
+ - `from`: default sender (`string | { name, address }`, falls back to `process.env.MAIL_FROM`, then `'noreply@localhost'` outside production: a production start refuses without one).
18
+ - `to`: default recipient(s) (falls back to `process.env.MAIL_TO`); `send()` with no recipient throws, in every mode.
19
+ - `transport`: `MailTransport` (`{ send(mail: SentMail): Promise<void> }`). Resolution order:
20
+ 1. Explicit `options.transport`
21
+ 2. `process.env.MAIL_URL` (`smtp://`, `smtps://`, `resend://`, `postmark://`)
22
+ 3. `process.env.RESEND_API_KEY` (`resend()`)
23
+ - A production start refuses with no transport (`transport`, `MAIL_URL`, or `RESEND_API_KEY`) unless `optional: true`.
24
+ - `optional`: when `false`/omitted, calling `send()` in `NODE_ENV=production` without a transport throws `MailNotConfiguredError`.
25
+ - `previewRoute`: dev outbox URL (default `'/_pru/mail'`). `preview: false` disables the preview.
26
+ - `previews`: array of `{ name, subject?, props?, render: () => MailBody }` templates rendered live in the dev outbox. You can also register previews imperatively via `mail.preview(name, Component, sampleProps, { subject? })` or `mail.preview(name, () => <Welcome ... />, { subject? })`.
27
+ - `retries`: `{ queue?: string, attempts?: number, backoff?: 'exponential' | 'fixed' | number }` used when `@prunellejs/jobs` (`JOBS_SERVICE`) is registered. On transport failure, delivery is enqueued on `mail.deliver` with `{ key: record.id }` for durable deduplicated retries. Set `asyncQueue: true` to enqueue upfront without attempting inline send first.
28
+
29
+ ## JSX/TSX Templates & Components
30
+
31
+ - `await mail.send({ to, subject, body: <Welcome name="Ada" /> })` renders both `html` and a clean `text` alternative automatically (explicit `text` or `html` overrides the rendered part).
32
+ - `await renderMail(node)` returns `{ html, text }` from any JSX/TSX element, compiled `Html`, async component result, or render factory.
33
+ - Built-in email-safe components work identically in compiled Prunelle routes and direct Bun execution:
34
+ - `Email({ lang?, title?, preview?, backgroundColor?, containerBackgroundColor?, width?, children })` — full HTML email document with Outlook MSO namespaces & DPI XML, dark-mode `<meta>` + `@media (prefers-color-scheme: dark)` CSS, hidden preheader, and centered 600px table layout.
35
+ - `Section`, `Heading` (`h1`–`h3`), `Text` (`muted?`), `Button` (Outlook VML roundrect + dark-mode CTA), `Divider`, `Footer`, `Link`.
36
+
37
+ ## Transports & `MAIL_URL`
38
+
39
+ - `transportFromUrl(url)` supports:
40
+ - `smtp://[user:pass@]host[:port]` (default port 587; upgrades via `STARTTLS` when advertised, `?tls=true`/`?starttls=true` to require, `?tls=false` to disable, `?allowInsecureAuth=true` to allow plaintext `AUTH` on non-loopback hosts)
41
+ - `smtps://[user:pass@]host[:port]` (default port 465; implicit TLS)
42
+ - `resend://<apiKey>` or `resend://:<apiKey>@api.resend.com`
43
+ - `postmark://<serverToken>` or `postmark://:<serverToken>@api.postmarkapp.com`
44
+ - `smtp(options)` uses `Bun.connect` TCP/TLS sockets directly (zero npm dependencies): RFC 5321 multi-line parsing, `EHLO`, `STARTTLS` (with RFC 3207 response-injection protection and plaintext credential downgrade refusal on non-loopback hosts unless `allowInsecureAuth: true` or `requireTls: false`), `AUTH PLAIN` / `AUTH LOGIN`, `MAIL FROM`, `RCPT TO`, `DATA` with CRLF normalization + dot-stuffing, MIME `multipart/alternative`, and `QUIT`.
45
+ - `resend({ apiKey?, endpoint?, timeoutMs?, retries? })` and `postmark({ serverToken?, endpoint?, timeoutMs?, retries?, messageStream? })` use native `fetch()` with timeout and retries on `429`/`5xx` and transient network/timeout errors.
46
+
47
+ ## Mounted Routes (`prunelle dev` or `NODE_ENV=test` only — never in production or built servers outside test)
48
+
49
+ - `GET /_pru/mail` — HTML outbox viewer showing registered template previews (HTML iframe + plain text) and sent messages (sandboxed `<iframe>`s + plain text).
50
+ - `GET /_pru/mail.json` — `{ count, messages, previews }` JSON dump (up to 100 sent messages in memory; production keeps no copy).
51
+
52
+ ## Snippet
53
+
54
+ ```tsx
55
+ // src/mail.tsx (and register `plugins: [mail]` in prunelle.config.ts)
56
+ import { Button, createMailer, Email, Footer, Heading, Text } from '@prunellejs/mail'
57
+
58
+ export function Welcome({ name }: { name: string }) {
59
+ return (
60
+ <Email preview="Welcome aboard">
61
+ <Heading>Welcome, {name}!</Heading>
62
+ <Text>Your account is ready.</Text>
63
+ <Button href="https://example.com/start">Get started</Button>
64
+ <Footer>Acme Inc.</Footer>
65
+ </Email>
66
+ )
67
+ }
68
+
69
+ export const mail = createMailer({
70
+ from: 'App <noreply@example.com>',
71
+ previews: [{ name: 'Welcome', subject: 'Welcome!', render: () => <Welcome name="Ada" /> }],
72
+ })
73
+
74
+ // In an action or route (uses MAIL_URL or RESEND_API_KEY automatically):
75
+ await mail.send({ to: 'ada@example.com', subject: 'Welcome!', body: <Welcome name="Ada" /> })
76
+ ```
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@prunellejs/mail",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.2",
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
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "files": [
9
+ "src",
10
+ "llms.txt"
11
+ ],
12
+ "exports": {
13
+ ".": "./src/index.ts"
14
+ },
15
+ "engines": {
16
+ "bun": ">=1.4.0"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/Kayno0o/prunelle",
21
+ "directory": "packages/plugin-mail"
22
+ },
23
+ "peerDependencies": {
24
+ "prunelle": "^0.5.2"
25
+ }
26
+ }
@@ -0,0 +1,255 @@
1
+ // Email-safe JSX/TSX components with table layouts, inline styles, Outlook MSO VML fallbacks, and dark-mode CSS.
2
+ // Built with `raw`/`esc`/`escAttr` from `prunelle/server` so they render identically both in compiled Prunelle routes and direct Bun execution.
3
+
4
+ import type { Html, PrunelleChild } from 'prunelle/jsx-runtime'
5
+ import { esc, escAttr, raw } from 'prunelle/server'
6
+
7
+ export type TextAlign = 'left' | 'center' | 'right'
8
+
9
+ export interface EmailProps {
10
+ /** Document language attribute (default `'en'`). */
11
+ lang?: string | undefined
12
+ /** Optional `<title>` inside `<head>`. */
13
+ title?: string | undefined
14
+ /** Hidden inbox preheader text (excluded from auto-derived plain text). */
15
+ preview?: string | undefined
16
+ /** Outer email canvas background color (default `'#f4f4f5'`). */
17
+ backgroundColor?: string | undefined
18
+ /** Inner card background color (default `'#ffffff'`). */
19
+ containerBackgroundColor?: string | undefined
20
+ /** Max container width in pixels (default `600`). */
21
+ width?: number | undefined
22
+ children?: PrunelleChild | undefined
23
+ }
24
+
25
+ export interface SectionProps {
26
+ padding?: string | undefined
27
+ backgroundColor?: string | undefined
28
+ align?: TextAlign | undefined
29
+ style?: string | undefined
30
+ children?: PrunelleChild | undefined
31
+ }
32
+
33
+ export interface HeadingProps {
34
+ as?: 'h1' | 'h2' | 'h3' | undefined
35
+ align?: TextAlign | undefined
36
+ style?: string | undefined
37
+ children?: PrunelleChild | undefined
38
+ }
39
+
40
+ export interface TextProps {
41
+ align?: TextAlign | undefined
42
+ muted?: boolean | undefined
43
+ style?: string | undefined
44
+ children?: PrunelleChild | undefined
45
+ }
46
+
47
+ export interface ButtonProps {
48
+ href: string
49
+ backgroundColor?: string | undefined
50
+ color?: string | undefined
51
+ borderRadius?: number | undefined
52
+ align?: TextAlign | undefined
53
+ style?: string | undefined
54
+ children?: PrunelleChild | undefined
55
+ }
56
+
57
+ export interface DividerProps {
58
+ color?: string | undefined
59
+ margin?: string | undefined
60
+ style?: string | undefined
61
+ }
62
+
63
+ export interface FooterProps {
64
+ align?: TextAlign | undefined
65
+ style?: string | undefined
66
+ children?: PrunelleChild | undefined
67
+ }
68
+
69
+ export interface LinkProps {
70
+ href: string
71
+ color?: string | undefined
72
+ style?: string | undefined
73
+ children?: PrunelleChild | undefined
74
+ }
75
+
76
+ const SAFE_URL_SCHEME_RE = /^(?:https?:|mailto:|tel:|\/|#)/i
77
+ const HAS_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i
78
+
79
+ const EMAIL_HEAD_CSS = [
80
+ ':root{color-scheme:light dark;supported-color-schemes:light dark;}',
81
+ 'body{margin:0;padding:0;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;}',
82
+ 'table,td{border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt;}',
83
+ 'img{border:0;height:auto;line-height:100%;outline:none;text-decoration:none;}',
84
+ '@media (prefers-color-scheme: dark){',
85
+ '.pru-email-bg{background-color:#09090b!important;color:#f4f4f5!important;}',
86
+ '.pru-email-card{background-color:#18181b!important;border-color:#27272a!important;}',
87
+ '.pru-email-heading,.pru-email-text{color:#f4f4f5!important;}',
88
+ '.pru-email-muted{color:#a1a1aa!important;}',
89
+ '.pru-email-divider{border-top-color:#27272a!important;}',
90
+ '.pru-email-link{color:#60a5fa!important;}',
91
+ '.pru-email-btn{background-color:#f4f4f5!important;color:#09090b!important;}',
92
+ '}',
93
+ '[data-ogsc] .pru-email-bg{background-color:#09090b!important;color:#f4f4f5!important;}',
94
+ '[data-ogsc] .pru-email-card{background-color:#18181b!important;border-color:#27272a!important;}',
95
+ '[data-ogsc] .pru-email-heading,[data-ogsc] .pru-email-text{color:#f4f4f5!important;}',
96
+ '[data-ogsc] .pru-email-muted{color:#a1a1aa!important;}',
97
+ '[data-ogsc] .pru-email-link{color:#60a5fa!important;}',
98
+ '@media only screen and (max-width:620px){.pru-email-pad{padding:24px 16px!important;}}',
99
+ ].join('')
100
+
101
+ const HEADING_STYLES: Readonly<Record<'h1' | 'h2' | 'h3', string>> = {
102
+ h1: 'margin:0 0 16px;font-size:24px;line-height:1.3;font-weight:700;color:#18181b;',
103
+ h2: 'margin:0 0 12px;font-size:20px;line-height:1.35;font-weight:700;color:#18181b;',
104
+ h3: 'margin:0 0 8px;font-size:16px;line-height:1.4;font-weight:600;color:#18181b;',
105
+ }
106
+
107
+ const PREVIEW_SPACER = '&zwnj;&nbsp;'.repeat(24)
108
+
109
+ function safeEmailUrl(href: string, component: string): string {
110
+ const trimmed = href.trim()
111
+ if (HAS_SCHEME_RE.test(trimmed) && !SAFE_URL_SCHEME_RE.test(trimmed))
112
+ throw new RangeError(`@prunellejs/mail: <${component}> refused unsafe URL "${href}"`)
113
+ return trimmed
114
+ }
115
+
116
+ function appendExtraStyle(base: string, extra?: string): string {
117
+ if (!extra)
118
+ return base
119
+ const normalized = extra.trim()
120
+ if (normalized.length === 0)
121
+ return base
122
+ return base.endsWith(';') ? `${base}${normalized}` : `${base};${normalized}`
123
+ }
124
+
125
+ function safeAlign(align?: TextAlign): TextAlign {
126
+ return align === 'center' || align === 'right' ? align : 'left'
127
+ }
128
+
129
+ /** Root HTML email document with Outlook MSO namespaces/DPI settings, dark-mode meta + CSS, and centered 600px table container. */
130
+ export function Email(props: EmailProps = {}): Html {
131
+ const lang = props.lang ?? 'en'
132
+ const bg = props.backgroundColor ?? '#f4f4f5'
133
+ const cardBg = props.containerBackgroundColor ?? '#ffffff'
134
+ const width = props.width ?? 600
135
+ const titleTag = props.title !== undefined ? `<title>${esc(props.title)}</title>` : ''
136
+ const previewBlock = props.preview !== undefined
137
+ ? `<div data-pru-preview style="display:none;overflow:hidden;line-height:1px;opacity:0;max-height:0;max-width:0;font-size:1px;">${esc(props.preview)}${PREVIEW_SPACER}</div>`
138
+ : ''
139
+
140
+ return raw(
141
+ `<!DOCTYPE html>`
142
+ + `<html lang="${escAttr(lang)}" xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">`
143
+ + `<head>`
144
+ + `<meta charset="utf-8">`
145
+ + `<meta name="viewport" content="width=device-width,initial-scale=1">`
146
+ + `<meta http-equiv="X-UA-Compatible" content="IE=edge">`
147
+ + `<meta name="x-apple-disable-message-reformatting">`
148
+ + `<meta name="color-scheme" content="light dark">`
149
+ + `<meta name="supported-color-schemes" content="light dark">`
150
+ + titleTag
151
+ + `<!--[if gte mso 9]><xml><o:OfficeDocumentSettings><o:AllowPNG/><o:PixelsPerInch>96</o:PixelsPerInch></o:OfficeDocumentSettings></xml><![endif]-->`
152
+ + `<style>${EMAIL_HEAD_CSS}</style>`
153
+ + `</head>`
154
+ + `<body class="pru-email-bg" style="margin:0;padding:0;background-color:${escAttr(bg)};color:#18181b;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;">`
155
+ + previewBlock
156
+ + `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" class="pru-email-bg" style="background-color:${escAttr(bg)};width:100%;margin:0;padding:24px 0;">`
157
+ + `<tr><td align="center" style="padding:0 12px;">`
158
+ + `<!--[if mso]><table role="presentation" align="center" border="0" cellspacing="0" cellpadding="0" width="${width}"><tr><td width="${width}"><![endif]-->`
159
+ + `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" class="pru-email-card" style="max-width:${width}px;width:100%;margin:0 auto;background-color:${escAttr(cardBg)};border-radius:8px;border:1px solid #e4e4e7;overflow:hidden;">`
160
+ + `<tr><td class="pru-email-pad" style="padding:32px 28px;">${esc(props.children)}</td></tr>`
161
+ + `</table>`
162
+ + `<!--[if mso]></td></tr></table><![endif]-->`
163
+ + `</td></tr></table>`
164
+ + `</body></html>`,
165
+ )
166
+ }
167
+
168
+ /** Table-based email layout section with inline padding and optional background color. */
169
+ export function Section(props: SectionProps = {}): Html {
170
+ const align = safeAlign(props.align)
171
+ let tdStyle = `padding:${props.padding ?? '8px 0'};`
172
+ if (props.backgroundColor !== undefined)
173
+ tdStyle += `background-color:${props.backgroundColor};`
174
+ tdStyle = appendExtraStyle(tdStyle, props.style)
175
+
176
+ return raw(
177
+ `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;">`
178
+ + `<tr><td align="${align}" style="${escAttr(tdStyle)}">${esc(props.children)}</td></tr>`
179
+ + `</table>`,
180
+ )
181
+ }
182
+
183
+ /** Email-safe heading (`h1`–`h3`) with inline typography and dark-mode class. */
184
+ export function Heading(props: HeadingProps = {}): Html {
185
+ const tag = props.as === 'h2' || props.as === 'h3' ? props.as : 'h1'
186
+ let style = HEADING_STYLES[tag]
187
+ if (props.align !== undefined)
188
+ style += `text-align:${safeAlign(props.align)};`
189
+ style = appendExtraStyle(style, props.style)
190
+ return raw(`<${tag} class="pru-email-heading" style="${escAttr(style)}">${esc(props.children)}</${tag}>`)
191
+ }
192
+
193
+ /** Email-safe paragraph with readable line height, inline styles, and optional muted tone. */
194
+ export function Text(props: TextProps = {}): Html {
195
+ const cls = props.muted ? 'pru-email-muted' : 'pru-email-text'
196
+ const color = props.muted ? '#71717a' : '#27272a'
197
+ let style = `margin:0 0 16px;font-size:15px;line-height:1.6;color:${color};`
198
+ if (props.align !== undefined)
199
+ style += `text-align:${safeAlign(props.align)};`
200
+ style = appendExtraStyle(style, props.style)
201
+ return raw(`<p class="${cls}" style="${escAttr(style)}">${esc(props.children)}</p>`)
202
+ }
203
+
204
+ /** Bulletproof Outlook VML + dark-mode CTA button. */
205
+ export function Button(props: ButtonProps): Html {
206
+ const href = safeEmailUrl(props.href, 'Button')
207
+ const bg = props.backgroundColor ?? '#18181b'
208
+ const color = props.color ?? '#ffffff'
209
+ const radius = props.borderRadius ?? 6
210
+ const align = safeAlign(props.align)
211
+ const arcsize = Math.min(50, Math.max(0, Math.round((radius / 44) * 100)))
212
+ const label = esc(props.children)
213
+ const linkStyle = appendExtraStyle(
214
+ `display:inline-block;padding:12px 24px;background-color:${bg};color:${color};font-size:15px;font-weight:600;line-height:1.2;text-decoration:none;border-radius:${radius}px;mso-hide:all;`,
215
+ props.style,
216
+ )
217
+
218
+ return raw(
219
+ `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;margin:20px 0;">`
220
+ + `<tr><td align="${align}">`
221
+ + `<!--[if mso]><v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="${escAttr(href)}" style="height:44px;v-text-anchor:middle;width:220px;" arcsize="${arcsize}%" stroke="f" fillcolor="${escAttr(bg)}"><w:anchorlock/><center style="color:${escAttr(color)};font-family:sans-serif;font-size:15px;font-weight:600;">${label}</center></v:roundrect><![endif]-->`
222
+ + `<!--[if !mso]><!--><a href="${escAttr(href)}" class="pru-email-btn" style="${escAttr(linkStyle)}">${label}</a><!--<![endif]-->`
223
+ + `</td></tr></table>`,
224
+ )
225
+ }
226
+
227
+ /** Horizontal rule styled for email clients and dark mode. */
228
+ export function Divider(props: DividerProps = {}): Html {
229
+ const color = props.color ?? '#e4e4e7'
230
+ const margin = props.margin ?? '24px 0'
231
+ const style = appendExtraStyle(`border:0;border-top:1px solid ${color};margin:${margin};`, props.style)
232
+ return raw(`<hr class="pru-email-divider" style="${escAttr(style)}">`)
233
+ }
234
+
235
+ /** Muted footer section separated by a top border. */
236
+ export function Footer(props: FooterProps = {}): Html {
237
+ const align = safeAlign(props.align)
238
+ const tdStyle = appendExtraStyle(
239
+ 'padding-top:16px;font-size:12px;line-height:1.5;color:#71717a;',
240
+ props.style,
241
+ )
242
+ return raw(
243
+ `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" class="pru-email-divider" style="width:100%;margin-top:24px;border-top:1px solid #e4e4e7;">`
244
+ + `<tr><td align="${align}" class="pru-email-muted" style="${escAttr(tdStyle)}">${esc(props.children)}</td></tr>`
245
+ + `</table>`,
246
+ )
247
+ }
248
+
249
+ /** Styled inline hyperlink for email bodies. */
250
+ export function Link(props: LinkProps): Html {
251
+ const href = safeEmailUrl(props.href, 'Link')
252
+ const color = props.color ?? '#2563eb'
253
+ const style = appendExtraStyle(`color:${color};text-decoration:underline;`, props.style)
254
+ return raw(`<a href="${escAttr(href)}" class="pru-email-link" style="${escAttr(style)}">${esc(props.children)}</a>`)
255
+ }
package/src/index.ts ADDED
@@ -0,0 +1,255 @@
1
+ // @prunellejs/mail — Zero-dependency email delivery (JSX/TSX templates, SMTP/SMTPS, Resend, Postmark, MAIL_URL, @prunellejs/jobs retries) + `/_pru/mail` dev outbox & template previews.
2
+ // Built strictly on the public PrunellePlugin API (`server(api).route`, `api.inject(JOBS_SERVICE)`).
3
+
4
+ import type { JobsQueueOptions, JobsService } from 'prunelle/config'
5
+ import type { PrunelleChild } from 'prunelle/jsx-runtime'
6
+ import type { MailBody, Mailer, MailerOptions, MailMessage, MailPreviewEntry, MailPreviewRegisterOptions, MailTransport, SentMail } from './types'
7
+ import { definePlugin, JOBS_SERVICE } from 'prunelle/config'
8
+ import { nodeEnv } from 'prunelle/server'
9
+ import { renderOutboxHtml, renderPreviewEntries } from './preview'
10
+ import { renderMail } from './render'
11
+ import { resend, transportFromUrl } from './transports'
12
+ import { assertNoHeaderInjection, formatAddress, MailNotConfiguredError, normalizeList } from './types'
13
+
14
+ export { Button, Divider, Email, Footer, Heading, Link, Section, Text } from './components'
15
+ export type { ButtonProps, DividerProps, EmailProps, FooterProps, HeadingProps, LinkProps, SectionProps, TextAlign, TextProps } from './components'
16
+ export { htmlToText, renderMail } from './render'
17
+ export { buildMimeMessage, dotStuffSmtpData, smtp } from './smtp'
18
+ export type { SmtpOptions } from './smtp'
19
+ export { postmark, resend, transportFromUrl } from './transports'
20
+ export type { PostmarkOptions, ResendOptions } from './transports'
21
+ export { MailNotConfiguredError } from './types'
22
+ export type { MailAddress, MailBody, Mailer, MailerOptions, MailMessage, MailPreviewEntry, MailPreviewOptions, MailPreviewRegisterOptions, MailRetryOptions, MailTransport, RenderedMail, RenderedMailPreview, SentMail } from './types'
23
+
24
+ const DEFAULT_QUEUE_NAME = 'mail.deliver'
25
+ const DEFAULT_RETRY_OPTIONS: JobsQueueOptions = { attempts: 3, backoff: 'exponential' }
26
+
27
+ function isDevOrTest(devFlag: boolean): boolean {
28
+ const env = nodeEnv()
29
+ if (env === 'production')
30
+ return false
31
+ return devFlag || env === 'test'
32
+ }
33
+
34
+ function toPreviewEntry(
35
+ nameOrEntry: string | MailPreviewEntry,
36
+ renderOrComponent?: ((props?: Record<string, unknown>) => MailBody) | (() => MailBody),
37
+ samplePropsOrOptions?: Record<string, unknown> | MailPreviewRegisterOptions,
38
+ options?: MailPreviewRegisterOptions,
39
+ ): MailPreviewEntry {
40
+ if (typeof nameOrEntry !== 'string')
41
+ return nameOrEntry
42
+ if (typeof renderOrComponent !== 'function')
43
+ throw new TypeError('@prunellejs/mail: preview() requires a render function or component')
44
+
45
+ // Distinguish `preview(name, () => <T />, { subject })` from `preview(name, Comp, { ...sampleProps }, { subject })`.
46
+ const hasExplicitProps = options !== undefined || (samplePropsOrOptions !== undefined && renderOrComponent.length > 0)
47
+ if (hasExplicitProps) {
48
+ const props = samplePropsOrOptions as Record<string, unknown>
49
+ return {
50
+ name: nameOrEntry,
51
+ subject: options?.subject,
52
+ props,
53
+ render: () => (renderOrComponent as (p: Record<string, unknown>) => PrunelleChild | Promise<PrunelleChild>)(props),
54
+ }
55
+ }
56
+ const opts = samplePropsOrOptions as MailPreviewRegisterOptions | undefined
57
+ return {
58
+ name: nameOrEntry,
59
+ subject: opts?.subject,
60
+ render: renderOrComponent as () => MailBody,
61
+ }
62
+ }
63
+
64
+ function createTransportResolver(explicitTransport: MailTransport | undefined): () => MailTransport | undefined {
65
+ let cachedMailUrl: string | undefined
66
+ let cachedUrlTransport: MailTransport | undefined
67
+ return () => {
68
+ if (explicitTransport !== undefined)
69
+ return explicitTransport
70
+ const envUrl = process.env.MAIL_URL
71
+ if (envUrl) {
72
+ if (envUrl !== cachedMailUrl) {
73
+ cachedUrlTransport = transportFromUrl(envUrl)
74
+ cachedMailUrl = envUrl
75
+ }
76
+ return cachedUrlTransport
77
+ }
78
+ if (process.env.RESEND_API_KEY)
79
+ return resend({ apiKey: process.env.RESEND_API_KEY })
80
+ return undefined
81
+ }
82
+ }
83
+
84
+ async function deliverRecord(params: {
85
+ record: SentMail
86
+ transport: MailTransport | undefined
87
+ devOrTest: boolean
88
+ optional: boolean
89
+ asyncQueue: boolean
90
+ queueName: string
91
+ jobs: JobsService | undefined
92
+ }): Promise<void> {
93
+ const { record, transport, devOrTest, optional, asyncQueue, queueName, jobs } = params
94
+ if (transport === undefined) {
95
+ if (!devOrTest && !optional)
96
+ throw new MailNotConfiguredError()
97
+ return
98
+ }
99
+
100
+ if (jobs !== undefined && asyncQueue) {
101
+ await jobs.enqueue(queueName, record, { key: record.id })
102
+ return
103
+ }
104
+
105
+ try {
106
+ await transport.send(record)
107
+ }
108
+ catch (error) {
109
+ if (jobs !== undefined) {
110
+ await jobs.enqueue(queueName, record, { key: record.id })
111
+ return
112
+ }
113
+ throw error
114
+ }
115
+ }
116
+
117
+ export function createMailer(options: MailerOptions = {}): Mailer {
118
+ const outbox: SentMail[] = []
119
+ const previews: MailPreviewEntry[] = [...(options.previews ?? [])]
120
+ const route = options.previewRoute ?? '/_pru/mail'
121
+ const queueName = options.retries?.queue ?? DEFAULT_QUEUE_NAME
122
+ const queueOpts: JobsQueueOptions = {
123
+ attempts: options.retries?.attempts ?? DEFAULT_RETRY_OPTIONS.attempts,
124
+ backoff: options.retries?.backoff ?? DEFAULT_RETRY_OPTIONS.backoff,
125
+ }
126
+
127
+ let serverDev: boolean | undefined
128
+ let injectJobs: (() => JobsService | undefined) | undefined
129
+ const registeredJobs = new WeakSet<JobsService>()
130
+ const getTransport = createTransportResolver(options.transport)
131
+
132
+ const ensureJobsQueue = (): JobsService | undefined => {
133
+ const svc = injectJobs?.()
134
+ if (svc === undefined)
135
+ return undefined
136
+ if (!registeredJobs.has(svc)) {
137
+ registeredJobs.add(svc)
138
+ svc.queue<SentMail>(queueName, async (record) => {
139
+ const transport = getTransport()
140
+ if (transport === undefined)
141
+ throw new MailNotConfiguredError()
142
+ await transport.send(record)
143
+ }, queueOpts)
144
+ }
145
+ return svc
146
+ }
147
+
148
+ const plugin = definePlugin({
149
+ name: '@prunellejs/mail',
150
+ after: ['@prunellejs/jobs'],
151
+ server(api) {
152
+ serverDev = api.dev
153
+ injectJobs = () => api.inject(JOBS_SERVICE)
154
+ ensureJobsQueue()
155
+
156
+ api.onShutdown(() => {
157
+ injectJobs = undefined
158
+ })
159
+
160
+ const enablePreview = options.preview !== false && isDevOrTest(api.dev)
161
+ if (!enablePreview)
162
+ return
163
+
164
+ api.route('GET', `${route}.json`, async (ctx) => {
165
+ const renderedPreviews = await renderPreviewEntries(previews)
166
+ return ctx.json({ count: outbox.length, messages: outbox, previews: renderedPreviews })
167
+ })
168
+
169
+ api.route('GET', route, async () => {
170
+ const renderedPreviews = await renderPreviewEntries(previews)
171
+ const html = renderOutboxHtml(outbox, renderedPreviews)
172
+ // prunelle adds the app's CSP with this page's <style> hash.
173
+ return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } })
174
+ })
175
+ },
176
+ })
177
+
178
+ const instance: Mailer = {
179
+ ...plugin,
180
+ outbox,
181
+ isConfigured() {
182
+ return getTransport() !== undefined
183
+ },
184
+ requires() {
185
+ const unmet: string[] = []
186
+ if (getTransport() === undefined && !options.optional)
187
+ unmet.push('no transport, so every send() throws: set `RESEND_API_KEY`, or pass `transport` to `createMailer()` (`optional: true` drops mail instead).')
188
+ if ((options.from ?? process.env.MAIL_FROM) === undefined)
189
+ unmet.push('no sender, so mail goes out from noreply@localhost: set `MAIL_FROM`, or pass `from` to `createMailer()`.')
190
+ return unmet
191
+ },
192
+ clearOutbox() {
193
+ outbox.length = 0
194
+ },
195
+ preview(
196
+ nameOrEntry: string | MailPreviewEntry,
197
+ renderOrComponent?: ((props?: Record<string, unknown>) => MailBody) | (() => MailBody),
198
+ samplePropsOrOptions?: Record<string, unknown> | MailPreviewRegisterOptions,
199
+ previewOptions?: MailPreviewRegisterOptions,
200
+ ) {
201
+ const entry = toPreviewEntry(nameOrEntry, renderOrComponent, samplePropsOrOptions, previewOptions)
202
+ const existingIndex = previews.findIndex(p => p.name === entry.name)
203
+ if (existingIndex >= 0)
204
+ previews[existingIndex] = entry
205
+ else
206
+ previews.push(entry)
207
+ },
208
+ async send(message: MailMessage) {
209
+ assertNoHeaderInjection(message.subject, 'subject')
210
+ const from = message.from ?? options.from ?? process.env.MAIL_FROM ?? 'noreply@localhost'
211
+ const toList = normalizeList(message.to ?? options.to ?? process.env.MAIL_TO, 'to')
212
+ if (toList.length === 0)
213
+ throw new Error(`@prunellejs/mail: send({ subject: ${JSON.stringify(message.subject)} }) has no recipient: give it \`to\`, pass \`to\` to \`createMailer()\`, or set \`MAIL_TO\`.`)
214
+
215
+ let html = message.html
216
+ let text = message.text
217
+ if (message.body !== undefined) {
218
+ const rendered = await renderMail(message.body)
219
+ html = html ?? rendered.html
220
+ text = text ?? rendered.text
221
+ }
222
+
223
+ const record: SentMail = {
224
+ id: crypto.randomUUID(),
225
+ from: formatAddress(from, 'from'),
226
+ to: toList,
227
+ ...(message.replyTo !== undefined ? { replyTo: formatAddress(message.replyTo, 'replyTo') } : {}),
228
+ subject: message.subject,
229
+ ...(text !== undefined ? { text } : {}),
230
+ ...(html !== undefined ? { html } : {}),
231
+ sentAt: new Date().toISOString(),
232
+ }
233
+
234
+ const devOrTest = isDevOrTest(serverDev ?? (process.env.PRUNELLE_DEV === '1'))
235
+ await deliverRecord({
236
+ record,
237
+ transport: getTransport(),
238
+ devOrTest,
239
+ optional: options.optional === true,
240
+ asyncQueue: options.asyncQueue === true,
241
+ queueName,
242
+ jobs: ensureJobsQueue(),
243
+ })
244
+
245
+ // Non-dev/test runs keep no copy: the outbox holds sign-in links in plain text, and no preview reads it there.
246
+ if (devOrTest) {
247
+ outbox.unshift(record)
248
+ if (outbox.length > 100)
249
+ outbox.length = 100
250
+ }
251
+ return record
252
+ },
253
+ }
254
+ return instance
255
+ }