@prunellejs/mail 0.1.1 → 0.6.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/llms.txt +49 -18
- package/package.json +3 -3
- package/src/components.ts +255 -0
- package/src/index.ts +193 -197
- package/src/preview.ts +84 -0
- package/src/render.ts +119 -0
- package/src/smtp.ts +529 -0
- package/src/transports.ts +230 -0
- package/src/types.ts +161 -0
package/src/index.ts
CHANGED
|
@@ -1,167 +1,182 @@
|
|
|
1
|
-
// @prunellejs/mail —
|
|
2
|
-
// Built strictly on the public PrunellePlugin API (server(api).route).
|
|
3
|
-
|
|
4
|
-
import type {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
html?: string | undefined
|
|
27
|
-
sentAt: string
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export interface MailTransport {
|
|
31
|
-
send(mail: SentMail): Promise<void>
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export class MailNotConfiguredError extends Error {
|
|
35
|
-
constructor(message = '@prunellejs/mail: no transport configured (set RESEND_API_KEY or pass transport)') {
|
|
36
|
-
super(message)
|
|
37
|
-
this.name = 'MailNotConfiguredError'
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
const CR_LF_OR_NUL_RE = /[\r\n\0]/
|
|
42
|
-
const ANGLE_BRACKET_RE = /[<>]/
|
|
43
|
-
const NEEDS_DISPLAY_NAME_QUOTES_RE = /[^A-Za-z0-9 !#$%&'*+\-/=?^_`{|}~]/
|
|
44
|
-
const DEFAULT_RESEND_TIMEOUT_MS = 10_000
|
|
45
|
-
|
|
46
|
-
function assertNoHeaderInjection(value: string, label: string): void {
|
|
47
|
-
if (CR_LF_OR_NUL_RE.test(value))
|
|
48
|
-
throw new RangeError(`@prunellejs/mail: ${label} must not contain CR, LF, or NUL characters`)
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
function escapeDisplayName(name: string): string {
|
|
52
|
-
const trimmed = name.trim()
|
|
53
|
-
if (trimmed.length === 0)
|
|
54
|
-
return ''
|
|
55
|
-
if (!NEEDS_DISPLAY_NAME_QUOTES_RE.test(trimmed))
|
|
56
|
-
return trimmed
|
|
57
|
-
return `"${trimmed.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function formatAddress(addr: MailAddress, label: string): string {
|
|
61
|
-
if (typeof addr === 'string') {
|
|
62
|
-
assertNoHeaderInjection(addr, label)
|
|
63
|
-
return addr
|
|
64
|
-
}
|
|
65
|
-
assertNoHeaderInjection(addr.name, `${label} name`)
|
|
66
|
-
assertNoHeaderInjection(addr.address, `${label} address`)
|
|
67
|
-
const address = addr.address.trim()
|
|
68
|
-
if (ANGLE_BRACKET_RE.test(address))
|
|
69
|
-
throw new RangeError(`@prunellejs/mail: ${label} address must not contain angle brackets`)
|
|
70
|
-
const displayName = escapeDisplayName(addr.name)
|
|
71
|
-
return displayName.length > 0 ? `${displayName} <${address}>` : address
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
function normalizeList(to: MailAddress | MailAddress[] | undefined, label: string): string[] {
|
|
75
|
-
if (to === undefined)
|
|
76
|
-
return []
|
|
77
|
-
return Array.isArray(to) ? to.map(item => formatAddress(item, label)) : [formatAddress(to, label)]
|
|
78
|
-
}
|
|
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' }
|
|
79
26
|
|
|
80
27
|
function isDevOrTest(devFlag: boolean): boolean {
|
|
81
28
|
const env = nodeEnv()
|
|
82
29
|
if (env === 'production')
|
|
83
30
|
return false
|
|
84
|
-
return devFlag || env === '
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
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
|
+
}
|
|
91
62
|
}
|
|
92
63
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
if (
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
from: mail.from,
|
|
105
|
-
to: mail.to,
|
|
106
|
-
reply_to: mail.replyTo,
|
|
107
|
-
subject: mail.subject,
|
|
108
|
-
text: mail.text,
|
|
109
|
-
html: mail.html,
|
|
110
|
-
})
|
|
111
|
-
for (let attempt = 0; ; attempt++) {
|
|
112
|
-
const res = await fetch(endpoint, {
|
|
113
|
-
method: 'POST',
|
|
114
|
-
headers: {
|
|
115
|
-
'authorization': `Bearer ${apiKey}`,
|
|
116
|
-
'content-type': 'application/json',
|
|
117
|
-
'idempotency-key': mail.id,
|
|
118
|
-
},
|
|
119
|
-
body,
|
|
120
|
-
...(timeoutMs > 0 ? { signal: AbortSignal.timeout(timeoutMs) } : {}),
|
|
121
|
-
})
|
|
122
|
-
if (res.ok)
|
|
123
|
-
return
|
|
124
|
-
const text = await res.text()
|
|
125
|
-
if ((res.status !== 429 && res.status < 500) || attempt >= retries)
|
|
126
|
-
throw new Error(`@prunellejs/mail (resend): HTTP ${res.status}: ${text}`)
|
|
127
|
-
await Bun.sleep(resendRetryDelay(res, attempt))
|
|
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
|
|
128
75
|
}
|
|
129
|
-
|
|
76
|
+
return cachedUrlTransport
|
|
77
|
+
}
|
|
78
|
+
if (process.env.RESEND_API_KEY)
|
|
79
|
+
return resend({ apiKey: process.env.RESEND_API_KEY })
|
|
80
|
+
return undefined
|
|
130
81
|
}
|
|
131
82
|
}
|
|
132
83
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
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
|
+
}
|
|
140
99
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
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
|
+
}
|
|
147
115
|
}
|
|
148
116
|
|
|
149
117
|
export function createMailer(options: MailerOptions = {}): Mailer {
|
|
150
118
|
const outbox: SentMail[] = []
|
|
151
|
-
|
|
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
|
+
}
|
|
152
126
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
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
|
|
159
146
|
}
|
|
160
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
|
+
|
|
161
178
|
const instance: Mailer = {
|
|
162
|
-
...
|
|
163
|
-
serverDev = dev
|
|
164
|
-
}),
|
|
179
|
+
...plugin,
|
|
165
180
|
outbox,
|
|
166
181
|
isConfigured() {
|
|
167
182
|
return getTransport() !== undefined
|
|
@@ -177,31 +192,55 @@ export function createMailer(options: MailerOptions = {}): Mailer {
|
|
|
177
192
|
clearOutbox() {
|
|
178
193
|
outbox.length = 0
|
|
179
194
|
},
|
|
180
|
-
|
|
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) {
|
|
181
209
|
assertNoHeaderInjection(message.subject, 'subject')
|
|
182
210
|
const from = message.from ?? options.from ?? process.env.MAIL_FROM ?? 'noreply@localhost'
|
|
183
211
|
const toList = normalizeList(message.to ?? options.to ?? process.env.MAIL_TO, 'to')
|
|
184
212
|
if (toList.length === 0)
|
|
185
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
|
+
|
|
186
223
|
const record: SentMail = {
|
|
187
224
|
id: crypto.randomUUID(),
|
|
188
225
|
from: formatAddress(from, 'from'),
|
|
189
226
|
to: toList,
|
|
190
227
|
...(message.replyTo !== undefined ? { replyTo: formatAddress(message.replyTo, 'replyTo') } : {}),
|
|
191
228
|
subject: message.subject,
|
|
192
|
-
...(
|
|
193
|
-
...(
|
|
229
|
+
...(text !== undefined ? { text } : {}),
|
|
230
|
+
...(html !== undefined ? { html } : {}),
|
|
194
231
|
sentAt: new Date().toISOString(),
|
|
195
232
|
}
|
|
196
233
|
|
|
197
234
|
const devOrTest = isDevOrTest(serverDev ?? (process.env.PRUNELLE_DEV === '1'))
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
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
|
+
})
|
|
205
244
|
|
|
206
245
|
// Non-dev/test runs keep no copy: the outbox holds sign-in links in plain text, and no preview reads it there.
|
|
207
246
|
if (devOrTest) {
|
|
@@ -214,46 +253,3 @@ export function createMailer(options: MailerOptions = {}): Mailer {
|
|
|
214
253
|
}
|
|
215
254
|
return instance
|
|
216
255
|
}
|
|
217
|
-
|
|
218
|
-
export interface MailPreviewOptions {
|
|
219
|
-
/** Dev outbox preview route (default: '/_pru/mail'). */
|
|
220
|
-
previewRoute?: string | undefined
|
|
221
|
-
/** Turns the outbox preview off; it is only ever mounted under `prunelle dev` or NODE_ENV development or test, never in production. */
|
|
222
|
-
preview?: false | undefined
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
const MAIL_OUTBOX_CSS = 'body{font-family:system-ui,sans-serif;max-width:48rem;margin:2rem auto;padding:0 1rem;background:#f9fafb}article{border:1px solid #e5e7eb;border-radius:8px;padding:1rem;margin-bottom:1rem;background:#fff}h2{margin:0 0 .25rem;font-size:1rem}.meta,.empty{margin:0 0 .5rem;font-size:.85rem;color:#6b7280}iframe{width:100%;min-height:16rem;border:0}pre{margin:0;white-space:pre-wrap;font-size:.85rem}'
|
|
226
|
-
|
|
227
|
-
function previewPlugin(
|
|
228
|
-
outbox: readonly SentMail[],
|
|
229
|
-
options: MailPreviewOptions,
|
|
230
|
-
onServerInit?: (dev: boolean) => void,
|
|
231
|
-
): PrunellePlugin {
|
|
232
|
-
const route = options.previewRoute ?? '/_pru/mail'
|
|
233
|
-
|
|
234
|
-
return definePlugin({
|
|
235
|
-
name: '@prunellejs/mail',
|
|
236
|
-
server(api) {
|
|
237
|
-
onServerInit?.(api.dev)
|
|
238
|
-
const enablePreview = options.preview !== false && isDevOrTest(api.dev)
|
|
239
|
-
if (!enablePreview)
|
|
240
|
-
return
|
|
241
|
-
|
|
242
|
-
api.route('GET', `${route}.json`, ctx => ctx.json({ count: outbox.length, messages: outbox }))
|
|
243
|
-
|
|
244
|
-
api.route('GET', route, () => {
|
|
245
|
-
const rows = outbox.map(m =>
|
|
246
|
-
`<article>`
|
|
247
|
-
+ `<h2>${esc(m.subject)}</h2>`
|
|
248
|
-
+ `<p class="meta">From: ${esc(m.from)} → To: ${esc(m.to.join(', '))}${m.replyTo ? ` (Reply-To: ${esc(m.replyTo)})` : ''} · ${esc(m.sentAt)}</p>`
|
|
249
|
-
+ (m.html ? `<iframe sandbox="" srcdoc="${escAttr(m.html)}" title="${escAttr(m.subject)}"></iframe>` : `<pre>${esc(m.text ?? '')}</pre>`)
|
|
250
|
-
+ `</article>`,
|
|
251
|
-
).join('')
|
|
252
|
-
|
|
253
|
-
const html = `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Prunelle Mail Outbox (${outbox.length})</title><style>${MAIL_OUTBOX_CSS}</style></head><body><h1>Mail Outbox (${outbox.length})</h1>${rows || '<p class="empty">No messages sent yet.</p>'}</body></html>`
|
|
254
|
-
// prunelle adds the app's CSP with this page's <style> hash.
|
|
255
|
-
return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } })
|
|
256
|
-
})
|
|
257
|
-
},
|
|
258
|
-
})
|
|
259
|
-
}
|
package/src/preview.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// Dev-only outbox and live template preview rendering (`/_pru/mail` and `/_pru/mail.json`).
|
|
2
|
+
// Never emits inline `style="..."` attributes so Prunelle's strict CSP style hash covers the entire page.
|
|
3
|
+
|
|
4
|
+
import type { MailPreviewEntry, RenderedMailPreview, SentMail } from './types'
|
|
5
|
+
import { esc, escAttr } from 'prunelle/server'
|
|
6
|
+
import { renderMail } from './render'
|
|
7
|
+
|
|
8
|
+
const MAIL_OUTBOX_CSS = [
|
|
9
|
+
'body{font-family:system-ui,sans-serif;max-width:52rem;margin:2rem auto;padding:0 1rem;background:#f9fafb;color:#111827}',
|
|
10
|
+
'h1{margin:0 0 1.25rem;font-size:1.5rem}',
|
|
11
|
+
'.section-title{margin:2rem 0 .75rem;font-size:1.1rem;color:#374151;border-bottom:1px solid #e5e7eb;padding-bottom:.35rem}',
|
|
12
|
+
'article{border:1px solid #e5e7eb;border-radius:8px;padding:1rem;margin-bottom:1rem;background:#fff}',
|
|
13
|
+
'h2{margin:0 0 .25rem;font-size:1rem}',
|
|
14
|
+
'.meta,.empty{margin:0 0 .5rem;font-size:.85rem;color:#6b7280}',
|
|
15
|
+
'.error{margin:0 0 .5rem;font-size:.85rem;color:#b91c1c;background:#fef2f2;padding:.5rem;border-radius:4px}',
|
|
16
|
+
'iframe{width:100%;min-height:18rem;border:1px solid #f3f4f6;border-radius:4px;background:#fff}',
|
|
17
|
+
'details{margin-top:.5rem}',
|
|
18
|
+
'summary{cursor:pointer;font-size:.8rem;color:#4b5563;user-select:none}',
|
|
19
|
+
'pre{margin:.4rem 0 0;white-space:pre-wrap;font-size:.85rem;background:#f9fafb;padding:.65rem;border-radius:4px;border:1px solid #f3f4f6}',
|
|
20
|
+
].join('')
|
|
21
|
+
|
|
22
|
+
export async function renderPreviewEntries(entries: readonly MailPreviewEntry[]): Promise<RenderedMailPreview[]> {
|
|
23
|
+
const results: RenderedMailPreview[] = []
|
|
24
|
+
for (const entry of entries) {
|
|
25
|
+
const subject = entry.subject ?? entry.name
|
|
26
|
+
try {
|
|
27
|
+
const rendered = await renderMail(entry.render())
|
|
28
|
+
results.push({
|
|
29
|
+
name: entry.name,
|
|
30
|
+
subject,
|
|
31
|
+
...(entry.props !== undefined ? { props: entry.props } : {}),
|
|
32
|
+
html: rendered.html,
|
|
33
|
+
text: rendered.text,
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
catch (err) {
|
|
37
|
+
results.push({
|
|
38
|
+
name: entry.name,
|
|
39
|
+
subject,
|
|
40
|
+
...(entry.props !== undefined ? { props: entry.props } : {}),
|
|
41
|
+
error: err instanceof Error ? err.message : String(err),
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return results
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function renderSentArticle(m: SentMail): string {
|
|
49
|
+
const meta = `From: ${esc(m.from)} → To: ${esc(m.to.join(', '))}${m.replyTo ? ` (Reply-To: ${esc(m.replyTo)})` : ''} · ${esc(m.sentAt)}`
|
|
50
|
+
let body: string
|
|
51
|
+
if (m.html) {
|
|
52
|
+
body = `<iframe sandbox="" srcdoc="${escAttr(m.html)}" title="${escAttr(m.subject)}"></iframe>`
|
|
53
|
+
+ (m.text !== undefined ? `<details><summary>Plain text</summary><pre>${esc(m.text)}</pre></details>` : '')
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
body = `<pre>${esc(m.text ?? '')}</pre>`
|
|
57
|
+
}
|
|
58
|
+
return `<article><h2>${esc(m.subject)}</h2><p class="meta">${meta}</p>${body}</article>`
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function renderPreviewArticle(p: RenderedMailPreview): string {
|
|
62
|
+
const propsMeta = p.props !== undefined ? ` · Props: ${esc(JSON.stringify(p.props))}` : ''
|
|
63
|
+
const meta = `Template: ${esc(p.name)} · Subject: ${esc(p.subject)}${propsMeta}`
|
|
64
|
+
if (p.error !== undefined)
|
|
65
|
+
return `<article><h2>${esc(p.name)}</h2><p class="meta">${meta}</p><p class="error">${esc(p.error)}</p></article>`
|
|
66
|
+
|
|
67
|
+
const frame = p.html !== undefined
|
|
68
|
+
? `<iframe sandbox="" srcdoc="${escAttr(p.html)}" title="${escAttr(p.name)}"></iframe>`
|
|
69
|
+
: ''
|
|
70
|
+
const textBlock = p.text !== undefined
|
|
71
|
+
? `<details open><summary>Plain text</summary><pre>${esc(p.text)}</pre></details>`
|
|
72
|
+
: ''
|
|
73
|
+
return `<article><h2>${esc(p.name)}</h2><p class="meta">${meta}</p>${frame}${textBlock}</article>`
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function renderOutboxHtml(outbox: readonly SentMail[], previews: readonly RenderedMailPreview[]): string {
|
|
77
|
+
const sentRows = outbox.map(renderSentArticle).join('')
|
|
78
|
+
const previewSection = previews.length > 0
|
|
79
|
+
? `<section><h2 class="section-title">Templates / Previews (${previews.length})</h2>${previews.map(renderPreviewArticle).join('')}</section>`
|
|
80
|
+
: ''
|
|
81
|
+
const sentSection = `<section><h2 class="section-title">Sent Messages (${outbox.length})</h2>${sentRows || '<p class="empty">No messages sent yet.</p>'}</section>`
|
|
82
|
+
|
|
83
|
+
return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Prunelle Mail Outbox (${outbox.length})</title><style>${MAIL_OUTBOX_CSS}</style></head><body><h1>Mail Outbox (${outbox.length})</h1>${previewSection}${sentSection}</body></html>`
|
|
84
|
+
}
|
package/src/render.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Renders JSX/TSX email bodies (compiled Prunelle Html or direct runtime components) to HTML + clean plain text.
|
|
2
|
+
|
|
3
|
+
import type { MailBody, RenderedMail } from './types'
|
|
4
|
+
import { esc } from 'prunelle/server'
|
|
5
|
+
|
|
6
|
+
const NAMED_ENTITIES: Readonly<Record<string, string>> = {
|
|
7
|
+
amp: '&',
|
|
8
|
+
lt: '<',
|
|
9
|
+
gt: '>',
|
|
10
|
+
quot: '"',
|
|
11
|
+
apos: '\'',
|
|
12
|
+
nbsp: ' ',
|
|
13
|
+
ndash: '-',
|
|
14
|
+
mdash: '--',
|
|
15
|
+
hellip: '...',
|
|
16
|
+
copy: '(c)',
|
|
17
|
+
reg: '(R)',
|
|
18
|
+
trade: '(TM)',
|
|
19
|
+
bull: '*',
|
|
20
|
+
middot: '*',
|
|
21
|
+
zwnj: '',
|
|
22
|
+
zwj: '',
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const DOCTYPE_RE = /<!DOCTYPE[^>]*>/gi
|
|
26
|
+
const HEAD_BLOCK_RE = /<head\b[^>]*>[\s\S]*?<\/head>/gi
|
|
27
|
+
const STYLE_OR_SCRIPT_RE = /<(style|script|title)\b[^>]*>[\s\S]*?<\/\1>/gi
|
|
28
|
+
const PREVIEW_BLOCK_RE = /<div\b[^>]*\bdata-pru-preview\b[^>]*>[\s\S]*?<\/div>/gi
|
|
29
|
+
const HTML_COMMENT_RE = /<!--[\s\S]*?-->/g
|
|
30
|
+
const ANCHOR_RE = /<a\b([^>]*)>([\s\S]*?)<\/a>/gi
|
|
31
|
+
const HREF_ATTR_RE = /\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i
|
|
32
|
+
const HR_RE = /<hr\b[^>]*\/?>/gi
|
|
33
|
+
const BR_RE = /<br\b[^>]*\/?>/gi
|
|
34
|
+
const LIST_ITEM_RE = /<li\b[^>]*>/gi
|
|
35
|
+
const DOUBLE_BREAK_OPEN_RE = /<(?:h[1-6]|p|blockquote|ul|ol)\b[^>]*>/gi
|
|
36
|
+
const DOUBLE_BREAK_CLOSE_RE = /<\/(?:h[1-6]|p|blockquote|ul|ol|table|section|header|footer)>/gi
|
|
37
|
+
const SINGLE_BREAK_CLOSE_RE = /<\/(?:div|tr)>/gi
|
|
38
|
+
const TAG_RE = /<[^>]+>/g
|
|
39
|
+
const ENTITY_RE = /&(#x[0-9a-f]+|#\d+|[a-z]+);/gi
|
|
40
|
+
const MULTI_SPACE_RE = /[ \t\f\v]+/g
|
|
41
|
+
const MULTI_BLANK_LINE_RE = /\n{3,}/g
|
|
42
|
+
|
|
43
|
+
function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
|
|
44
|
+
return typeof value === 'object' && value !== null && 'then' in value && typeof (value as { then?: unknown }).then === 'function'
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function resolveBodyToHtml(node: unknown): Promise<string> {
|
|
48
|
+
if (typeof node === 'function')
|
|
49
|
+
return resolveBodyToHtml((node as () => unknown)())
|
|
50
|
+
if (isPromiseLike(node))
|
|
51
|
+
return resolveBodyToHtml(await node)
|
|
52
|
+
if (node == null || typeof node === 'boolean')
|
|
53
|
+
return ''
|
|
54
|
+
if (Array.isArray(node)) {
|
|
55
|
+
let out = ''
|
|
56
|
+
for (let i = 0; i < node.length; i++)
|
|
57
|
+
out += await resolveBodyToHtml(node[i])
|
|
58
|
+
return out
|
|
59
|
+
}
|
|
60
|
+
return esc(node)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function decodeHtmlEntities(text: string): string {
|
|
64
|
+
return text.replace(ENTITY_RE, (full, body: string) => {
|
|
65
|
+
if (body.startsWith('#x') || body.startsWith('#X')) {
|
|
66
|
+
const cp = Number.parseInt(body.slice(2), 16)
|
|
67
|
+
return Number.isFinite(cp) && cp >= 0 && cp <= 0x10FFFF ? String.fromCodePoint(cp) : full
|
|
68
|
+
}
|
|
69
|
+
if (body.startsWith('#')) {
|
|
70
|
+
const cp = Number.parseInt(body.slice(1), 10)
|
|
71
|
+
return Number.isFinite(cp) && cp >= 0 && cp <= 0x10FFFF ? String.fromCodePoint(cp) : full
|
|
72
|
+
}
|
|
73
|
+
return NAMED_ENTITIES[body.toLowerCase()] ?? full
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function replaceAnchorWithText(_full: string, attrs: string, inner: string): string {
|
|
78
|
+
const hrefMatch = HREF_ATTR_RE.exec(attrs)
|
|
79
|
+
const rawHref = hrefMatch !== null ? (hrefMatch[1] ?? hrefMatch[2] ?? hrefMatch[3] ?? '') : ''
|
|
80
|
+
const href = decodeHtmlEntities(rawHref).trim()
|
|
81
|
+
const label = decodeHtmlEntities(inner.replace(TAG_RE, '')).replace(MULTI_SPACE_RE, ' ').trim()
|
|
82
|
+
if (href.length === 0)
|
|
83
|
+
return label
|
|
84
|
+
if (label.length === 0)
|
|
85
|
+
return href
|
|
86
|
+
const bareHref = href.startsWith('mailto:') ? href.slice('mailto:'.length) : href
|
|
87
|
+
if (label === href || label === bareHref)
|
|
88
|
+
return label
|
|
89
|
+
return `${label} (${href})`
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Converts email HTML into a clean, readable plain-text alternative part. */
|
|
93
|
+
export function htmlToText(html: string): string {
|
|
94
|
+
let out = html
|
|
95
|
+
.replace(DOCTYPE_RE, '')
|
|
96
|
+
.replace(HEAD_BLOCK_RE, '')
|
|
97
|
+
.replace(STYLE_OR_SCRIPT_RE, '')
|
|
98
|
+
.replace(PREVIEW_BLOCK_RE, '')
|
|
99
|
+
.replace(HTML_COMMENT_RE, '')
|
|
100
|
+
.replace(ANCHOR_RE, replaceAnchorWithText)
|
|
101
|
+
.replace(HR_RE, '\n\n---\n\n')
|
|
102
|
+
.replace(BR_RE, '\n')
|
|
103
|
+
.replace(LIST_ITEM_RE, '\n- ')
|
|
104
|
+
.replace(DOUBLE_BREAK_OPEN_RE, '\n\n')
|
|
105
|
+
.replace(DOUBLE_BREAK_CLOSE_RE, '\n\n')
|
|
106
|
+
.replace(SINGLE_BREAK_CLOSE_RE, '\n')
|
|
107
|
+
.replace(TAG_RE, '')
|
|
108
|
+
|
|
109
|
+
out = decodeHtmlEntities(out).replace(/\r\n?/g, '\n')
|
|
110
|
+
|
|
111
|
+
const lines = out.split('\n').map(line => line.replace(MULTI_SPACE_RE, ' ').trim())
|
|
112
|
+
return lines.join('\n').replace(MULTI_BLANK_LINE_RE, '\n\n').trim()
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Renders a JSX/TSX email component, compiled Html, or lazy factory to both `html` and `text`. */
|
|
116
|
+
export async function renderMail(body: MailBody): Promise<RenderedMail> {
|
|
117
|
+
const html = await resolveBodyToHtml(body)
|
|
118
|
+
return { html, text: htmlToText(html) }
|
|
119
|
+
}
|