@prunellejs/mail 0.0.0-stage → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
+ }