@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,916 @@
1
+ // @bun
2
+ // packages/mail/src/server/index.ts
3
+ import { queue, testBuild } from "#hamur/mail/config";
4
+ import { enqueue, useLogger as useLogger2 } from "hamur/server";
5
+
6
+ // packages/mail/src/server/message.ts
7
+ import { baseURL as baseURL2, from, lang, replyTo, templates } from "#hamur/mail/config";
8
+ import { renderComponent, templates as components } from "#hamur/mail/templates";
9
+ import { useEvent } from "hamur/server";
10
+
11
+ // packages/mail/src/server/runtime.ts
12
+ import { baseURL, dev, reuse, siteUrl, transport, transports } from "#hamur/mail/config";
13
+ import { useLogger, useSiteConfig, withSpan } from "hamur/server";
14
+
15
+ // packages/mail/src/server/hooks.ts
16
+ var current;
17
+ function serverHooks() {
18
+ return current;
19
+ }
20
+
21
+ // packages/mail/src/server/runtime.ts
22
+ var opened;
23
+ function open() {
24
+ return opened ??= (async () => {
25
+ if (!transport)
26
+ throw new Error("@hamur/mail has no mail.transport in this run");
27
+ const load = transports[transport.type];
28
+ if (!load)
29
+ throw new Error(`the ${transport.type} transport is not part of this version of @hamur/mail`);
30
+ return (await load()).default(transport, { reuse });
31
+ })().catch((error) => {
32
+ opened = undefined;
33
+ throw error;
34
+ });
35
+ }
36
+ function siteOrigin(event) {
37
+ try {
38
+ return useSiteConfig(event).url ?? siteUrl ?? undefined;
39
+ } catch {
40
+ return siteUrl ?? undefined;
41
+ }
42
+ }
43
+ var transmitDeps = {
44
+ transport: transport?.type ?? "none",
45
+ open,
46
+ hooks: serverHooks,
47
+ span: (name, fn, options) => withSpan(name, fn, options),
48
+ sent({ label, to, event }) {
49
+ if (!dev || transport?.type !== "outbox")
50
+ return;
51
+ const origin = event ? new URL(event.request.url).origin : siteOrigin(undefined) ?? "";
52
+ useLogger(event).child({ name: "mail" }).info(`${label} \u2192 ${to.map((address) => address.address).join(", ")} (open in devtools: ${origin}${baseURL}_hamur/devtools/#/mail)`);
53
+ }
54
+ };
55
+
56
+ // packages/mail/src/server/template.ts
57
+ import { createAppContext, createHead, createState } from "hamur/adapter";
58
+
59
+ // packages/mail/src/html.ts
60
+ var TAG_NAME = /<(\/?)([a-z][^\s/>]*)/iy;
61
+ var TAG_END = /[\s/]*>/y;
62
+ var ATTRIBUTE = /[\s/]*([^\s/>][^\s/>=]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>][^\s>]*)))?/y;
63
+ var RAW_TEXT = new Set(["script", "style", "textarea", "title"]);
64
+ function* htmlTokens(html) {
65
+ const token = (kind, start, end, name = "") => ({
66
+ kind,
67
+ name,
68
+ start,
69
+ end,
70
+ attributes: []
71
+ });
72
+ let text = 0;
73
+ let at = 0;
74
+ while ((at = html.indexOf("<", at)) !== -1) {
75
+ let found;
76
+ TAG_NAME.lastIndex = at;
77
+ const tag = TAG_NAME.exec(html);
78
+ if (tag) {
79
+ found = token(tag[1] ? "close" : "open", at, TAG_NAME.lastIndex, tag[2].toLowerCase());
80
+ for (;; ) {
81
+ TAG_END.lastIndex = found.end;
82
+ if (TAG_END.test(html)) {
83
+ found.end = TAG_END.lastIndex;
84
+ break;
85
+ }
86
+ ATTRIBUTE.lastIndex = found.end;
87
+ const match = ATTRIBUTE.exec(html);
88
+ if (!match) {
89
+ if (at > text)
90
+ yield token("text", text, at);
91
+ return;
92
+ }
93
+ const value = match[2] ?? match[3] ?? match[4] ?? "";
94
+ const end = ATTRIBUTE.lastIndex;
95
+ const valueEnd = match[2] === undefined && match[3] === undefined ? end : end - 1;
96
+ found.attributes.push({
97
+ name: match[1].toLowerCase(),
98
+ start: found.end,
99
+ end,
100
+ valueStart: valueEnd - value.length,
101
+ valueEnd
102
+ });
103
+ found.end = end;
104
+ }
105
+ } else if (/[!?/]/.test(html[at + 1] ?? "")) {
106
+ const comment = html.startsWith("<!--", at);
107
+ const close = comment ? html.indexOf("-->", at + 2) : html.indexOf(">", at);
108
+ found = token("comment", at, close === -1 ? html.length : close + (comment ? 3 : 1));
109
+ } else {
110
+ at++;
111
+ continue;
112
+ }
113
+ if (at > text)
114
+ yield token("text", text, at);
115
+ yield found;
116
+ text = at = found.end;
117
+ if (found.kind === "open" && RAW_TEXT.has(found.name)) {
118
+ const end = new RegExp(`</${found.name}(?=[\\s/>])`, "gi");
119
+ end.lastIndex = at;
120
+ at = end.exec(html)?.index ?? html.length;
121
+ }
122
+ }
123
+ if (html.length > text)
124
+ yield token("text", text, html.length);
125
+ }
126
+ var HYDRATION = new Set(["_hk", "data-hk", "jsaction", "ng-server-context", "ng-version", "ngh"]);
127
+ var CONDITIONAL = /^<!--(?:\[if\s|<!\[endif\])/i;
128
+ var PRELOAD = /^(?:module)?preload$/i;
129
+ function absoluteUrl(value, { origin, baseURL }) {
130
+ const path = value.trim();
131
+ if (!/^\/(?!\/)/.test(path))
132
+ return value;
133
+ const base = baseURL.replace(/\/+$/, "");
134
+ const below = path === base || ["/", "?", "#"].some((next) => path.startsWith(base + next));
135
+ return `${origin}${below ? "" : base}${path}`;
136
+ }
137
+ function mailHtml(html, site) {
138
+ let out = "";
139
+ let inScript = false;
140
+ for (const token of htmlTokens(html)) {
141
+ if (inScript || token.name === "script") {
142
+ inScript = token.name === "script" ? token.kind === "open" : true;
143
+ continue;
144
+ }
145
+ const source = html.slice(token.start, token.end);
146
+ if (token.kind === "comment" && source.startsWith("<!--") && !CONDITIONAL.test(source))
147
+ continue;
148
+ if (token.kind !== "open") {
149
+ out += source;
150
+ continue;
151
+ }
152
+ const valueOf = (attribute) => html.slice(attribute.valueStart, attribute.valueEnd);
153
+ if (token.name === "link" && token.attributes.some((item) => item.name === "rel" && PRELOAD.test(valueOf(item))))
154
+ continue;
155
+ let at = token.start;
156
+ for (const attribute of token.attributes) {
157
+ if (HYDRATION.has(attribute.name)) {
158
+ out += html.slice(at, attribute.start);
159
+ at = attribute.end;
160
+ } else if (attribute.name === "href" || attribute.name === "src") {
161
+ out += html.slice(at, attribute.valueStart) + absoluteUrl(valueOf(attribute), site);
162
+ at = attribute.valueEnd;
163
+ }
164
+ }
165
+ out += html.slice(at, token.end);
166
+ }
167
+ return out;
168
+ }
169
+ var LATIN_1 = "nbsp iexcl cent pound curren yen brvbar sect uml copy ordf laquo not shy reg macr deg plusmn sup2 sup3 acute micro para middot cedil sup1 ordm raquo frac14 frac12 frac34 iquest Agrave Aacute Acirc Atilde Auml Aring AElig Ccedil Egrave Eacute Ecirc Euml Igrave Iacute Icirc Iuml ETH Ntilde Ograve Oacute Ocirc Otilde Ouml times Oslash Ugrave Uacute Ucirc Uuml Yacute THORN szlig agrave aacute acirc atilde auml aring aelig ccedil egrave eacute ecirc euml igrave iacute icirc iuml eth ntilde ograve oacute ocirc otilde ouml divide oslash ugrave uacute ucirc uuml yacute thorn yuml";
170
+ var ENTITIES = new Map([
171
+ ...LATIN_1.split(" ").map((name, at) => [name, String.fromCharCode(160 + at)]),
172
+ ["amp", "&"],
173
+ ["lt", "<"],
174
+ ["gt", ">"],
175
+ ["quot", '"'],
176
+ ["apos", "'"],
177
+ ["hellip", "\u2026"],
178
+ ["mdash", "\u2014"],
179
+ ["ndash", "\u2013"],
180
+ ["lsquo", "\u2018"],
181
+ ["rsquo", "\u2019"],
182
+ ["sbquo", "\u201A"],
183
+ ["ldquo", "\u201C"],
184
+ ["rdquo", "\u201D"],
185
+ ["bdquo", "\u201E"],
186
+ ["lsaquo", "\u2039"],
187
+ ["rsaquo", "\u203A"],
188
+ ["bull", "\u2022"],
189
+ ["euro", "\u20AC"],
190
+ ["trade", "\u2122"],
191
+ ["larr", "\u2190"],
192
+ ["uarr", "\u2191"],
193
+ ["rarr", "\u2192"],
194
+ ["darr", "\u2193"],
195
+ ["ensp", "\u2002"],
196
+ ["emsp", "\u2003"],
197
+ ["thinsp", "\u2009"],
198
+ ["zwnj", "\u200C"],
199
+ ["zwj", "\u200D"]
200
+ ]);
201
+ var ENTITY = /&(?:#x([\da-f]+)|#(\d+)|([a-z][a-z\d]*));/gi;
202
+ function decode(text) {
203
+ return text.replace(ENTITY, (whole, hex, decimal, name) => {
204
+ if (name)
205
+ return ENTITIES.get(name) ?? whole;
206
+ const code = Number.parseInt(hex ?? decimal, hex ? 16 : 10);
207
+ return code > 0 && code <= 1114111 ? String.fromCodePoint(code) : "\uFFFD";
208
+ });
209
+ }
210
+ var BLOCKS = new Set("address article aside blockquote body center dd details div dl dt fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hr html li main nav ol p pre section summary table tbody tfoot thead tr ul".split(" "));
211
+ var DROPPED = new Set(["head", "script", "style"]);
212
+ function htmlToText(html) {
213
+ let out = "";
214
+ let last = "line";
215
+ let dropped;
216
+ let link;
217
+ const write = (source) => {
218
+ let text = source.replace(/[ \t\r\n\f]+/g, " ");
219
+ if (last !== "word" && text.startsWith(" "))
220
+ text = text.slice(1);
221
+ if (text === "")
222
+ return;
223
+ out += decode(text);
224
+ last = text.endsWith(" ") ? "space" : "word";
225
+ };
226
+ const endLine = () => {
227
+ if (last === "line")
228
+ return;
229
+ out += `
230
+ `;
231
+ last = "line";
232
+ };
233
+ const closeLink = () => {
234
+ if (!link)
235
+ return;
236
+ const { href, ...before } = link;
237
+ const inner = out;
238
+ const text = inner.trim();
239
+ link = undefined;
240
+ out = before.out;
241
+ if (text === "") {
242
+ last = before.last;
243
+ if (href) {
244
+ out += href;
245
+ last = "word";
246
+ }
247
+ return;
248
+ }
249
+ out += inner.trimEnd() + (!href || href === text ? "" : ` (${href})`);
250
+ const ended = last;
251
+ last = "word";
252
+ if (ended === "line")
253
+ endLine();
254
+ else if (ended === "space")
255
+ write(" ");
256
+ };
257
+ for (const token of htmlTokens(html)) {
258
+ const { kind, name } = token;
259
+ if (dropped) {
260
+ if (name === dropped ? kind === "close" : dropped === "head" && name === "body")
261
+ dropped = undefined;
262
+ continue;
263
+ }
264
+ const attribute = (wanted) => {
265
+ const found = token.attributes.find((item) => item.name === wanted);
266
+ return found && html.slice(found.valueStart, found.valueEnd);
267
+ };
268
+ if (kind === "text")
269
+ write(html.slice(token.start, token.end));
270
+ else if (kind === "open" && DROPPED.has(name))
271
+ dropped = name;
272
+ else if (name === "a") {
273
+ closeLink();
274
+ if (kind === "open") {
275
+ const href = attribute("href");
276
+ link = { href: href === undefined ? undefined : decode(href.trim()), out, last };
277
+ out = "";
278
+ }
279
+ } else if (kind === "open" && name === "img")
280
+ write(attribute("alt") ?? "");
281
+ else if (kind === "open" && name === "br") {
282
+ out += `
283
+ `;
284
+ last = "line";
285
+ } else if (kind === "close" && (name === "td" || name === "th"))
286
+ write(" ");
287
+ else if (BLOCKS.has(name) && !(kind === "open" && last === "bullet")) {
288
+ endLine();
289
+ if (kind === "open" && name === "li") {
290
+ out += "- ";
291
+ last = "bullet";
292
+ }
293
+ }
294
+ }
295
+ closeLink();
296
+ return out.split(`
297
+ `).map((line) => line.trimEnd()).join(`
298
+ `).replace(/\n{3,}/g, `
299
+
300
+ `).trim();
301
+ }
302
+
303
+ // packages/mail/src/server/template.ts
304
+ async function renderTemplate(renderComponent, component, props, site) {
305
+ const { baseURL } = site;
306
+ const route = {
307
+ name: "mail",
308
+ path: "/",
309
+ fullPath: "/",
310
+ params: {},
311
+ query: {},
312
+ search: {},
313
+ hash: "",
314
+ meta: {},
315
+ matched: []
316
+ };
317
+ const app = createAppContext({ state: createState(), config: { public: {} }, head: createHead({ baseURL }) });
318
+ const { html } = await renderComponent(component, props, {
319
+ app,
320
+ url: new URL(baseURL, site.origin),
321
+ route,
322
+ baseURL,
323
+ idPrefix: "mail"
324
+ });
325
+ return `<!doctype html><html lang="${site.lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"></head><body>${mailHtml(html, site)}</body></html>`;
326
+ }
327
+
328
+ // packages/mail/src/server/message.ts
329
+ function currentEvent() {
330
+ try {
331
+ return useEvent();
332
+ } catch {
333
+ return;
334
+ }
335
+ }
336
+ var messageDeps = (site) => ({
337
+ ...transmitDeps,
338
+ from,
339
+ ...replyTo ? { replyTo } : {},
340
+ templates,
341
+ async render(name, props, event) {
342
+ const { default: component } = await components[name]();
343
+ return renderTemplate(renderComponent, component, props, {
344
+ origin: site ?? siteOrigin(event) ?? "http://localhost",
345
+ baseURL: baseURL2,
346
+ lang
347
+ });
348
+ },
349
+ event: currentEvent,
350
+ host: (event) => {
351
+ const origin = site ?? siteOrigin(event);
352
+ return origin ? new URL(origin).hostname : "localhost";
353
+ }
354
+ });
355
+
356
+ // packages/mail/src/transports/http.ts
357
+ import { readSecret } from "hamur/server/internal";
358
+
359
+ // packages/mail/src/address.ts
360
+ var CONTROL = /[\x00-\x1f\x7f]/;
361
+ var LOCAL = /^[^\s@<>()[\],;:\\"\x00-\x1f\x7f]+$/;
362
+ var LABEL = /^(?!-)[a-z0-9-]{1,63}(?<!-)$/;
363
+ var ATOM = /^[A-Za-z0-9!#$%&'*+\-/=?^_`{|}~ ]+$/;
364
+ var ASCII = /^[\x00-\x7f]*$/;
365
+ var MAX_LOCAL = 64;
366
+ var MAX_ADDRESS = 254;
367
+ var encoder = new TextEncoder;
368
+ function asciiDomain(domain) {
369
+ if (domain === "" || /[\s/\\?#@:%[\]]/.test(domain))
370
+ return;
371
+ let host;
372
+ try {
373
+ host = new URL(`http://${domain}`).hostname;
374
+ } catch {
375
+ return;
376
+ }
377
+ if (host.length > 253 || host.split(".").some((label) => !LABEL.test(label)))
378
+ return;
379
+ return host;
380
+ }
381
+ function parseBare(text) {
382
+ const at = text.lastIndexOf("@");
383
+ if (at <= 0)
384
+ return;
385
+ const local = text.slice(0, at);
386
+ if (!LOCAL.test(local) || local.startsWith(".") || local.endsWith(".") || local.includes(".."))
387
+ return;
388
+ const domain = asciiDomain(text.slice(at + 1));
389
+ if (domain === undefined)
390
+ return;
391
+ const address = `${local}@${domain}`;
392
+ return encoder.encode(local).length > MAX_LOCAL || encoder.encode(address).length > MAX_ADDRESS ? undefined : { address };
393
+ }
394
+ function parseAddress(value) {
395
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
396
+ const { name, address } = value;
397
+ if (typeof address !== "string" || name !== undefined && typeof name !== "string")
398
+ return;
399
+ if (name !== undefined && CONTROL.test(name))
400
+ return;
401
+ const parsed = parseBare(address);
402
+ if (!parsed)
403
+ return;
404
+ const trimmed = name?.trim();
405
+ return trimmed ? { name: trimmed, address: parsed.address } : parsed;
406
+ }
407
+ if (typeof value !== "string" || CONTROL.test(value))
408
+ return;
409
+ const text = value.trim();
410
+ const angle = /^(.*?)\s*<([^<>]*)>$/s.exec(text);
411
+ if (!angle)
412
+ return parseBare(text);
413
+ let name = angle[1].trim();
414
+ if (name.length >= 2 && name.startsWith('"') && name.endsWith('"'))
415
+ name = name.slice(1, -1).replace(/\\(.)/g, "$1");
416
+ else if (/[<>"]/.test(name))
417
+ return;
418
+ const parsed = parseBare(angle[2]);
419
+ if (!parsed)
420
+ return;
421
+ return name ? { name, address: parsed.address } : parsed;
422
+ }
423
+ function addressList(value) {
424
+ if (value === undefined)
425
+ return [];
426
+ return Array.isArray(value) ? value : [value];
427
+ }
428
+ function quotedName(name) {
429
+ if (ATOM.test(name) && !name.startsWith(" ") && !name.endsWith(" ") && !name.includes(" "))
430
+ return name;
431
+ return `"${name.replace(/(["\\])/g, "\\$1")}"`;
432
+ }
433
+ function isAscii(text) {
434
+ return ASCII.test(text);
435
+ }
436
+
437
+ // packages/mail/src/transport.ts
438
+ class UnconfirmedError extends Error {
439
+ }
440
+
441
+ // packages/mail/src/smtp/client.ts
442
+ var encoder2 = new TextEncoder;
443
+
444
+ // packages/mail/src/transports/http.ts
445
+ var MAX_ERROR = 500;
446
+ var NEVER_SENT = new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN"]);
447
+ var CONTROLS = /[\x00-\x1f\x7f]+/g;
448
+ var encoder3 = new TextEncoder;
449
+ var escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
450
+ function shown(text, hidden) {
451
+ const values = hidden.filter(Boolean).sort((a, b) => b.length - a.length);
452
+ const clean = values.length ? text.replace(new RegExp(values.map(escape).join("|"), "gi"), "\u2026") : text;
453
+ return clean.replace(CONTROLS, " ").trim().slice(0, MAX_ERROR);
454
+ }
455
+
456
+ // packages/mail/src/server/send.ts
457
+ import { contentType as typeOfFile } from "hamur/server/http";
458
+
459
+ // packages/mail/src/mime.ts
460
+ var CRLF = `\r
461
+ `;
462
+ var FOLD_AT = 78;
463
+ var LINE_LIMIT = 998;
464
+ var WORD_BYTES = 45;
465
+ var ATTR_CHAR = /[A-Za-z0-9!#$&+\-.^_`|~]/;
466
+ var encoder4 = new TextEncoder;
467
+ function binary(bytes) {
468
+ let out = "";
469
+ for (let at = 0;at < bytes.length; at += 32768)
470
+ out += String.fromCharCode(...bytes.subarray(at, at + 32768));
471
+ return out;
472
+ }
473
+ function base64Lines(bytes) {
474
+ const text = btoa(binary(bytes));
475
+ const lines = [];
476
+ for (let at = 0;at < text.length; at += 76)
477
+ lines.push(text.slice(at, at + 76));
478
+ return lines.join(CRLF);
479
+ }
480
+ var hex = (byte) => `=${byte.toString(16).toUpperCase().padStart(2, "0")}`;
481
+ function quotedPrintable(text) {
482
+ const out = [];
483
+ for (const line of text.replace(/\r\n?/g, `
484
+ `).split(`
485
+ `)) {
486
+ const bytes = encoder4.encode(line);
487
+ const pieces = [];
488
+ bytes.forEach((byte, at) => {
489
+ const last = at === bytes.length - 1;
490
+ if ((byte === 32 || byte === 9) && !last)
491
+ pieces.push(String.fromCharCode(byte));
492
+ else if (byte >= 33 && byte <= 126 && byte !== 61)
493
+ pieces.push(String.fromCharCode(byte));
494
+ else
495
+ pieces.push(hex(byte));
496
+ });
497
+ let current = "";
498
+ pieces.forEach((piece, at) => {
499
+ const fitsLast = at === pieces.length - 1 && current.length + piece.length <= 76;
500
+ if (current.length + piece.length > 75 && !fitsLast) {
501
+ out.push(`${current}=`);
502
+ current = "";
503
+ }
504
+ current += piece;
505
+ });
506
+ out.push(current);
507
+ }
508
+ return out.join(CRLF);
509
+ }
510
+ function encodedWords(text) {
511
+ const words = [];
512
+ let chunk = [];
513
+ for (const char of text) {
514
+ const bytes = encoder4.encode(char);
515
+ if (chunk.length + bytes.length > WORD_BYTES) {
516
+ words.push(`=?UTF-8?B?${btoa(String.fromCharCode(...chunk))}?=`);
517
+ chunk = [];
518
+ }
519
+ chunk.push(...bytes);
520
+ }
521
+ if (chunk.length || !words.length)
522
+ words.push(`=?UTF-8?B?${btoa(String.fromCharCode(...chunk))}?=`);
523
+ return words;
524
+ }
525
+ function header(name, tokens) {
526
+ let out = `${name}:`;
527
+ let line = out.length;
528
+ tokens.forEach((token, at) => {
529
+ if (at > 0 && token !== "" && line + 1 + token.length > FOLD_AT) {
530
+ out += `${CRLF} ${token}`;
531
+ line = 1 + token.length;
532
+ return;
533
+ }
534
+ out += ` ${token}`;
535
+ line += 1 + token.length;
536
+ });
537
+ return out;
538
+ }
539
+ var fits = (text) => text.split(CRLF).every((line) => encoder4.encode(line).length <= LINE_LIMIT);
540
+ function textHeader(name, value) {
541
+ if (isAscii(value)) {
542
+ const plain = header(name, value.split(" "));
543
+ if (fits(plain))
544
+ return plain;
545
+ }
546
+ return header(name, encodedWords(value));
547
+ }
548
+ function nameTokens(name) {
549
+ const quoted = quotedName(name);
550
+ if (isAscii(name) && quoted.length <= LINE_LIMIT - 400)
551
+ return [quoted];
552
+ return encodedWords(name);
553
+ }
554
+ function addressTokens(addresses) {
555
+ return addresses.flatMap((address, at) => {
556
+ const comma = at < addresses.length - 1 ? "," : "";
557
+ return address.name ? [...nameTokens(address.name), `<${address.address}>${comma}`] : [`${address.address}${comma}`];
558
+ });
559
+ }
560
+ function mailDate(date) {
561
+ return date.toUTCString().replace(/GMT$/, "+0000");
562
+ }
563
+ function boundary() {
564
+ const bytes = crypto.getRandomValues(new Uint8Array(12));
565
+ return `=_hamur_${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
566
+ }
567
+ function textPart(subtype, body) {
568
+ return {
569
+ headers: [`Content-Type: text/${subtype}; charset=utf-8`, "Content-Transfer-Encoding: quoted-printable"],
570
+ body: quotedPrintable(body)
571
+ };
572
+ }
573
+ function filenameParams(filename) {
574
+ let encoded = "UTF-8''";
575
+ for (const byte of encoder4.encode(filename)) {
576
+ const char = String.fromCharCode(byte);
577
+ encoded += byte < 128 && ATTR_CHAR.test(char) ? char : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
578
+ }
579
+ if (encoded.length <= 60)
580
+ return [`filename*=${encoded}`];
581
+ const chunks = [];
582
+ let at = 0;
583
+ while (at < encoded.length) {
584
+ let end = Math.min(at + 60, encoded.length);
585
+ const percent = encoded.lastIndexOf("%", end - 1);
586
+ if (percent >= at && percent > end - 3 && end < encoded.length)
587
+ end = percent;
588
+ chunks.push(encoded.slice(at, end));
589
+ at = end;
590
+ }
591
+ return chunks.map((chunk, index) => `filename*${index}*=${chunk}`);
592
+ }
593
+ function attachmentPart(attachment) {
594
+ const disposition = attachment.cid === undefined ? "attachment" : "inline";
595
+ const params = filenameParams(attachment.filename);
596
+ const headers = [
597
+ `Content-Type: ${attachment.contentType}`,
598
+ "Content-Transfer-Encoding: base64",
599
+ `Content-Disposition: ${disposition};${params.map((param) => `${CRLF} ${param}`).join(";")}`
600
+ ];
601
+ if (attachment.cid !== undefined)
602
+ headers.push(`Content-ID: <${attachment.cid}>`);
603
+ return { headers, body: base64Lines(attachment.content) };
604
+ }
605
+ function multipart(subtype, parts) {
606
+ const mark = boundary();
607
+ const body = parts.map((part) => `--${mark}${CRLF}${part.headers.join(CRLF)}${CRLF}${CRLF}${part.body}${CRLF}`).join("");
608
+ return { headers: [`Content-Type: multipart/${subtype};${CRLF} boundary="${mark}"`], body: `${body}--${mark}--` };
609
+ }
610
+ function writeMime(input) {
611
+ const bodies = [];
612
+ if (input.text !== undefined)
613
+ bodies.push(textPart("plain", input.text));
614
+ if (input.html !== undefined)
615
+ bodies.push(textPart("html", input.html));
616
+ let root = bodies.length === 1 ? bodies[0] : multipart("alternative", bodies);
617
+ const attachments = input.attachments ?? [];
618
+ const inline = attachments.filter((attachment) => attachment.cid !== undefined);
619
+ const attached = attachments.filter((attachment) => attachment.cid === undefined);
620
+ if (inline.length)
621
+ root = multipart("related", [root, ...inline.map(attachmentPart)]);
622
+ if (attached.length)
623
+ root = multipart("mixed", [root, ...attached.map(attachmentPart)]);
624
+ const lines = [header("From", addressTokens([input.from]))];
625
+ if (input.replyTo)
626
+ lines.push(header("Reply-To", addressTokens([input.replyTo])));
627
+ if (input.to.length)
628
+ lines.push(header("To", addressTokens(input.to)));
629
+ if (input.cc?.length)
630
+ lines.push(header("Cc", addressTokens(input.cc)));
631
+ lines.push(textHeader("Subject", input.subject), `Date: ${mailDate(input.date)}`, `Message-ID: <${input.messageId}>`, "MIME-Version: 1.0");
632
+ for (const [name, value] of Object.entries(input.headers ?? {}))
633
+ lines.push(textHeader(name, value));
634
+ lines.push(...root.headers);
635
+ return `${lines.join(CRLF)}${CRLF}${CRLF}${root.body}${CRLF}`;
636
+ }
637
+
638
+ // packages/mail/src/server/send.ts
639
+ var OWN_HEADERS = {
640
+ from: "from",
641
+ to: "to",
642
+ cc: "cc",
643
+ bcc: "bcc",
644
+ subject: "subject",
645
+ "reply-to": "replyTo",
646
+ date: undefined,
647
+ "message-id": undefined,
648
+ "mime-version": undefined,
649
+ "content-type": undefined,
650
+ "content-transfer-encoding": undefined
651
+ };
652
+ var HEADER_NAME = /^[!-9;-~]{1,76}$/;
653
+ var CONTROL2 = /[\x00-\x08\x0a-\x1f\x7f]/;
654
+ var MAX_PART_VALUE = 900;
655
+ var TOKEN = "[!#$%&'*+.^_`|~0-9A-Za-z-]+";
656
+ var CONTENT_TYPE = new RegExp(`^${TOKEN}/${TOKEN}(?:\\s*;\\s*${TOKEN}=(?:${TOKEN}|"[^"\\\\\\x00-\\x1f\\x7f]*"))*$`);
657
+ var CONTENT_ID = /^[!#-;=?-~]+$/;
658
+ var encoder5 = new TextEncoder;
659
+ var isContentType = (value) => value.length <= MAX_PART_VALUE && CONTENT_TYPE.test(value);
660
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
661
+ function shown2(value) {
662
+ if (value === undefined)
663
+ return "undefined";
664
+ if (typeof value === "function")
665
+ return "a function";
666
+ return JSON.stringify(value);
667
+ }
668
+ function addresses(field, value) {
669
+ return addressList(value).map((item, at) => {
670
+ const parsed = parseAddress(item);
671
+ if (!parsed)
672
+ throw new TypeError(`sendMail ${field}[${at}] ${shown2(item)} is not an address`);
673
+ return parsed;
674
+ });
675
+ }
676
+ function single(field, value) {
677
+ if (value === undefined)
678
+ return;
679
+ const parsed = parseAddress(value);
680
+ if (!parsed)
681
+ throw new TypeError(`sendMail ${field} ${shown2(value)} is not an address`);
682
+ return parsed;
683
+ }
684
+ function checkHeaders(headers) {
685
+ if (headers === undefined)
686
+ return {};
687
+ if (!isObject(headers))
688
+ throw new TypeError(`sendMail headers must be an object (got ${shown2(headers)})`);
689
+ const checked = {};
690
+ for (const [name, value] of Object.entries(headers)) {
691
+ if (!HEADER_NAME.test(name))
692
+ throw new TypeError(`sendMail headers[${JSON.stringify(name)}] is not a header name`);
693
+ const lower = name.toLowerCase();
694
+ if (Object.hasOwn(OWN_HEADERS, lower)) {
695
+ const option = OWN_HEADERS[lower];
696
+ throw new TypeError(`sendMail headers cannot set ${JSON.stringify(lower)}; ${option ? `use the ${option} option` : "Hamur writes it"}`);
697
+ }
698
+ if (typeof value !== "string")
699
+ throw new TypeError(`sendMail headers[${JSON.stringify(name)}] must be a string (got ${shown2(value)})`);
700
+ if (CONTROL2.test(value))
701
+ throw new TypeError(`sendMail headers[${JSON.stringify(name)}] holds a line break`);
702
+ checked[name] = value;
703
+ }
704
+ return checked;
705
+ }
706
+ function checkAttachments(value) {
707
+ if (value === undefined)
708
+ return [];
709
+ if (!Array.isArray(value))
710
+ throw new TypeError(`sendMail attachments must be an array (got ${shown2(value)})`);
711
+ return value.map((attachment, at) => {
712
+ const label = `sendMail attachments[${at}]`;
713
+ if (!isObject(attachment))
714
+ throw new TypeError(`${label} must be an object (got ${shown2(attachment)})`);
715
+ const { filename, content, contentType, cid } = attachment;
716
+ if (typeof filename !== "string" || filename === "")
717
+ throw new TypeError(`${label}.filename must be a non-empty string (got ${shown2(filename)})`);
718
+ if (!(typeof content === "string" || content instanceof Uint8Array || content instanceof Blob))
719
+ throw new TypeError(`${label}.content must be a Uint8Array, Blob or string`);
720
+ if (contentType !== undefined && (typeof contentType !== "string" || !isContentType(contentType)))
721
+ throw new TypeError(`${label}.contentType ${shown2(contentType)} is not a content type`);
722
+ if (cid !== undefined && (typeof cid !== "string" || cid.length > MAX_PART_VALUE || !CONTENT_ID.test(cid)))
723
+ throw new TypeError(`${label}.cid ${shown2(cid)} is not a content id`);
724
+ return attachment;
725
+ });
726
+ }
727
+ function checkMessage(message) {
728
+ const to = addresses("to", message.to);
729
+ const cc = addresses("cc", message.cc);
730
+ const bcc = addresses("bcc", message.bcc);
731
+ if (!to.length && !cc.length && !bcc.length)
732
+ throw new TypeError("sendMail needs to (got no address)");
733
+ const from = single("from", message.from);
734
+ const replyTo = single("replyTo", message.replyTo);
735
+ const { subject } = message;
736
+ if (typeof subject !== "string")
737
+ throw new TypeError(`sendMail subject must be a string (got ${shown2(subject)})`);
738
+ if (CONTROL2.test(subject))
739
+ throw new TypeError("sendMail subject holds a line break");
740
+ for (const key of ["html", "text"]) {
741
+ if (message[key] !== undefined && typeof message[key] !== "string")
742
+ throw new TypeError(`sendMail ${key} must be a string (got ${shown2(message[key])})`);
743
+ }
744
+ const tags = message.tags ?? [];
745
+ if (!Array.isArray(tags) || tags.some((tag) => typeof tag !== "string"))
746
+ throw new TypeError(`sendMail tags must be an array of strings (got ${shown2(tags)})`);
747
+ return {
748
+ to,
749
+ cc,
750
+ bcc,
751
+ from,
752
+ replyTo,
753
+ subject,
754
+ headers: checkHeaders(message.headers),
755
+ attachments: checkAttachments(message.attachments),
756
+ tags
757
+ };
758
+ }
759
+ async function bytesOf(content) {
760
+ if (typeof content === "string")
761
+ return encoder5.encode(content);
762
+ if (content instanceof Blob)
763
+ return new Uint8Array(await content.arrayBuffer());
764
+ return content;
765
+ }
766
+ function providerText(error) {
767
+ return error instanceof Error ? error.message : String(error);
768
+ }
769
+ function outgoingMail(id, date, message) {
770
+ const { from, to, cc, bcc } = message;
771
+ return {
772
+ id,
773
+ date,
774
+ raw: writeMime({ ...message, date, messageId: id }),
775
+ envelope: { from: from.address, to: [...new Set([...to, ...cc, ...bcc].map((address) => address.address))] },
776
+ message
777
+ };
778
+ }
779
+ async function transmit(deps, mail) {
780
+ const { template } = mail.message;
781
+ await deps.span("mail.send", async () => {
782
+ try {
783
+ const sender = await deps.open();
784
+ await sender.send(mail);
785
+ } catch (cause) {
786
+ throw new Error(`Mail ${template === undefined ? "html" : JSON.stringify(template)} failed on ${deps.transport}`, { cause });
787
+ }
788
+ }, {
789
+ kind: "client",
790
+ attributes: {
791
+ "mail.transport": deps.transport,
792
+ ...template === undefined ? {} : { "mail.template": template }
793
+ }
794
+ });
795
+ }
796
+ function mailFailure(recorded) {
797
+ const { message, cause } = recorded;
798
+ return new Error(`${message}: ${providerText(cause)}`, { cause });
799
+ }
800
+ function createSendMail(deps) {
801
+ return async function sendMail(message, options = {}) {
802
+ const queued = options.queue ?? deps.queue;
803
+ if (!queued && options.delay !== undefined)
804
+ throw new TypeError("sendMail delay needs queue: true");
805
+ const input = isObject(message) ? message : {};
806
+ const hasTemplate = input.template !== undefined;
807
+ if (!hasTemplate && input.html === undefined)
808
+ throw new TypeError("sendMail needs template or html (got neither)");
809
+ if (hasTemplate && input.html !== undefined)
810
+ throw new TypeError("sendMail takes template or html, not both");
811
+ checkMessage(input);
812
+ if (hasTemplate && !deps.templates.includes(input.template))
813
+ throw new TypeError(`No mail template ${JSON.stringify(input.template)} (templates: ${[...deps.templates].sort().join(", ")})`);
814
+ const event = deps.event();
815
+ const ready = {
816
+ ...message,
817
+ ...hasTemplate ? { html: await deps.render(input.template, isObject(input.props) ? input.props : {}, event) } : {},
818
+ to: addressList(message.to),
819
+ cc: addressList(message.cc),
820
+ bcc: addressList(message.bcc),
821
+ from: message.from ?? deps.from,
822
+ ...message.replyTo === undefined && deps.replyTo ? { replyTo: deps.replyTo } : {},
823
+ headers: { ...message.headers },
824
+ attachments: [...message.attachments ?? []]
825
+ };
826
+ const hooks = deps.hooks();
827
+ await hooks?.callHook("mail:beforeSend", ready, { event });
828
+ const checked = checkMessage(ready);
829
+ if (typeof ready.html !== "string")
830
+ throw new TypeError(`sendMail html must be a string (got ${shown2(ready.html)})`);
831
+ const attachments = await Promise.all(checked.attachments.map(async (attachment) => ({
832
+ filename: attachment.filename,
833
+ content: await bytesOf(attachment.content),
834
+ contentType: attachment.contentType || (attachment.content instanceof Blob && isContentType(attachment.content.type) ? attachment.content.type : typeOfFile(attachment.filename)),
835
+ ...attachment.cid === undefined ? {} : { cid: attachment.cid }
836
+ })));
837
+ const template = hasTemplate ? input.template : undefined;
838
+ const text = ready.text ?? (htmlToText(ready.html) || undefined);
839
+ const mail = {
840
+ from: checked.from ?? deps.from,
841
+ to: checked.to,
842
+ cc: checked.cc,
843
+ bcc: checked.bcc,
844
+ ...checked.replyTo ? { replyTo: checked.replyTo } : {},
845
+ subject: checked.subject,
846
+ ...template === undefined ? {} : { template },
847
+ html: ready.html,
848
+ ...text === undefined ? {} : { text },
849
+ attachments,
850
+ headers: checked.headers,
851
+ tags: checked.tags
852
+ };
853
+ const id = `${deps.id ?? crypto.randomUUID()}@${deps.host(event)}`;
854
+ const outgoing = outgoingMail(id, new Date, mail);
855
+ if (queued) {
856
+ await deps.enqueue(outgoing, options.delay);
857
+ return { id, queued: true };
858
+ }
859
+ try {
860
+ await transmit(deps, outgoing);
861
+ } catch (recorded) {
862
+ const failure = mailFailure(recorded);
863
+ await hooks?.callHook("mail:error", failure, ready);
864
+ throw failure;
865
+ }
866
+ const result = { id, queued: false };
867
+ await hooks?.callHook("mail:sent", result, ready);
868
+ deps.sent?.({ label: template ?? "html", to: mail.to, event });
869
+ return result;
870
+ };
871
+ }
872
+
873
+ // packages/mail/src/server/queue.ts
874
+ function packMail({ id, date, message }) {
875
+ return { id, date, message };
876
+ }
877
+ function withoutAddresses(failure, { from, to, cc, bcc, replyTo }) {
878
+ const addresses = [from, ...to, ...cc, ...bcc, ...replyTo ? [replyTo] : []].map(({ address }) => address);
879
+ return new Error(shown(failure.message, addresses));
880
+ }
881
+ async function sendOnce(deps, mail, log, queued) {
882
+ const message = mail.message;
883
+ const hooks = deps.hooks();
884
+ try {
885
+ await transmit(deps, mail);
886
+ } catch (recorded) {
887
+ const failure = mailFailure(recorded);
888
+ await hooks?.callHook("mail:error", failure, message).catch((error) => log.error(error));
889
+ const reported = withoutAddresses(failure, mail.message);
890
+ if (!(failure.cause instanceof UnconfirmedError))
891
+ throw reported;
892
+ return reported;
893
+ }
894
+ await hooks?.callHook("mail:sent", { id: mail.id, queued }, message).catch((error) => log.error(error));
895
+ deps.sent?.({ label: mail.message.template ?? "html", to: mail.message.to, event: undefined });
896
+ return;
897
+ }
898
+ async function sendQueued(deps, mail, log) {
899
+ const unconfirmed = await sendOnce(deps, mail, log, true);
900
+ if (unconfirmed)
901
+ log.error(unconfirmed, `${unconfirmed.message}; the queue does not send it again`);
902
+ }
903
+
904
+ // packages/mail/src/server/index.ts
905
+ var TASK = "mail:send";
906
+ var send = createSendMail({
907
+ ...messageDeps(),
908
+ queue,
909
+ enqueue: (mail, delay) => testBuild ? sendQueued(transmitDeps, mail, useLogger2()) : enqueue(TASK, packMail(mail), delay === undefined ? {} : { delay })
910
+ });
911
+ function sendMail(message, options) {
912
+ return send(message, options);
913
+ }
914
+ export {
915
+ sendMail
916
+ };