@hamur/mail 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +14 -2
  3. package/dist/src/devtools.js +268 -0
  4. package/dist/src/index.js +573 -0
  5. package/dist/src/server/index.js +916 -0
  6. package/dist/src/test.js +39 -0
  7. package/dist/types/src/address.d.ts +14 -0
  8. package/dist/types/src/build/devtools.d.ts +20 -0
  9. package/dist/types/src/build/outbox.d.ts +35 -0
  10. package/dist/types/src/build/setup.d.ts +22 -0
  11. package/dist/types/src/build/templates.d.ts +12 -0
  12. package/dist/types/src/devtools-model.d.ts +12 -0
  13. package/dist/types/src/devtools.d.ts +2 -0
  14. package/dist/types/src/html.d.ts +10 -0
  15. package/dist/types/src/index.d.ts +24 -0
  16. package/dist/types/src/mime.d.ts +32 -0
  17. package/dist/types/src/module.d.ts +3 -0
  18. package/dist/types/src/options.d.ts +12 -0
  19. package/dist/types/src/server/deliver.d.ts +15 -0
  20. package/dist/types/src/server/devtools-routes.d.ts +1 -0
  21. package/dist/types/src/server/door-dev.d.ts +3 -0
  22. package/dist/types/src/server/door.d.ts +2 -0
  23. package/dist/types/src/server/hooks.d.ts +5 -0
  24. package/dist/types/src/server/index.d.ts +6 -0
  25. package/dist/types/src/server/message.d.ts +3 -0
  26. package/dist/types/src/server/plugin.d.ts +1 -0
  27. package/dist/types/src/server/preview.d.ts +8 -0
  28. package/dist/types/src/server/queue.d.ts +19 -0
  29. package/dist/types/src/server/runtime.d.ts +5 -0
  30. package/dist/types/src/server/send.d.ts +54 -0
  31. package/dist/types/src/server/task.d.ts +4 -0
  32. package/dist/types/src/server/template.d.ts +8 -0
  33. package/dist/types/src/smtp/client.d.ts +28 -0
  34. package/dist/types/src/smtp/dkim.d.ts +8 -0
  35. package/dist/types/src/smtp/sockets.d.ts +42 -0
  36. package/dist/types/src/test.d.ts +27 -0
  37. package/dist/types/src/transport.d.ts +28 -0
  38. package/dist/types/src/transports/cloudflare.d.ts +17 -0
  39. package/dist/types/src/transports/http.d.ts +26 -0
  40. package/dist/types/src/transports/mailgun.d.ts +9 -0
  41. package/dist/types/src/transports/outbox.d.ts +9 -0
  42. package/dist/types/src/transports/postmark.d.ts +8 -0
  43. package/dist/types/src/transports/resend.d.ts +7 -0
  44. package/dist/types/src/transports/sendgrid.d.ts +7 -0
  45. package/dist/types/src/transports/ses.d.ts +9 -0
  46. package/dist/types/src/transports/smtp.d.ts +3 -0
  47. package/dist/types/src/types.d.ts +124 -0
  48. package/package.json +36 -4
  49. package/src/address.ts +86 -0
  50. package/src/build/devtools.ts +81 -0
  51. package/src/build/outbox.ts +69 -0
  52. package/src/build/setup.ts +226 -0
  53. package/src/build/templates.ts +113 -0
  54. package/src/devtools-model.ts +24 -0
  55. package/src/devtools.ts +351 -0
  56. package/src/env.d.ts +36 -0
  57. package/src/html.ts +274 -0
  58. package/src/index.ts +25 -0
  59. package/src/mime.ts +220 -0
  60. package/src/module.ts +11 -0
  61. package/src/options.ts +157 -0
  62. package/src/server/deliver.ts +54 -0
  63. package/src/server/devtools-routes.ts +32 -0
  64. package/src/server/door-dev.ts +6 -0
  65. package/src/server/door.ts +4 -0
  66. package/src/server/hooks.ts +13 -0
  67. package/src/server/index.ts +28 -0
  68. package/src/server/message.ts +36 -0
  69. package/src/server/plugin.ts +4 -0
  70. package/src/server/preview.ts +41 -0
  71. package/src/server/queue.ts +58 -0
  72. package/src/server/runtime.ts +45 -0
  73. package/src/server/send.ts +308 -0
  74. package/src/server/task.ts +13 -0
  75. package/src/server/template.ts +37 -0
  76. package/src/smtp/client.ts +305 -0
  77. package/src/smtp/dkim.ts +72 -0
  78. package/src/smtp/sockets.ts +296 -0
  79. package/src/test.ts +70 -0
  80. package/src/transport.ts +35 -0
  81. package/src/transports/cloudflare.ts +68 -0
  82. package/src/transports/http.ts +75 -0
  83. package/src/transports/mailgun.ts +31 -0
  84. package/src/transports/outbox.ts +64 -0
  85. package/src/transports/postmark.ts +59 -0
  86. package/src/transports/resend.ts +46 -0
  87. package/src/transports/sendgrid.ts +64 -0
  88. package/src/transports/ses.ts +53 -0
  89. package/src/transports/smtp.ts +37 -0
  90. package/src/types.ts +104 -0
@@ -0,0 +1,113 @@
1
+ import { readdirSync, readFileSync, statSync } from "node:fs"
2
+ import { basename, extname, join, relative, sep } from "node:path"
3
+ import { diagnostic } from "hamur/kit"
4
+
5
+ export interface MailTemplateFile {
6
+ name: string
7
+ file: string
8
+ }
9
+
10
+ const TEMPLATE_NAME = /^[A-Z][A-Za-z0-9]*$/
11
+ const scanners: Record<string, Bun.Transpiler> = {
12
+ ".ts": new Bun.Transpiler({ loader: "ts" }),
13
+ ".js": new Bun.Transpiler({ loader: "js" }),
14
+ ".tsx": new Bun.Transpiler({ loader: "tsx" }),
15
+ ".jsx": new Bun.Transpiler({ loader: "jsx" }),
16
+ }
17
+ const COMMENT = /<!--[\s\S]*?-->|\/\*[\s\S]*?\*\/|^\s*\/\/.*$/gm
18
+ const STYLE = /<style[\s>]/i
19
+
20
+ const slashes = (path: string): string => path.split(sep).join("/")
21
+
22
+ /** The templates of the app's `mail/` folder, then each layer's in order; the first of a name wins. A script without a default export is a helper. */
23
+ export function scanTemplates(srcDirs: string[], extensions: string[]): MailTemplateFile[] {
24
+ const found = new Map<string, MailTemplateFile>()
25
+ for (const srcDir of srcDirs) {
26
+ const dir = join(srcDir, "mail")
27
+ let entries: string[]
28
+ try {
29
+ entries = readdirSync(dir).sort()
30
+ } catch {
31
+ continue
32
+ }
33
+ for (const ext of extensions) {
34
+ for (const entry of entries) {
35
+ const name = basename(entry, ext)
36
+ const file = join(dir, entry)
37
+ if (extname(entry) !== ext || !TEMPLATE_NAME.test(name) || found.has(name) || !statSync(file).isFile()) continue
38
+ const scanner = scanners[ext]
39
+ if (scanner && !scanner.scan(readFileSync(file)).exports.includes("default")) continue
40
+ found.set(name, { name, file })
41
+ }
42
+ }
43
+ }
44
+ return [...found.values()].sort((a, b) => (a.name < b.name ? -1 : 1))
45
+ }
46
+
47
+ /** The warning of each template with a `<style>` block. */
48
+ export function styleWarnings(rootDir: string, templates: MailTemplateFile[]): string[] {
49
+ return templates
50
+ .filter(({ file }) => STYLE.test(readFileSync(file, "utf8").replace(COMMENT, "")))
51
+ .map(({ file }) =>
52
+ diagnostic(
53
+ "HAMUR_W6707",
54
+ `${slashes(relative(rootDir, file))} has a <style> block; mail clients drop it, so write styles inline`,
55
+ ),
56
+ )
57
+ }
58
+
59
+ /** `#hamur/mail/templates`: per name, a lazy import of the server build, and the adapter's `renderComponent` when there is a template. */
60
+ export function templatesModule(templates: MailTemplateFile[], serverEntry: () => string): string {
61
+ const entries = templates.map(({ name, file }) => ` ${name}: () => import(${JSON.stringify(file)}),\n`)
62
+ return [
63
+ templates.length
64
+ ? `export { renderComponent } from ${JSON.stringify(serverEntry())};`
65
+ : "export const renderComponent = undefined;",
66
+ `export const templates = {\n${entries.join("")}};`,
67
+ "",
68
+ ].join("\n")
69
+ }
70
+
71
+ /** A Vue component's `$props`, the second parameter of a Svelte component, else the first parameter of a function component. */
72
+ const PROPS = `type MailProps<T> = T extends abstract new (...args: never) => { $props: infer P }
73
+ ? P
74
+ : T extends (...args: infer A) => unknown
75
+ ? A extends [unknown, infer P, ...unknown[]]
76
+ ? P
77
+ : A extends [(infer P)?, ...unknown[]]
78
+ ? P
79
+ : never
80
+ : never;`
81
+
82
+ /** The inputs of an Angular component; their types do not say which are required. */
83
+ const ANGULAR_PROPS = `import type { InputSignalWithTransform } from "@angular/core";
84
+
85
+ type MailProps<T> = T extends abstract new (...args: never) => infer C
86
+ ? {
87
+ [K in keyof C as C[K] extends InputSignalWithTransform<any, any>
88
+ ? K
89
+ : C[K] extends (...args: never) => unknown
90
+ ? never
91
+ : K]?: C[K] extends InputSignalWithTransform<any, infer W> ? W : C[K];
92
+ }
93
+ : never;`
94
+
95
+ /** `.hamur/types/mail.d.ts`, each template's props in `MailTemplates`. */
96
+ export function templateTypes(templates: MailTemplateFile[], typesDir: string, library: string): string {
97
+ if (!templates.length) return "export {};\n"
98
+ return [
99
+ library === "angular" ? ANGULAR_PROPS : PROPS,
100
+ "",
101
+ `declare module "@hamur/mail" {`,
102
+ " interface MailTemplates {",
103
+ ...templates.map(
104
+ ({ name, file }) =>
105
+ ` ${name}: MailProps<typeof import(${JSON.stringify(slashes(relative(typesDir, file)))}).default>;`,
106
+ ),
107
+ " }",
108
+ "}",
109
+ "",
110
+ "export {};",
111
+ "",
112
+ ].join("\n")
113
+ }
@@ -0,0 +1,24 @@
1
+ /** What a mail's document may load in the `mail` tab's frame. */
2
+ export const MAIL_CSP = "default-src 'none'; img-src * data:; style-src 'unsafe-inline'"
3
+
4
+ /** The mail's document inside one that starts with the policy, so no markup in the mail comes before it. */
5
+ export function framedDocument(html: string): string {
6
+ return `<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="${MAIL_CSP}"></head><body style="margin:0">${html}</body></html>`
7
+ }
8
+
9
+ /** The props box's text as an object, or why it is not one. */
10
+ export function parseProps(text: string): { props: Record<string, unknown> } | { error: string } {
11
+ if (text.trim() === "") return { props: {} }
12
+ let value: unknown
13
+ try {
14
+ value = JSON.parse(text)
15
+ } catch (error) {
16
+ return { error: `Props are not JSON: ${error instanceof Error ? error.message : String(error)}` }
17
+ }
18
+ if (typeof value !== "object" || value === null || Array.isArray(value))
19
+ return { error: "Props must be a JSON object" }
20
+ return { props: value as Record<string, unknown> }
21
+ }
22
+
23
+ /** The file name a download of the outbox message `name` gets. */
24
+ export const emlFileName = (name: string): string => `${name.replace(/[^\w.@-]+/g, "_")}.eml`
@@ -0,0 +1,351 @@
1
+ import { defineDevtoolsApp } from "hamur/app"
2
+ import type { MailListAnswer } from "./build/devtools.ts"
3
+ import type { MailSummary, OutboxRecord } from "./build/outbox.ts"
4
+ import { emlFileName, framedDocument, MAIL_CSP, parseProps } from "./devtools-model.ts"
5
+
6
+ type Part = "outbox" | "templates"
7
+ type Shown = "html" | "text" | "headers"
8
+
9
+ const FOCUS = "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
10
+ const BUTTON = `inline-flex items-center gap-1.5 h-6 px-2 rounded-md border-0 bg-transparent text-fg-2 ring-1 ring-inset ring-line-strong font-medium text-sm whitespace-nowrap cursor-pointer hover:bg-hover hover:text-fg disabled:opacity-40 disabled:cursor-default ${FOCUS}`
11
+ const TAB = (on: boolean) =>
12
+ `inline-flex items-center h-7 px-0.5 mr-3.5 border-0 border-b-2 bg-transparent text-sm cursor-pointer ${FOCUS} ${on ? "border-fg text-fg" : "border-transparent text-fg-3 hover:text-fg"}`
13
+ const PILL = (on: boolean) =>
14
+ `inline-flex items-center h-6 px-2 rounded-md border-0 font-medium text-xs whitespace-nowrap cursor-pointer ${FOCUS} ${on ? "bg-active text-fg" : "bg-transparent text-fg-3 hover:bg-hover hover:text-fg"}`
15
+ const TEXTAREA = `block w-full min-h-20 px-2 py-1.5 rounded-md border-0 bg-field ring-1 ring-inset ring-line font-mono text-xs text-fg placeholder:text-fg-4 ${FOCUS}`
16
+ const NOTICE = "m-0 p-4 text-sm text-fg-3"
17
+ const FAIL = "text-xs text-red"
18
+ const LABEL = "text-xs font-medium text-fg-3"
19
+
20
+ const element = <K extends keyof HTMLElementTagNameMap>(
21
+ tag: K,
22
+ props: Partial<HTMLElementTagNameMap[K]> = {},
23
+ ...children: (Node | string)[]
24
+ ): HTMLElementTagNameMap[K] => {
25
+ const node = Object.assign(document.createElement(tag), props)
26
+ node.append(...children)
27
+ return node
28
+ }
29
+
30
+ const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error))
31
+
32
+ function frame(html: string): HTMLIFrameElement {
33
+ const iframe = element("iframe", {
34
+ className: "block w-full flex-1 min-h-64 border-0 rounded-md bg-white",
35
+ title: "Message HTML",
36
+ srcdoc: framedDocument(html),
37
+ referrerPolicy: "no-referrer",
38
+ })
39
+ iframe.setAttribute("sandbox", "")
40
+ iframe.setAttribute("csp", MAIL_CSP)
41
+ return iframe
42
+ }
43
+
44
+ const pre = (text: string): HTMLElement =>
45
+ element(
46
+ "pre",
47
+ {
48
+ className:
49
+ "m-0 px-3 py-2 rounded-lg bg-field font-mono text-xs text-fg-2 whitespace-pre-wrap break-words overflow-auto",
50
+ },
51
+ text,
52
+ )
53
+
54
+ function download(name: string, eml: string): void {
55
+ const url = URL.createObjectURL(new Blob([eml], { type: "message/rfc822" }))
56
+ const link = element("a", { href: url, download: emlFileName(name) })
57
+ link.click()
58
+ setTimeout(() => URL.revokeObjectURL(url), 1000)
59
+ }
60
+
61
+ function shownTabs(
62
+ current: Shown,
63
+ choose: (next: Shown) => void,
64
+ names: readonly Shown[] = ["html", "text", "headers"],
65
+ ): HTMLElement {
66
+ return element(
67
+ "div",
68
+ { className: "flex gap-1" },
69
+ ...names.map((name) => {
70
+ const button = element("button", { type: "button", className: PILL(name === current) }, name.toUpperCase())
71
+ button.dataset.shown = name
72
+ button.addEventListener("click", () => choose(name))
73
+ return button
74
+ }),
75
+ )
76
+ }
77
+
78
+ export default defineDevtoolsApp({
79
+ async init(canvas, ctx) {
80
+ canvas.className = "flex flex-col flex-1 min-h-0"
81
+ const strip = element("div", {
82
+ className: "flex-none flex gap-0.5 px-3 pt-1 border-b border-line",
83
+ role: "tablist",
84
+ })
85
+ strip.setAttribute("aria-label", "Mail views")
86
+ const note = element("p", { className: `m-0 px-4 py-1 ${FAIL} empty:hidden` })
87
+ note.dataset.error = ""
88
+ const body = element("div", { className: "flex-1 flex min-h-0" })
89
+ canvas.append(strip, note, body)
90
+
91
+ let part: Part = "outbox"
92
+ let messages: MailSummary[] = []
93
+ let transport = "none"
94
+ let templates: string[] = []
95
+ let selected: string | undefined
96
+ let shown: Shown = "html"
97
+ let detail: { name: string; record: OutboxRecord; eml: string } | undefined
98
+ let template: string | undefined
99
+ let propsText = "{}"
100
+ let preview: { html: string; text: string } | undefined
101
+ let previewShown: Shown = "html"
102
+ let previewError = ""
103
+ let detailToken = 0
104
+
105
+ const detailPane = element("div", { className: "flex-1 min-w-0 flex flex-col gap-2 p-3 overflow-auto" })
106
+ const listPane = element("ul", {
107
+ className: "flex-none w-72 m-0 p-1.5 list-none border-r border-line overflow-auto",
108
+ })
109
+
110
+ function paintStrip(): void {
111
+ strip.replaceChildren(
112
+ ...(
113
+ [
114
+ ["outbox", "Outbox"],
115
+ ["templates", "Templates"],
116
+ ] as const
117
+ ).map(([name, title]) => {
118
+ const button = element("button", { type: "button", role: "tab", className: TAB(name === part) }, title)
119
+ button.dataset.part = name
120
+ button.setAttribute("aria-selected", String(name === part))
121
+ button.addEventListener("click", () => {
122
+ part = name
123
+ paint()
124
+ })
125
+ return button
126
+ }),
127
+ )
128
+ }
129
+
130
+ function listItem(message: MailSummary): HTMLElement {
131
+ const button = element(
132
+ "button",
133
+ {
134
+ type: "button",
135
+ className: `flex flex-col items-start gap-0.5 w-full px-2.5 py-1.5 border-0 rounded-md text-left cursor-pointer ${FOCUS} ${message.name === selected ? "bg-active" : "bg-transparent hover:bg-hover"}`,
136
+ },
137
+ element(
138
+ "strong",
139
+ { className: "block max-w-full truncate text-sm font-medium text-fg" },
140
+ message.subject || "(no subject)",
141
+ ),
142
+ element("span", { className: "block max-w-full truncate text-xs text-fg-3" }, message.to.join(", ")),
143
+ element("span", { className: "text-xs text-fg-4" }, new Date(message.date).toLocaleTimeString()),
144
+ )
145
+ button.addEventListener("click", () => void open(message.name))
146
+ const item = element("li", {}, button)
147
+ item.dataset.name = message.name
148
+ return item
149
+ }
150
+
151
+ async function open(name: string): Promise<void> {
152
+ selected = name
153
+ const token = ++detailToken
154
+ paintList()
155
+ try {
156
+ const found = await ctx.rpc<{ record: OutboxRecord; eml: string }>("mail:message", { name })
157
+ if (token !== detailToken) return
158
+ detail = { name, ...found }
159
+ note.textContent = ""
160
+ } catch (error) {
161
+ if (token !== detailToken) return
162
+ detail = undefined
163
+ note.textContent = messageOf(error)
164
+ }
165
+ paintDetail()
166
+ }
167
+
168
+ function paintList(): void {
169
+ listPane.replaceChildren(...messages.map(listItem))
170
+ }
171
+
172
+ function paintDetail(): void {
173
+ if (!detail) {
174
+ detailPane.replaceChildren(element("p", { className: NOTICE }, "Pick a message"))
175
+ return
176
+ }
177
+ const { name, record, eml } = detail
178
+ const save = element("button", { type: "button", className: BUTTON }, "Download .eml")
179
+ save.addEventListener("click", () => download(name, eml))
180
+ const line = (label: string, value: string) =>
181
+ element(
182
+ "div",
183
+ { className: "flex gap-2 text-xs" },
184
+ element("span", { className: `flex-none w-12 ${LABEL}` }, label),
185
+ element("span", { className: "min-w-0 break-words text-fg" }, value),
186
+ )
187
+ const content =
188
+ shown === "html"
189
+ ? frame(record.html)
190
+ : shown === "text"
191
+ ? pre(record.text || "(no text part)")
192
+ : pre(
193
+ Object.entries(record.headers)
194
+ .map(([key, value]) => `${key}: ${value}`)
195
+ .join("\n") || "(no extra headers)",
196
+ )
197
+ detailPane.replaceChildren(
198
+ element(
199
+ "div",
200
+ { className: "flex items-start gap-2" },
201
+ element("strong", { className: "flex-1 min-w-0 text-sm font-semibold text-fg break-words" }, record.subject),
202
+ save,
203
+ ),
204
+ line("From", record.from),
205
+ line("To", record.to.join(", ")),
206
+ ...(record.cc.length ? [line("Cc", record.cc.join(", "))] : []),
207
+ ...(record.bcc.length ? [line("Bcc", record.bcc.join(", "))] : []),
208
+ line("Date", new Date(record.date).toLocaleString()),
209
+ ...(record.template ? [line("Template", record.template)] : []),
210
+ ...(record.attachments.length
211
+ ? [line("Files", record.attachments.map((file) => `${file.filename} (${file.size} B)`).join(", "))]
212
+ : []),
213
+ shownTabs(shown, (next) => {
214
+ shown = next
215
+ paintDetail()
216
+ }),
217
+ content,
218
+ )
219
+ }
220
+
221
+ function paintOutbox(): void {
222
+ if (!messages.length) {
223
+ body.replaceChildren(
224
+ element(
225
+ "p",
226
+ { className: NOTICE },
227
+ transport === "outbox"
228
+ ? "No mail sent yet"
229
+ : `The outbox is off: mail.transport is ${transport}. Set it to { type: "outbox" } to read mail here.`,
230
+ ),
231
+ )
232
+ return
233
+ }
234
+ paintList()
235
+ paintDetail()
236
+ body.replaceChildren(listPane, detailPane)
237
+ }
238
+
239
+ function paintTemplates(): void {
240
+ if (!templates.length) {
241
+ body.replaceChildren(element("p", { className: NOTICE }, "No template in app/mail/"))
242
+ return
243
+ }
244
+ const choose = element("select", {
245
+ className: `h-6 px-2 rounded-md border-0 bg-field ring-1 ring-inset ring-line text-xs text-fg ${FOCUS}`,
246
+ })
247
+ choose.setAttribute("aria-label", "Template")
248
+ for (const name of templates) choose.append(element("option", { value: name, selected: name === template }, name))
249
+ choose.addEventListener("change", () => {
250
+ template = choose.value
251
+ preview = undefined
252
+ previewError = ""
253
+ paintPreview()
254
+ })
255
+ template ??= templates[0]
256
+ choose.value = template!
257
+ const props = element("textarea", { className: TEXTAREA, rows: 6, value: propsText, spellcheck: false })
258
+ props.setAttribute("aria-label", "Props (JSON)")
259
+ props.addEventListener("input", () => {
260
+ propsText = props.value
261
+ })
262
+ const render = element("button", { type: "button", className: BUTTON }, "Render")
263
+ render.addEventListener("click", () => {
264
+ void (async () => {
265
+ const parsed = parseProps(propsText)
266
+ if ("error" in parsed) {
267
+ previewError = parsed.error
268
+ paintPreview()
269
+ return
270
+ }
271
+ render.disabled = true
272
+ try {
273
+ preview = await ctx.rpc<{ html: string; text: string }>("mail:render", { template, props: parsed.props })
274
+ previewError = ""
275
+ } catch (error) {
276
+ preview = undefined
277
+ previewError = messageOf(error)
278
+ }
279
+ render.disabled = false
280
+ paintPreview()
281
+ })()
282
+ })
283
+ const form = element(
284
+ "div",
285
+ { className: "flex-none w-80 flex flex-col gap-2 p-3 border-r border-line overflow-auto" },
286
+ element("span", { className: LABEL }, "Template"),
287
+ choose,
288
+ element("span", { className: LABEL }, "Props (JSON)"),
289
+ props,
290
+ render,
291
+ element("span", { className: "text-xs text-fg-3" }, "Rendering sends nothing."),
292
+ )
293
+ preview = undefined
294
+ body.replaceChildren(form, previewPane)
295
+ paintPreview()
296
+ }
297
+
298
+ const previewPane = element("div", { className: "flex-1 min-w-0 flex flex-col gap-2 p-3 overflow-auto" })
299
+ function paintPreview(): void {
300
+ if (previewError) {
301
+ previewPane.replaceChildren(element("p", { className: `m-0 whitespace-pre-wrap ${FAIL}` }, previewError))
302
+ previewPane.firstElementChild!.setAttribute("data-error", "")
303
+ return
304
+ }
305
+ if (!preview) {
306
+ previewPane.replaceChildren(element("p", { className: NOTICE }, "Render a template to see it"))
307
+ return
308
+ }
309
+ previewPane.replaceChildren(
310
+ shownTabs(
311
+ previewShown,
312
+ (next) => {
313
+ previewShown = next
314
+ paintPreview()
315
+ },
316
+ ["html", "text"],
317
+ ),
318
+ previewShown === "text" ? pre(preview.text || "(empty)") : frame(preview.html),
319
+ )
320
+ }
321
+
322
+ function paint(): void {
323
+ paintStrip()
324
+ if (part === "outbox") paintOutbox()
325
+ else paintTemplates()
326
+ }
327
+
328
+ const off = ctx.on("devtools:mail", (data) => {
329
+ const pushed = (data as { messages?: MailSummary[] }).messages
330
+ if (!Array.isArray(pushed)) return
331
+ messages = pushed
332
+ if (part === "outbox") {
333
+ if (!selected && messages[0]) void open(messages[0].name)
334
+ paintOutbox()
335
+ }
336
+ })
337
+
338
+ try {
339
+ const list = await ctx.rpc<MailListAnswer>("mail:list")
340
+ messages = list.messages
341
+ transport = list.transport
342
+ templates = (await ctx.rpc<{ templates: string[] }>("mail:templates")).templates
343
+ if (messages[0]) await open(messages[0].name)
344
+ } catch (error) {
345
+ note.textContent = messageOf(error)
346
+ }
347
+ paint()
348
+
349
+ return off
350
+ },
351
+ })
package/src/env.d.ts ADDED
@@ -0,0 +1,36 @@
1
+ declare module "#hamur/mail/config" {
2
+ type Address = import("./types.ts").ParsedAddress
3
+ export const from: Address
4
+ export const replyTo: Address | null
5
+ /** `mail.queue`: each `sendMail` goes through the task `mail:send` unless its `queue` is false. */
6
+ export const queue: boolean
7
+ /** A build of `hamur/test`, where a queued mail is in the outbox once `sendMail` resolved: `callHandler` has no tasks. */
8
+ export const testBuild: boolean
9
+ /** The transport of the run: the configured one, else `outbox` under `hamur dev` and tests. */
10
+ export const transport: import("./types.ts").ResolvedMailTransport | null
11
+ /** True on bun, node and under `hamur dev`, where a transport may keep a connection between sends. */
12
+ export const reuse: boolean
13
+ /** True under `hamur dev`. */
14
+ export const dev: boolean
15
+ /** `site.url` of the config; the server's resolved site is read first. */
16
+ export const siteUrl: string | null
17
+ /** `app.baseURL`, with its trailing slash. */
18
+ export const baseURL: string
19
+ /** The names of the `app/mail/` templates. */
20
+ export const templates: string[]
21
+ /** The language of a template's document. */
22
+ export const lang: string
23
+ export const transports: Partial<
24
+ Record<
25
+ import("./types.ts").MailTransport["type"],
26
+ () => Promise<{ default: import("./transport.ts").OpenTransport }>
27
+ >
28
+ >
29
+ }
30
+
31
+ declare module "#hamur/mail/templates" {
32
+ /** The `renderComponent` of the adapter's server entry; `undefined` while `app/mail/` has no template. */
33
+ export const renderComponent: import("hamur/adapter").AdapterServerEntry["renderComponent"]
34
+ /** Template name → a lazy import of its module in the server build; the default export is the component. */
35
+ export const templates: Record<string, () => Promise<{ default: unknown }>>
36
+ }