@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,573 @@
1
+ // packages/mail/src/module.ts
2
+ import { defineModule } from "hamur/kit";
3
+
4
+ // packages/mail/src/build/setup.ts
5
+ import { readFile as readFile2 } from "node:fs/promises";
6
+ import { isAbsolute, join as join3, relative as relative2, resolve } from "node:path";
7
+ import {
8
+ DiagnosticError,
9
+ addServer,
10
+ addTask,
11
+ addTemplate,
12
+ addTypeTemplate,
13
+ createResolver as createResolver2,
14
+ diagnostic as diagnostic2,
15
+ useLogger
16
+ } from "hamur/kit";
17
+
18
+ // packages/mail/src/build/devtools.ts
19
+ import { mkdirSync, watch } from "node:fs";
20
+ import { addDevtoolsTab, createResolver, extendDevtoolsRpc, useDevChannel } from "hamur/kit";
21
+
22
+ // packages/mail/src/build/outbox.ts
23
+ import { readdir, readFile } from "node:fs/promises";
24
+ import { join } from "node:path";
25
+ var names = (dir) => readdir(dir).catch(() => []);
26
+ async function listOutbox(dir) {
27
+ const stems = (await names(dir)).filter((file) => file.endsWith(".json")).map((file) => file.slice(0, -".json".length)).sort().reverse();
28
+ const summaries = await Promise.all(stems.map(async (name) => {
29
+ try {
30
+ const record = JSON.parse(await readFile(join(dir, `${name}.json`), "utf8"));
31
+ const { date, from, to, subject, template } = record;
32
+ return { name, date, from, to, subject, ...template === undefined ? {} : { template } };
33
+ } catch {
34
+ return;
35
+ }
36
+ }));
37
+ return summaries.filter((summary) => summary !== undefined);
38
+ }
39
+ async function readOutbox(dir, name) {
40
+ const files = await names(dir);
41
+ if (!files.includes(`${name}.json`) || !files.includes(`${name}.eml`))
42
+ return;
43
+ try {
44
+ const [record, eml] = await Promise.all([
45
+ readFile(join(dir, `${name}.json`), "utf8").then((text) => JSON.parse(text)),
46
+ readFile(join(dir, `${name}.eml`), "utf8")
47
+ ]);
48
+ return { record, eml };
49
+ } catch {
50
+ return;
51
+ }
52
+ }
53
+
54
+ // packages/mail/src/build/devtools.ts
55
+ var MAIL_ICON = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="5" width="18" height="14" rx="2" fill="currentColor" fill-opacity="0.16" stroke="none"></rect><path d="M3 7l9 6 9-6M5 5h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z"></path></svg>';
56
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
57
+ function setupMailDevtools(hamur, options) {
58
+ const { transport } = options;
59
+ addDevtoolsTab({
60
+ name: "mail",
61
+ title: "Mail",
62
+ icon: MAIL_ICON,
63
+ view: { type: "module", entry: createResolver(new URL("../../src/build/devtools.ts", import.meta.url).href).resolve("../devtools.ts") }
64
+ });
65
+ if (!hamur.options.dev)
66
+ return;
67
+ const dir = transport?.type === "outbox" ? transport.dir : undefined;
68
+ let serverUrl;
69
+ hamur.hooks.hook("dev:ready", ({ url }) => {
70
+ serverUrl = new URL(url);
71
+ });
72
+ extendDevtoolsRpc("mail:list", async () => ({
73
+ transport: transport?.type ?? "none",
74
+ messages: dir === undefined ? [] : await listOutbox(dir)
75
+ }));
76
+ extendDevtoolsRpc("mail:message", async (args) => {
77
+ const name = isObject(args) ? args.name : undefined;
78
+ const found = dir !== undefined && typeof name === "string" ? await readOutbox(dir, name) : undefined;
79
+ if (!found)
80
+ throw new Error(`No message ${JSON.stringify(name)} in the outbox`);
81
+ return found;
82
+ });
83
+ extendDevtoolsRpc("mail:templates", () => ({ templates: options.templates() }));
84
+ extendDevtoolsRpc("mail:render", async (args) => {
85
+ if (!serverUrl)
86
+ throw new Error("The dev server is not serving yet");
87
+ const target = new URL(`${hamur.options.app.baseURL}_hamur/devtools/api/mail/render`, serverUrl);
88
+ const response = await fetch(target, {
89
+ method: "POST",
90
+ headers: { "content-type": "application/json" },
91
+ body: JSON.stringify(isObject(args) ? { template: args.template, props: args.props } : {}),
92
+ ...target.protocol === "https:" ? { tls: { rejectUnauthorized: false } } : {}
93
+ });
94
+ const answer = await response.json().catch(() => ({}));
95
+ if (!response.ok || typeof answer.html !== "string")
96
+ throw new Error(answer.error ?? `The template preview answered ${response.status}`);
97
+ return { html: answer.html, text: answer.text ?? "" };
98
+ });
99
+ if (dir === undefined)
100
+ return;
101
+ const channel = useDevChannel();
102
+ let timer;
103
+ try {
104
+ mkdirSync(dir, { recursive: true });
105
+ watch(dir, { persistent: false }, () => {
106
+ clearTimeout(timer);
107
+ timer = setTimeout(() => {
108
+ listOutbox(dir).then((messages) => channel.send("devtools:mail", { messages }, "devtools"));
109
+ }, 50);
110
+ });
111
+ } catch {}
112
+ }
113
+
114
+ // packages/mail/src/build/templates.ts
115
+ import { readdirSync, readFileSync, statSync } from "node:fs";
116
+ import { basename, extname, join as join2, relative, sep } from "node:path";
117
+ import { diagnostic } from "hamur/kit";
118
+ var TEMPLATE_NAME = /^[A-Z][A-Za-z0-9]*$/;
119
+ var scanners = {
120
+ ".ts": new Bun.Transpiler({ loader: "ts" }),
121
+ ".js": new Bun.Transpiler({ loader: "js" }),
122
+ ".tsx": new Bun.Transpiler({ loader: "tsx" }),
123
+ ".jsx": new Bun.Transpiler({ loader: "jsx" })
124
+ };
125
+ var COMMENT = /<!--[\s\S]*?-->|\/\*[\s\S]*?\*\/|^\s*\/\/.*$/gm;
126
+ var STYLE = /<style[\s>]/i;
127
+ var slashes = (path) => path.split(sep).join("/");
128
+ function scanTemplates(srcDirs, extensions) {
129
+ const found = new Map;
130
+ for (const srcDir of srcDirs) {
131
+ const dir = join2(srcDir, "mail");
132
+ let entries;
133
+ try {
134
+ entries = readdirSync(dir).sort();
135
+ } catch {
136
+ continue;
137
+ }
138
+ for (const ext of extensions) {
139
+ for (const entry of entries) {
140
+ const name = basename(entry, ext);
141
+ const file = join2(dir, entry);
142
+ if (extname(entry) !== ext || !TEMPLATE_NAME.test(name) || found.has(name) || !statSync(file).isFile())
143
+ continue;
144
+ const scanner = scanners[ext];
145
+ if (scanner && !scanner.scan(readFileSync(file)).exports.includes("default"))
146
+ continue;
147
+ found.set(name, { name, file });
148
+ }
149
+ }
150
+ }
151
+ return [...found.values()].sort((a, b) => a.name < b.name ? -1 : 1);
152
+ }
153
+ function styleWarnings(rootDir, templates) {
154
+ return templates.filter(({ file }) => STYLE.test(readFileSync(file, "utf8").replace(COMMENT, ""))).map(({ file }) => diagnostic("HAMUR_W6707", `${slashes(relative(rootDir, file))} has a <style> block; mail clients drop it, so write styles inline`));
155
+ }
156
+ function templatesModule(templates, serverEntry) {
157
+ const entries = templates.map(({ name, file }) => ` ${name}: () => import(${JSON.stringify(file)}),
158
+ `);
159
+ return [
160
+ templates.length ? `export { renderComponent } from ${JSON.stringify(serverEntry())};` : "export const renderComponent = undefined;",
161
+ `export const templates = {
162
+ ${entries.join("")}};`,
163
+ ""
164
+ ].join(`
165
+ `);
166
+ }
167
+ var PROPS = `type MailProps<T> = T extends abstract new (...args: never) => { $props: infer P }
168
+ ? P
169
+ : T extends (...args: infer A) => unknown
170
+ ? A extends [unknown, infer P, ...unknown[]]
171
+ ? P
172
+ : A extends [(infer P)?, ...unknown[]]
173
+ ? P
174
+ : never
175
+ : never;`;
176
+ var ANGULAR_PROPS = `import type { InputSignalWithTransform } from "@angular/core";
177
+
178
+ type MailProps<T> = T extends abstract new (...args: never) => infer C
179
+ ? {
180
+ [K in keyof C as C[K] extends InputSignalWithTransform<any, any>
181
+ ? K
182
+ : C[K] extends (...args: never) => unknown
183
+ ? never
184
+ : K]?: C[K] extends InputSignalWithTransform<any, infer W> ? W : C[K];
185
+ }
186
+ : never;`;
187
+ function templateTypes(templates, typesDir, library) {
188
+ if (!templates.length)
189
+ return `export {};
190
+ `;
191
+ return [
192
+ library === "angular" ? ANGULAR_PROPS : PROPS,
193
+ "",
194
+ `declare module "@hamur/mail" {`,
195
+ " interface MailTemplates {",
196
+ ...templates.map(({ name, file }) => ` ${name}: MailProps<typeof import(${JSON.stringify(slashes(relative(typesDir, file)))}).default>;`),
197
+ " }",
198
+ "}",
199
+ "",
200
+ "export {};",
201
+ ""
202
+ ].join(`
203
+ `);
204
+ }
205
+
206
+ // packages/mail/src/build/setup.ts
207
+ var SERVER = "@hamur/mail/server";
208
+ var BUILT = new Set(["outbox", "smtp", "resend", "postmark", "sendgrid", "mailgun", "ses", "cloudflare"]);
209
+ var REUSES = new Set(["bun", "node"]);
210
+ var WORKERS = new Set(["cloudflare", "cloudflare-pages"]);
211
+ var WORKERS_PORTS = [465, 587];
212
+ var WRANGLER_FILES = ["wrangler.json", "wrangler.jsonc"];
213
+ var isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
214
+ async function declaredSendEmailBindings(rootDir, env) {
215
+ let config = {};
216
+ for (const name of WRANGLER_FILES) {
217
+ const text = await readFile2(join3(rootDir, name), "utf8").catch(() => {
218
+ return;
219
+ });
220
+ if (text === undefined)
221
+ continue;
222
+ const parsed = Bun.JSONC.parse(text);
223
+ if (isObject2(parsed))
224
+ config = parsed;
225
+ break;
226
+ }
227
+ const envs = isObject2(config.env) ? config.env : {};
228
+ const chosen = env !== undefined && isObject2(envs[env]) ? { ...config, ...envs[env] } : config;
229
+ const entries = Array.isArray(chosen.send_email) ? chosen.send_email : [];
230
+ return entries.flatMap((entry) => isObject2(entry) && typeof entry.name === "string" ? [entry.name] : []);
231
+ }
232
+ function chooseTransport(configured, run) {
233
+ const transport = run.setup ? { type: "outbox" } : configured ?? (run.dev || run.test ? { type: "outbox" } : undefined);
234
+ if (transport?.type !== "outbox")
235
+ return transport;
236
+ const dir = transport.dir === undefined ? join3(run.buildDir, "mail") : transport.dir;
237
+ return { type: "outbox", dir: isAbsolute(dir) ? dir : resolve(run.rootDir, dir) };
238
+ }
239
+ function checkBuild(transport, preset, siteUrl, sendEmailBindings = []) {
240
+ if (!transport)
241
+ throw new DiagnosticError("HAMUR_E6702", `@hamur/mail needs mail.transport on the ${preset} preset; outbox is for hamur dev and tests`);
242
+ if (siteUrl === undefined)
243
+ throw new DiagnosticError("HAMUR_E6703", "@hamur/mail needs site.url: a mail holds absolute links");
244
+ if (transport.type === "cloudflare") {
245
+ if (preset !== "cloudflare")
246
+ throw new DiagnosticError("HAMUR_E6708", `mail.transport cloudflare runs on the cloudflare preset only (got ${JSON.stringify(preset)})`);
247
+ if (!sendEmailBindings.includes(transport.binding))
248
+ throw new DiagnosticError("HAMUR_E6709", `mail.transport.binding ${JSON.stringify(transport.binding)} is not a send_email binding of the app's wrangler config; add send_email: [{ name: ${JSON.stringify(transport.binding)} }]`);
249
+ }
250
+ if (WORKERS.has(preset)) {
251
+ if (transport.type === "smtp" && transport.port !== undefined && !WORKERS_PORTS.includes(transport.port))
252
+ throw new DiagnosticError("HAMUR_E6705", `mail.transport smtp on the ${preset} preset uses ports 465 or 587; Workers refuse port 25 (got ${transport.port})`);
253
+ if (transport.type === "outbox")
254
+ throw new DiagnosticError("HAMUR_E6706", `mail.transport outbox writes files, which the ${preset} preset has none of`);
255
+ }
256
+ if (transport.type === "outbox")
257
+ return diagnostic2("HAMUR_W6704", `mail.transport is outbox in a build: messages are written to ${transport.dir} and never sent`);
258
+ return;
259
+ }
260
+ function dkimWarning(dkim, transport) {
261
+ return dkim && transport?.type !== "smtp" ? diagnostic2("HAMUR_W6710", "mail.dkim is read by the smtp transport only") : undefined;
262
+ }
263
+ function language(hamur) {
264
+ const { i18n } = hamur.options;
265
+ return typeof i18n?.defaultLocale === "string" ? i18n.defaultLocale : "en";
266
+ }
267
+ function setupTemplates(hamur, srcDirs, scan) {
268
+ const { rootDir, buildDir } = hamur.options;
269
+ addTemplate({
270
+ filename: "mail/templates",
271
+ getContents: () => templatesModule(scan(), () => Bun.resolveSync(hamur.adapter.serverEntry, rootDir))
272
+ });
273
+ addTypeTemplate({
274
+ filename: "mail.d.ts",
275
+ getContents: () => templateTypes(scan(), join3(buildDir, "types"), hamur.adapter.name)
276
+ }, { context: ["app", "server"] });
277
+ hamur.hooks.hook("build:before", () => {
278
+ for (const warning of styleWarnings(rootDir, scan()))
279
+ useLogger("mail").warn(warning);
280
+ });
281
+ hamur.hooks.hook("dev:change", (change) => {
282
+ if (srcDirs.some((dir) => !relative2(join3(dir, "mail"), change.file).startsWith("..")))
283
+ change.rebuildServer = true;
284
+ });
285
+ }
286
+ function setupMail(options, hamur) {
287
+ const { dev, preset, rootDir, buildDir } = hamur.options;
288
+ const test = process.env.NODE_ENV === "test";
289
+ const testBuild = process.env.HAMUR_TEST_BUILD === "1";
290
+ const chosen = chooseTransport(options.transport, {
291
+ dev,
292
+ test,
293
+ setup: testBuild,
294
+ rootDir,
295
+ buildDir
296
+ });
297
+ const transport = chosen?.type === "smtp" && options.dkim ? { ...chosen, dkim: options.dkim } : chosen;
298
+ const protection = hamur.options.build.importProtection;
299
+ const client = protection.client ??= {};
300
+ (client.deny ??= []).push(SERVER);
301
+ const srcDirs = [hamur.options.srcDir, ...hamur.options.layers.map((layer) => layer.srcDir)];
302
+ const scan = () => scanTemplates(srcDirs, hamur.adapter.extensions);
303
+ const r = createResolver2(new URL("../../src/build/setup.ts", import.meta.url).href);
304
+ addServer(r.resolve(dev ? "../server/door-dev.ts" : "../server/door.ts"));
305
+ addTask({ name: "mail:send", file: r.resolve("../server/task.ts") });
306
+ addTemplate({
307
+ filename: "mail/deliver",
308
+ getContents: () => `export { deliverMail } from ${JSON.stringify(r.resolve("../server/deliver.ts"))};
309
+ `
310
+ });
311
+ const loaders = transport && BUILT.has(transport.type) ? ` ${JSON.stringify(transport.type)}: () => import(${JSON.stringify(r.resolve(`../transports/${transport.type}.ts`))}),
312
+ ` : "";
313
+ addTemplate({
314
+ filename: "mail/config",
315
+ getContents: () => [
316
+ `export const from = ${JSON.stringify(options.from)};`,
317
+ `export const replyTo = ${JSON.stringify(options.replyTo ?? null)};`,
318
+ `export const queue = ${options.queue};`,
319
+ `export const testBuild = ${testBuild};`,
320
+ `export const transport = ${JSON.stringify(transport ?? null)};`,
321
+ `export const reuse = ${dev || REUSES.has(preset)};`,
322
+ `export const dev = ${JSON.stringify(dev)};`,
323
+ `export const siteUrl = ${JSON.stringify(hamur.options.site.url ?? null)};`,
324
+ `export const baseURL = ${JSON.stringify(hamur.options.app.baseURL)};`,
325
+ `export const templates = ${JSON.stringify(scan().map(({ name }) => name))};`,
326
+ `export const lang = ${JSON.stringify(language(hamur))};`,
327
+ `export const transports = {
328
+ ${loaders}};`,
329
+ ""
330
+ ].join(`
331
+ `)
332
+ });
333
+ setupTemplates(hamur, srcDirs, scan);
334
+ setupMailDevtools(hamur, { transport, templates: () => scan().map(({ name }) => name) });
335
+ hamur.hooks.hook("build:before", async () => {
336
+ if (dev || test)
337
+ return;
338
+ const bindings = transport?.type === "cloudflare" ? await declaredSendEmailBindings(rootDir, hamur.options.cloudflare.env) : [];
339
+ const warning = checkBuild(transport, preset, hamur.options.site.url ?? (process.env.HAMUR_SITE_URL || undefined), bindings);
340
+ if (warning)
341
+ useLogger("mail").warn(warning);
342
+ const unsigned = dkimWarning(options.dkim, transport);
343
+ if (unsigned)
344
+ useLogger("mail").warn(unsigned);
345
+ });
346
+ }
347
+
348
+ // packages/mail/src/options.ts
349
+ import { DiagnosticError as DiagnosticError2, isEnvRef } from "hamur/kit";
350
+
351
+ // packages/mail/src/address.ts
352
+ var CONTROL = /[\x00-\x1f\x7f]/;
353
+ var LOCAL = /^[^\s@<>()[\],;:\\"\x00-\x1f\x7f]+$/;
354
+ var LABEL = /^(?!-)[a-z0-9-]{1,63}(?<!-)$/;
355
+ var MAX_LOCAL = 64;
356
+ var MAX_ADDRESS = 254;
357
+ var encoder = new TextEncoder;
358
+ function asciiDomain(domain) {
359
+ if (domain === "" || /[\s/\\?#@:%[\]]/.test(domain))
360
+ return;
361
+ let host;
362
+ try {
363
+ host = new URL(`http://${domain}`).hostname;
364
+ } catch {
365
+ return;
366
+ }
367
+ if (host.length > 253 || host.split(".").some((label) => !LABEL.test(label)))
368
+ return;
369
+ return host;
370
+ }
371
+ function parseBare(text) {
372
+ const at = text.lastIndexOf("@");
373
+ if (at <= 0)
374
+ return;
375
+ const local = text.slice(0, at);
376
+ if (!LOCAL.test(local) || local.startsWith(".") || local.endsWith(".") || local.includes(".."))
377
+ return;
378
+ const domain = asciiDomain(text.slice(at + 1));
379
+ if (domain === undefined)
380
+ return;
381
+ const address = `${local}@${domain}`;
382
+ return encoder.encode(local).length > MAX_LOCAL || encoder.encode(address).length > MAX_ADDRESS ? undefined : { address };
383
+ }
384
+ function parseAddress(value) {
385
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
386
+ const { name, address } = value;
387
+ if (typeof address !== "string" || name !== undefined && typeof name !== "string")
388
+ return;
389
+ if (name !== undefined && CONTROL.test(name))
390
+ return;
391
+ const parsed = parseBare(address);
392
+ if (!parsed)
393
+ return;
394
+ const trimmed = name?.trim();
395
+ return trimmed ? { name: trimmed, address: parsed.address } : parsed;
396
+ }
397
+ if (typeof value !== "string" || CONTROL.test(value))
398
+ return;
399
+ const text = value.trim();
400
+ const angle = /^(.*?)\s*<([^<>]*)>$/s.exec(text);
401
+ if (!angle)
402
+ return parseBare(text);
403
+ let name = angle[1].trim();
404
+ if (name.length >= 2 && name.startsWith('"') && name.endsWith('"'))
405
+ name = name.slice(1, -1).replace(/\\(.)/g, "$1");
406
+ else if (/[<>"]/.test(name))
407
+ return;
408
+ const parsed = parseBare(angle[2]);
409
+ if (!parsed)
410
+ return;
411
+ return name ? { name, address: parsed.address } : parsed;
412
+ }
413
+
414
+ // packages/mail/src/options.ts
415
+ var TRANSPORTS = ["smtp", "resend", "postmark", "sendgrid", "mailgun", "ses", "cloudflare", "outbox"];
416
+ var KEYS = ["from", "replyTo", "transport", "queue", "dkim"];
417
+ var DKIM_KEYS = ["domain", "selector", "privateKey"];
418
+ var SELECTOR_LABEL = /^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$/;
419
+ var TRANSPORT_KEYS = {
420
+ smtp: ["host", "port", "secure", "user", "password"],
421
+ resend: ["apiKey"],
422
+ postmark: ["serverToken", "messageStream"],
423
+ sendgrid: ["apiKey"],
424
+ mailgun: ["apiKey", "domain", "region"],
425
+ ses: ["region", "accessKeyId", "secretAccessKey"],
426
+ cloudflare: ["binding"],
427
+ outbox: ["dir"]
428
+ };
429
+ var SECRETS = ["password", "apiKey", "serverToken", "accessKeyId", "secretAccessKey"];
430
+ var REQUIRED = {
431
+ resend: ["apiKey"],
432
+ postmark: ["serverToken"],
433
+ sendgrid: ["apiKey"],
434
+ mailgun: ["apiKey", "domain"],
435
+ ses: ["region", "accessKeyId", "secretAccessKey"],
436
+ cloudflare: ["binding"]
437
+ };
438
+ var BINDING = /^[A-Za-z_][A-Za-z0-9_]*$/;
439
+ var LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
440
+ function fail(message) {
441
+ throw new DiagnosticError2("HAMUR_E6701", message);
442
+ }
443
+ function shown(value) {
444
+ if (Array.isArray(value))
445
+ return "an array";
446
+ if (typeof value === "function")
447
+ return "a function";
448
+ if (value === undefined)
449
+ return "undefined";
450
+ return JSON.stringify(value);
451
+ }
452
+ var isObject3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
453
+ function address(key, value) {
454
+ const parsed = parseAddress(value);
455
+ if (!parsed)
456
+ fail(`mail.${key} must be an address such as "Acme <hello@acme.dev>" (got ${shown(value)})`);
457
+ return parsed;
458
+ }
459
+ function resolveTransport(input) {
460
+ if (!isObject3(input))
461
+ fail(`mail.transport must be an object (got ${shown(input)})`);
462
+ const type = input.type;
463
+ if (typeof type !== "string" || !TRANSPORTS.includes(type))
464
+ fail(`mail.transport.type must be "smtp", "resend", "postmark", "sendgrid", "mailgun", "ses", "cloudflare" or "outbox" (got ${shown(type)})`);
465
+ const keys = TRANSPORT_KEYS[type];
466
+ for (const key of Object.keys(input)) {
467
+ if (key !== "type" && !keys.includes(key))
468
+ fail(`mail.transport has no ${JSON.stringify(key)} on the "${type}" transport (it takes: ${keys.join(", ")})`);
469
+ }
470
+ for (const key of SECRETS) {
471
+ if (input[key] !== undefined && !isEnvRef(input[key]))
472
+ fail(`mail.transport.${key} must be env("NAME"); a secret in the config file ends up in the repository`);
473
+ }
474
+ for (const key of REQUIRED[type] ?? []) {
475
+ if (input[key] === undefined)
476
+ fail(`mail.transport.${key} is required on the "${type}" transport`);
477
+ }
478
+ const text = (key) => {
479
+ const value = input[key];
480
+ if (value !== undefined && (typeof value !== "string" || value === ""))
481
+ fail(`mail.transport.${key} must be a non-empty string (got ${shown(value)})`);
482
+ };
483
+ if (type === "smtp") {
484
+ const { host, port, secure, user } = input;
485
+ if (typeof host !== "string" || host === "" || /[\s/]/.test(host))
486
+ fail(`mail.transport.host must be a host name (got ${shown(host)})`);
487
+ if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535))
488
+ fail(`mail.transport.port must be an integer from 1 to 65535 (got ${shown(port)})`);
489
+ if (secure !== undefined && secure !== "tls" && secure !== "starttls" && secure !== false)
490
+ fail(`mail.transport.secure must be "tls", "starttls" or false (got ${shown(secure)})`);
491
+ if (secure === false && !LOCAL_HOSTS.has(host.toLowerCase()))
492
+ fail(`mail.transport.secure false is allowed for localhost only (got ${shown(host)})`);
493
+ if (user !== undefined && !isEnvRef(user) && (typeof user !== "string" || user === ""))
494
+ fail(`mail.transport.user must be a string or env("NAME") (got ${shown(user)})`);
495
+ for (const [key, other] of [
496
+ ["password", "user"],
497
+ ["user", "password"]
498
+ ]) {
499
+ if (input[key] === undefined && input[other] !== undefined)
500
+ fail(`mail.transport.${key} is required with mail.transport.${other}`);
501
+ }
502
+ }
503
+ if (type === "postmark")
504
+ text("messageStream");
505
+ if (type === "mailgun") {
506
+ text("domain");
507
+ if (input.region !== undefined && input.region !== "us" && input.region !== "eu")
508
+ fail(`mail.transport.region must be "us" or "eu" (got ${shown(input.region)})`);
509
+ }
510
+ if (type === "ses") {
511
+ text("region");
512
+ if (!/^[a-z0-9-]+$/.test(input.region))
513
+ fail(`mail.transport.region must be an AWS region such as "eu-west-1" (got ${shown(input.region)})`);
514
+ }
515
+ if (type === "cloudflare" && (typeof input.binding !== "string" || !BINDING.test(input.binding)))
516
+ fail(`mail.transport.binding must be a binding name (got ${shown(input.binding)})`);
517
+ if (type === "outbox")
518
+ text("dir");
519
+ return { ...input };
520
+ }
521
+ function resolveDkim(input) {
522
+ if (!isObject3(input))
523
+ fail("mail.dkim must be an object with domain, selector and privateKey");
524
+ for (const key of Object.keys(input)) {
525
+ if (!DKIM_KEYS.includes(key))
526
+ fail(`mail.dkim has no ${JSON.stringify(key)} (it takes: ${DKIM_KEYS.join(", ")})`);
527
+ }
528
+ for (const key of DKIM_KEYS) {
529
+ if (input[key] === undefined)
530
+ fail(`mail.dkim.${key} is required`);
531
+ }
532
+ const { domain, selector, privateKey } = input;
533
+ if (!isEnvRef(privateKey))
534
+ fail('mail.dkim.privateKey must be env("NAME"); a secret in the config file ends up in the repository');
535
+ const host = typeof domain === "string" ? asciiDomain(domain) : undefined;
536
+ if (host === undefined)
537
+ fail('mail.dkim.domain must be a domain such as "acme.dev"');
538
+ if (typeof selector !== "string" || !selector.split(".").every((label) => SELECTOR_LABEL.test(label)))
539
+ fail('mail.dkim.selector must be a DNS name such as "mail"');
540
+ return { domain: host, selector, privateKey };
541
+ }
542
+ function resolveOptions(input = {}) {
543
+ if (!isObject3(input))
544
+ fail(`mail must be an object (got ${shown(input)})`);
545
+ for (const key of Object.keys(input)) {
546
+ if (!KEYS.includes(key))
547
+ fail(`mail has no ${JSON.stringify(key)} (it takes: ${KEYS.join(", ")})`);
548
+ }
549
+ const resolved = { from: address("from", input.from), queue: false };
550
+ if (input.replyTo !== undefined)
551
+ resolved.replyTo = address("replyTo", input.replyTo);
552
+ if (input.transport !== undefined)
553
+ resolved.transport = resolveTransport(input.transport);
554
+ if (input.queue !== undefined) {
555
+ if (typeof input.queue !== "boolean")
556
+ fail(`mail.queue must be a boolean (got ${shown(input.queue)})`);
557
+ resolved.queue = input.queue;
558
+ }
559
+ if (input.dkim !== undefined)
560
+ resolved.dkim = resolveDkim(input.dkim);
561
+ return resolved;
562
+ }
563
+
564
+ // packages/mail/src/module.ts
565
+ var module_default = defineModule({
566
+ meta: { name: "mail", configKey: "mail" },
567
+ setup(input, hamur) {
568
+ setupMail(resolveOptions(input), hamur);
569
+ }
570
+ });
571
+ export {
572
+ module_default as default
573
+ };