@frigear-nu/notify 0.2.7 → 0.3.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.
- package/dist/module.d.mts +40 -4
- package/dist/module.json +1 -1
- package/dist/module.mjs +3 -2
- package/dist/runtime/drivers/email/cloudflare-binding.d.ts +20 -0
- package/dist/runtime/drivers/email/cloudflare-binding.js +34 -0
- package/dist/runtime/drivers/email/cloudflare.d.ts +5 -0
- package/dist/runtime/drivers/email/cloudflare.js +9 -3
- package/dist/runtime/drivers/email/index.d.ts +10 -2
- package/dist/runtime/drivers/email/index.js +12 -4
- package/dist/runtime/drivers/email/mime.d.ts +40 -0
- package/dist/runtime/drivers/email/mime.js +91 -0
- package/dist/runtime/drivers/email/resend.js +4 -3
- package/dist/runtime/drivers/email/ses.js +6 -3
- package/dist/runtime/drivers/email/shared.d.ts +12 -1
- package/dist/runtime/drivers/email/shared.js +8 -1
- package/dist/runtime/server/utils/dispatch.d.ts +5 -3
- package/dist/runtime/server/utils/dispatch.js +8 -2
- package/dist/runtime/server/utils/notify-user.js +2 -1
- package/dist/types.d.mts +1 -1
- package/package.json +4 -3
package/dist/module.d.mts
CHANGED
|
@@ -68,6 +68,12 @@ interface EmailNotification<M = NotificationMeta> {
|
|
|
68
68
|
body: string;
|
|
69
69
|
/** Optional plain-text body. */
|
|
70
70
|
text?: string;
|
|
71
|
+
/**
|
|
72
|
+
* The sender of this email (`a@x.test` or `"Name" <a@x.test>`), instead of the configured `from`
|
|
73
|
+
* (`NUXT_NOTIFY_EMAIL_FROM`). Optional and additive: every built-in driver (`resend`, `ses`, `cloudflare`, `log`) uses
|
|
74
|
+
* it. The address's domain must be verified with the provider, which refuses the send otherwise.
|
|
75
|
+
*/
|
|
76
|
+
from?: string;
|
|
71
77
|
/** Address replies should go to (the `Reply-To` header). */
|
|
72
78
|
replyTo?: string;
|
|
73
79
|
/**
|
|
@@ -75,6 +81,13 @@ interface EmailNotification<M = NotificationMeta> {
|
|
|
75
81
|
* on. A custom driver whose transport has no cc may ignore them, and should say so where it is documented.
|
|
76
82
|
*/
|
|
77
83
|
cc?: string | string[];
|
|
84
|
+
/**
|
|
85
|
+
* Extra headers, such as `List-Unsubscribe` and `List-Unsubscribe-Post` (RFC 8058). The built-in `resend`, `ses` and
|
|
86
|
+
* `cloudflare` drivers pass them on, and `log` logs them. Headers the provider sets itself (`From`, `To`, `Subject`,
|
|
87
|
+
* `Message-ID`, `Date`) cannot be set; Cloudflare accepts only its allowlisted headers and `X-` headers and rejects the
|
|
88
|
+
* whole send otherwise. A custom driver whose transport has no headers may ignore them.
|
|
89
|
+
*/
|
|
90
|
+
headers?: Record<string, string>;
|
|
78
91
|
/**
|
|
79
92
|
* Template to render this email from instead of `subject`/`body`/`text`, when a renderer is
|
|
80
93
|
* installed (`@frigear-nu/email-templates` listens on the `notify:email` hook). Without one,
|
|
@@ -116,7 +129,25 @@ type NotifyEmailContext = {
|
|
|
116
129
|
*/
|
|
117
130
|
type SimpleDriver = (notification: SimpleNotification) => Promise<void> | void;
|
|
118
131
|
type SMSDriver = (notification: SMSNotification) => Promise<void> | void;
|
|
119
|
-
|
|
132
|
+
/**
|
|
133
|
+
* What an email driver may report about a sent email. Optional: a driver that reports nothing returns `void`.
|
|
134
|
+
*/
|
|
135
|
+
type EmailSendResult = {
|
|
136
|
+
/**
|
|
137
|
+
* The `Message-ID` header the email went out with, without angle brackets, when the driver set it itself (the
|
|
138
|
+
* `cloudflare-binding` driver does). Only the RFC 5322 Message-ID belongs here, never a provider's own id.
|
|
139
|
+
*/
|
|
140
|
+
messageId?: string;
|
|
141
|
+
};
|
|
142
|
+
/** Options of one `dispatchEmailNotification` call. */
|
|
143
|
+
type NotifyEmailDispatchOptions = {
|
|
144
|
+
/**
|
|
145
|
+
* Send this email through this built-in driver instead of the configured one (`NUXT_NOTIFY_EMAIL_DRIVER`), with the
|
|
146
|
+
* same `NUXT_NOTIFY_EMAIL_*` settings (`from`, credentials, binding name).
|
|
147
|
+
*/
|
|
148
|
+
driver?: 'log' | 'resend' | 'ses' | 'cloudflare' | 'cloudflare-binding';
|
|
149
|
+
};
|
|
150
|
+
type EmailDriver = (notification: EmailNotification) => Promise<EmailSendResult | void> | EmailSendResult | void;
|
|
120
151
|
type PushDriver = (notification: PushNotification) => Promise<PushDispatchResult | void> | PushDispatchResult | void;
|
|
121
152
|
/** The channels `notifyUser` can reach a user on. */
|
|
122
153
|
type NotificationChannel = 'email' | 'sms' | 'push';
|
|
@@ -205,6 +236,7 @@ type NotifyUserInput = {
|
|
|
205
236
|
body: string;
|
|
206
237
|
text?: string;
|
|
207
238
|
replyTo?: string;
|
|
239
|
+
headers?: Record<string, string>;
|
|
208
240
|
template?: EmailTemplateRef;
|
|
209
241
|
meta?: Record<string, unknown>;
|
|
210
242
|
};
|
|
@@ -228,7 +260,7 @@ type NotifyUserResult = {
|
|
|
228
260
|
};
|
|
229
261
|
type ModuleOptions = {
|
|
230
262
|
email?: {
|
|
231
|
-
driver?: 'log' | 'resend' | 'ses' | 'cloudflare' | (string & {});
|
|
263
|
+
driver?: 'log' | 'resend' | 'ses' | 'cloudflare' | 'cloudflare-binding' | (string & {});
|
|
232
264
|
};
|
|
233
265
|
sms?: {
|
|
234
266
|
driver?: string | 'log';
|
|
@@ -243,7 +275,7 @@ type ModuleOptions = {
|
|
|
243
275
|
/** Private runtime config (`runtimeConfig.notify`), overridable through `NUXT_NOTIFY_*` env vars. */
|
|
244
276
|
type NotifyRuntimeConfig = {
|
|
245
277
|
email: {
|
|
246
|
-
/** `NUXT_NOTIFY_EMAIL_DRIVER`: `log` (default), `resend`, `ses` or `cloudflare`. */
|
|
278
|
+
/** `NUXT_NOTIFY_EMAIL_DRIVER`: `log` (default), `resend`, `ses`, `cloudflare` or `cloudflare-binding`. */
|
|
247
279
|
driver: string;
|
|
248
280
|
/** `NUXT_NOTIFY_EMAIL_FROM`: sender address, e.g. `Frigear <no-reply@frigear.nu>`. */
|
|
249
281
|
from: string;
|
|
@@ -263,6 +295,10 @@ type NotifyRuntimeConfig = {
|
|
|
263
295
|
accountId: string;
|
|
264
296
|
apiToken: string;
|
|
265
297
|
};
|
|
298
|
+
/** `NUXT_NOTIFY_EMAIL_BINDING_NAME`: the Workers `send_email` binding of `cloudflare-binding` (`SEND_EMAIL`). */
|
|
299
|
+
binding: {
|
|
300
|
+
name: string;
|
|
301
|
+
};
|
|
266
302
|
};
|
|
267
303
|
};
|
|
268
304
|
|
|
@@ -284,4 +320,4 @@ declare module '@nuxt/schema' {
|
|
|
284
320
|
declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
|
|
285
321
|
|
|
286
322
|
export { _default as default };
|
|
287
|
-
export type { ChannelSettings, EmailDriver, EmailNotification, EmailTemplateRef, EmailTemplateSource, ModuleOptions, NotificationChannel, NotificationChannelsDto, NotificationChannelsRow, NotificationChoices, NotificationTopic, NotificationTopicDto, NotifyChoicesStore, NotifyEmailContext, NotifyRecipient, NotifyRecipientStore, NotifyUserInput, NotifyUserResult, PushDispatchResult, PushDriver, PushNotification, PushText, SMSDriver, SMSNotification, SimpleDriver, SimpleNotification, Translated };
|
|
323
|
+
export type { ChannelSettings, EmailDriver, EmailNotification, EmailSendResult, EmailTemplateRef, EmailTemplateSource, ModuleOptions, NotificationChannel, NotificationChannelsDto, NotificationChannelsRow, NotificationChoices, NotificationTopic, NotificationTopicDto, NotifyChoicesStore, NotifyEmailContext, NotifyEmailDispatchOptions, NotifyRecipient, NotifyRecipientStore, NotifyUserInput, NotifyUserResult, PushDispatchResult, PushDriver, PushNotification, PushText, SMSDriver, SMSNotification, SimpleDriver, SimpleNotification, Translated };
|
package/dist/module.json
CHANGED
package/dist/module.mjs
CHANGED
|
@@ -7,7 +7,7 @@ import { joinURL } from 'ufo';
|
|
|
7
7
|
const BUILTIN_SERVER_DRIVERS = {
|
|
8
8
|
log: { path: "./runtime/drivers/log", exportName: "logDriver" }
|
|
9
9
|
};
|
|
10
|
-
const BUILTIN_EMAIL_DRIVERS = ["log", "resend", "ses", "cloudflare"];
|
|
10
|
+
const BUILTIN_EMAIL_DRIVERS = ["log", "resend", "ses", "cloudflare", "cloudflare-binding"];
|
|
11
11
|
const AUTO_EMAIL_DRIVER = { path: "./runtime/drivers/email/index", exportName: "default" };
|
|
12
12
|
const module$1 = defineNuxtModule({
|
|
13
13
|
meta: { name: "@frigear-nu/notify", configKey: "notify" },
|
|
@@ -53,7 +53,8 @@ const module$1 = defineNuxtModule({
|
|
|
53
53
|
from: "",
|
|
54
54
|
resend: { apiToken: "" },
|
|
55
55
|
ses: { region: "", accessKeyId: "", secretAccessKey: "", sessionToken: "" },
|
|
56
|
-
cloudflare: { accountId: "", apiToken: "" }
|
|
56
|
+
cloudflare: { accountId: "", apiToken: "" },
|
|
57
|
+
binding: { name: "SEND_EMAIL" }
|
|
57
58
|
}
|
|
58
59
|
});
|
|
59
60
|
registerServerDriver("email-driver", "EmailDriver", emailBuiltin ? "auto" : emailDriver, { auto: AUTO_EMAIL_DRIVER });
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { EmailDriver } from '../../../types.js';
|
|
2
|
+
import { type EmailConfig } from './shared.js';
|
|
3
|
+
export interface CloudflareBindingConfig extends EmailConfig {
|
|
4
|
+
/** The name of the `send_email` binding (`NUXT_NOTIFY_EMAIL_BINDING_NAME`). Defaults to `SEND_EMAIL`. */
|
|
5
|
+
name?: string;
|
|
6
|
+
}
|
|
7
|
+
/** The `send_email` binding, as far as the driver uses it. */
|
|
8
|
+
export type SendEmailBinding = {
|
|
9
|
+
send: (message: unknown) => Promise<unknown>;
|
|
10
|
+
};
|
|
11
|
+
/** `EmailMessage` of `cloudflare:email`. */
|
|
12
|
+
export type EmailMessageConstructor = new (from: string, to: string, raw: string) => unknown;
|
|
13
|
+
export type CloudflareBindingDeps = {
|
|
14
|
+
/** The Worker's bindings; defaults to the ones Nitro's Cloudflare presets keep on `globalThis.__env__`. */
|
|
15
|
+
env?: Record<string, unknown>;
|
|
16
|
+
/** Defaults to `EmailMessage` of `cloudflare:email`. */
|
|
17
|
+
EmailMessage?: EmailMessageConstructor;
|
|
18
|
+
};
|
|
19
|
+
export declare const DEFAULT_BINDING_NAME = "SEND_EMAIL";
|
|
20
|
+
export declare const createCloudflareBindingDriver: (config: CloudflareBindingConfig, deps?: CloudflareBindingDeps) => EmailDriver;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { resolveFrom, toArray } from "./shared.js";
|
|
2
|
+
import { buildMimeMessage, generateMessageId, splitAddress } from "./mime.js";
|
|
3
|
+
export const DEFAULT_BINDING_NAME = "SEND_EMAIL";
|
|
4
|
+
async function loadEmailMessage() {
|
|
5
|
+
const specifier = "cloudflare:email";
|
|
6
|
+
try {
|
|
7
|
+
const module = await import(
|
|
8
|
+
/* @vite-ignore */
|
|
9
|
+
specifier
|
|
10
|
+
);
|
|
11
|
+
return module.EmailMessage;
|
|
12
|
+
} catch {
|
|
13
|
+
throw new Error("[notify] The cloudflare-binding email driver only runs on Cloudflare Workers (cloudflare:email is missing).");
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export const createCloudflareBindingDriver = (config, deps = {}) => async (n) => {
|
|
17
|
+
const name = config.name || DEFAULT_BINDING_NAME;
|
|
18
|
+
const env = deps.env ?? globalThis.__env__;
|
|
19
|
+
const binding = env?.[name];
|
|
20
|
+
if (!binding || typeof binding.send !== "function") {
|
|
21
|
+
throw new Error(`[notify] Missing the send_email binding "${name}": add it to the Worker (wrangler send_email) or set NUXT_NOTIFY_EMAIL_BINDING_NAME`);
|
|
22
|
+
}
|
|
23
|
+
const from = resolveFrom(config, n);
|
|
24
|
+
const sender = splitAddress(from).address;
|
|
25
|
+
const to = toArray(n.to);
|
|
26
|
+
const cc = n.cc ? toArray(n.cc) : [];
|
|
27
|
+
const messageId = generateMessageId(sender);
|
|
28
|
+
const raw = buildMimeMessage({ from, to, cc, replyTo: n.replyTo, subject: n.subject, html: n.body, text: n.text, headers: n.headers, messageId });
|
|
29
|
+
const EmailMessage = deps.EmailMessage ?? await loadEmailMessage();
|
|
30
|
+
for (const recipient of [...new Set([...to, ...cc].map((address) => splitAddress(address).address))]) {
|
|
31
|
+
await binding.send(new EmailMessage(sender, recipient, raw));
|
|
32
|
+
}
|
|
33
|
+
return { messageId };
|
|
34
|
+
};
|
|
@@ -4,4 +4,9 @@ export interface CloudflareConfig extends EmailConfig {
|
|
|
4
4
|
accountId?: string;
|
|
5
5
|
apiToken?: string;
|
|
6
6
|
}
|
|
7
|
+
/** A sender as Cloudflare's REST API takes it: the bare address, or `{ address, name }` with a display name. */
|
|
8
|
+
export declare function cloudflareFrom(from: string): string | {
|
|
9
|
+
address: string;
|
|
10
|
+
name: string;
|
|
11
|
+
};
|
|
7
12
|
export declare const createCloudflareDriver: (config: CloudflareConfig) => EmailDriver;
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
import { assertOk, requireConfig, resolveFrom, toArray } from "./shared.js";
|
|
1
|
+
import { assertOk, hasHeaders, parseFromAddress, requireConfig, resolveFrom, toArray } from "./shared.js";
|
|
2
|
+
export function cloudflareFrom(from) {
|
|
3
|
+
const parsed = parseFromAddress(from);
|
|
4
|
+
return parsed.name ? { address: parsed.address, name: parsed.name } : parsed.address;
|
|
5
|
+
}
|
|
2
6
|
export const createCloudflareDriver = (config) => async (n) => {
|
|
3
7
|
const accountId = requireConfig(config.accountId, "NUXT_NOTIFY_EMAIL_CLOUDFLARE_ACCOUNT_ID");
|
|
4
8
|
const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(accountId)}/email/sending/send`, {
|
|
@@ -8,13 +12,15 @@ export const createCloudflareDriver = (config) => async (n) => {
|
|
|
8
12
|
"Content-Type": "application/json"
|
|
9
13
|
},
|
|
10
14
|
body: JSON.stringify({
|
|
11
|
-
|
|
15
|
+
// The REST API documents a bare address or `{ address, name }`, not the `"Name" <address>` form.
|
|
16
|
+
from: cloudflareFrom(resolveFrom(config, n)),
|
|
12
17
|
to: toArray(n.to),
|
|
13
18
|
cc: n.cc ? toArray(n.cc) : void 0,
|
|
14
19
|
subject: n.subject,
|
|
15
20
|
html: n.body,
|
|
16
21
|
text: n.text,
|
|
17
|
-
reply_to: n.replyTo
|
|
22
|
+
reply_to: n.replyTo,
|
|
23
|
+
headers: hasHeaders(n.headers) ? n.headers : void 0
|
|
18
24
|
})
|
|
19
25
|
});
|
|
20
26
|
await assertOk("Cloudflare", response);
|
|
@@ -1,5 +1,13 @@
|
|
|
1
|
-
import type { EmailDriver } from '../../../types.js';
|
|
2
|
-
export declare const EMAIL_DRIVER_NAMES: readonly ["log", "resend", "ses", "cloudflare"];
|
|
1
|
+
import type { EmailDriver, EmailNotification } from '../../../types.js';
|
|
2
|
+
export declare const EMAIL_DRIVER_NAMES: readonly ["log", "resend", "ses", "cloudflare", "cloudflare-binding"];
|
|
3
|
+
export type BuiltInEmailDriverName = typeof EMAIL_DRIVER_NAMES[number];
|
|
4
|
+
/** Whether `name` is a built-in email driver. */
|
|
5
|
+
export declare function isBuiltInEmailDriver(name: string): name is BuiltInEmailDriverName;
|
|
6
|
+
/**
|
|
7
|
+
* Sends through the built-in driver `name` (default: `NUXT_NOTIFY_EMAIL_DRIVER`), configured from
|
|
8
|
+
* `runtimeConfig.notify.email`. Only that driver's code is loaded.
|
|
9
|
+
*/
|
|
10
|
+
export declare function sendWithBuiltInEmailDriver(notification: EmailNotification, name?: string): Promise<void | import("../../../types.js").EmailSendResult>;
|
|
3
11
|
/**
|
|
4
12
|
* Default `#notify/email-driver`. Environment variables only exist at runtime, so the concrete
|
|
5
13
|
* driver is chosen per send from `runtimeConfig.notify.email` (`NUXT_NOTIFY_EMAIL_DRIVER`), and
|
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
import { useRuntimeConfig } from "#imports";
|
|
2
2
|
import { logDriver } from "../log.js";
|
|
3
|
-
export const EMAIL_DRIVER_NAMES = ["log", "resend", "ses", "cloudflare"];
|
|
4
|
-
|
|
3
|
+
export const EMAIL_DRIVER_NAMES = ["log", "resend", "ses", "cloudflare", "cloudflare-binding"];
|
|
4
|
+
export function isBuiltInEmailDriver(name) {
|
|
5
|
+
return EMAIL_DRIVER_NAMES.includes(name);
|
|
6
|
+
}
|
|
7
|
+
export async function sendWithBuiltInEmailDriver(notification, name) {
|
|
5
8
|
const config = useRuntimeConfig().notify?.email ?? {};
|
|
6
|
-
|
|
9
|
+
return sendWith(name || config.driver || "log", config, notification);
|
|
10
|
+
}
|
|
11
|
+
const autoDriver = (notification) => sendWithBuiltInEmailDriver(notification);
|
|
12
|
+
async function sendWith(name, config, notification) {
|
|
7
13
|
const base = { from: config.from };
|
|
8
14
|
switch (name) {
|
|
9
15
|
case "log":
|
|
@@ -14,8 +20,10 @@ const autoDriver = async (notification) => {
|
|
|
14
20
|
return (await import("./ses.js")).createSesDriver({ ...base, ...config.ses })(notification);
|
|
15
21
|
case "cloudflare":
|
|
16
22
|
return (await import("./cloudflare.js")).createCloudflareDriver({ ...base, ...config.cloudflare })(notification);
|
|
23
|
+
case "cloudflare-binding":
|
|
24
|
+
return (await import("./cloudflare-binding.js")).createCloudflareBindingDriver({ ...base, ...config.binding })(notification);
|
|
17
25
|
default:
|
|
18
26
|
throw new Error(`[notify] Unknown email driver "${name}" (NUXT_NOTIFY_EMAIL_DRIVER). Expected one of: ${EMAIL_DRIVER_NAMES.join(", ")}`);
|
|
19
27
|
}
|
|
20
|
-
}
|
|
28
|
+
}
|
|
21
29
|
export default autoDriver;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Bytes as base64 (`btoa` over chunks, so a long body never overflows the call stack). */
|
|
2
|
+
export declare function bytesToBase64(bytes: Uint8Array): string;
|
|
3
|
+
/** A header value on one line: line breaks and other control characters become a space (no header injection). */
|
|
4
|
+
export declare function headerSafe(value: string): string;
|
|
5
|
+
/**
|
|
6
|
+
* A header text as RFC 2047 encoded words when it has anything but printable ASCII (`=?UTF-8?B?...?=`, split so no
|
|
7
|
+
* word is longer than 75 characters and no character is cut in half); plain ASCII is returned as it is.
|
|
8
|
+
*/
|
|
9
|
+
export declare function encodeHeaderWords(value: string): string;
|
|
10
|
+
/** `"Name" <a@x.test>`, `Name <a@x.test>` or `a@x.test` split up. */
|
|
11
|
+
export declare function splitAddress(value: string): {
|
|
12
|
+
address: string;
|
|
13
|
+
name?: string;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* An address for a header: `"Name" <a@x.test>` with the name quoted when it is ASCII, or RFC 2047 encoded
|
|
17
|
+
* when it is not (`=?UTF-8?B?w6bDuMOl?= <a@x.test>`), or the bare address.
|
|
18
|
+
*/
|
|
19
|
+
export declare function formatAddressHeader(value: string): string;
|
|
20
|
+
/** A new globally unique Message-ID on the sender's domain, without angle brackets (`<hex>@<domain>` in the header). */
|
|
21
|
+
export declare function generateMessageId(from: string): string;
|
|
22
|
+
export type MimeMessageInput = {
|
|
23
|
+
from: string;
|
|
24
|
+
to: string[];
|
|
25
|
+
cc?: string[];
|
|
26
|
+
replyTo?: string;
|
|
27
|
+
subject: string;
|
|
28
|
+
html?: string;
|
|
29
|
+
text?: string;
|
|
30
|
+
/** Extra headers (`In-Reply-To`, `References`, `List-Unsubscribe`); the ones the builder writes are ignored. */
|
|
31
|
+
headers?: Record<string, string>;
|
|
32
|
+
/** Without angle brackets. */
|
|
33
|
+
messageId: string;
|
|
34
|
+
date?: Date;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* A complete RFC 5322 message with CRLF line ends: the headers (non-ASCII names and subjects RFC 2047 encoded, every
|
|
38
|
+
* value on one line), and a `text/plain`, `text/html` or `multipart/alternative` body in base64.
|
|
39
|
+
*/
|
|
40
|
+
export declare function buildMimeMessage(input: MimeMessageInput): string;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
const encoder = new TextEncoder();
|
|
2
|
+
export function bytesToBase64(bytes) {
|
|
3
|
+
let binary = "";
|
|
4
|
+
for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
|
|
5
|
+
return btoa(binary);
|
|
6
|
+
}
|
|
7
|
+
export function headerSafe(value) {
|
|
8
|
+
return value.replace(/[\u0000-\u001F\u007F]+/g, " ").trim();
|
|
9
|
+
}
|
|
10
|
+
const PRINTABLE_ASCII = /^[\u0020-\u007E]*$/;
|
|
11
|
+
export function encodeHeaderWords(value) {
|
|
12
|
+
const text = headerSafe(value);
|
|
13
|
+
if (PRINTABLE_ASCII.test(text)) return text;
|
|
14
|
+
const words = [];
|
|
15
|
+
let chunk = "";
|
|
16
|
+
for (const char of text) {
|
|
17
|
+
if (encoder.encode(chunk + char).length > 45) {
|
|
18
|
+
words.push(chunk);
|
|
19
|
+
chunk = "";
|
|
20
|
+
}
|
|
21
|
+
chunk += char;
|
|
22
|
+
}
|
|
23
|
+
if (chunk) words.push(chunk);
|
|
24
|
+
return words.map((word) => `=?UTF-8?B?${bytesToBase64(encoder.encode(word))}?=`).join(" ");
|
|
25
|
+
}
|
|
26
|
+
export function splitAddress(value) {
|
|
27
|
+
const match = /^([^<>]*)<([^<>\s]+)>\s*$/.exec(value.trim());
|
|
28
|
+
if (!match) return { address: value.trim() };
|
|
29
|
+
const name = match[1].trim().replace(/^"|"$/g, "").trim();
|
|
30
|
+
return name ? { address: match[2], name } : { address: match[2] };
|
|
31
|
+
}
|
|
32
|
+
export function formatAddressHeader(value) {
|
|
33
|
+
const { address, name } = splitAddress(value);
|
|
34
|
+
const safeAddress = headerSafe(address);
|
|
35
|
+
if (!name) return safeAddress;
|
|
36
|
+
const safeName = headerSafe(name).replace(/["\\]/g, "");
|
|
37
|
+
if (!safeName) return safeAddress;
|
|
38
|
+
return PRINTABLE_ASCII.test(safeName) ? `"${safeName}" <${safeAddress}>` : `${encodeHeaderWords(safeName)} <${safeAddress}>`;
|
|
39
|
+
}
|
|
40
|
+
function domainOf(address) {
|
|
41
|
+
const at = address.lastIndexOf("@");
|
|
42
|
+
return at < 0 ? "" : address.slice(at + 1).trim().toLowerCase();
|
|
43
|
+
}
|
|
44
|
+
export function generateMessageId(from) {
|
|
45
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
46
|
+
const id = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
47
|
+
return `${id}@${domainOf(splitAddress(from).address) || "localhost"}`;
|
|
48
|
+
}
|
|
49
|
+
const RESERVED_HEADERS = /* @__PURE__ */ new Set(["from", "to", "cc", "bcc", "subject", "reply-to", "message-id", "date", "mime-version", "content-type", "content-transfer-encoding"]);
|
|
50
|
+
const HEADER_NAME = /^[\u0021-\u0039\u003B-\u007E]+$/;
|
|
51
|
+
function base64Body(text) {
|
|
52
|
+
return bytesToBase64(encoder.encode(text)).replace(/.{1,76}/g, (line) => `${line}\r
|
|
53
|
+
`);
|
|
54
|
+
}
|
|
55
|
+
function part(contentType, text) {
|
|
56
|
+
return `Content-Type: ${contentType}; charset=UTF-8\r
|
|
57
|
+
Content-Transfer-Encoding: base64\r
|
|
58
|
+
\r
|
|
59
|
+
${base64Body(text)}`;
|
|
60
|
+
}
|
|
61
|
+
export function buildMimeMessage(input) {
|
|
62
|
+
const lines = [
|
|
63
|
+
`From: ${formatAddressHeader(input.from)}`,
|
|
64
|
+
`To: ${input.to.map(formatAddressHeader).join(", ")}`,
|
|
65
|
+
...input.cc?.length ? [`Cc: ${input.cc.map(formatAddressHeader).join(", ")}`] : [],
|
|
66
|
+
...input.replyTo ? [`Reply-To: ${formatAddressHeader(input.replyTo)}`] : [],
|
|
67
|
+
`Subject: ${encodeHeaderWords(input.subject)}`,
|
|
68
|
+
`Message-ID: <${headerSafe(input.messageId).replace(/^<|>$/g, "")}>`,
|
|
69
|
+
`Date: ${(input.date ?? /* @__PURE__ */ new Date()).toUTCString().replace("GMT", "+0000")}`,
|
|
70
|
+
"MIME-Version: 1.0"
|
|
71
|
+
];
|
|
72
|
+
for (const [name, value] of Object.entries(input.headers ?? {})) {
|
|
73
|
+
if (!HEADER_NAME.test(name) || RESERVED_HEADERS.has(name.toLowerCase())) continue;
|
|
74
|
+
lines.push(`${name}: ${encodeHeaderWords(value)}`);
|
|
75
|
+
}
|
|
76
|
+
const text = input.text;
|
|
77
|
+
const html = input.html;
|
|
78
|
+
if (text !== void 0 && html !== void 0) {
|
|
79
|
+
const boundary = `=_${generateMessageId("x@b").split("@")[0]}`;
|
|
80
|
+
lines.push(`Content-Type: multipart/alternative; boundary="${boundary}"`);
|
|
81
|
+
return `${lines.join("\r\n")}\r
|
|
82
|
+
\r
|
|
83
|
+
--${boundary}\r
|
|
84
|
+
${part("text/plain", text)}--${boundary}\r
|
|
85
|
+
${part("text/html", html)}--${boundary}--\r
|
|
86
|
+
`;
|
|
87
|
+
}
|
|
88
|
+
const [type, body] = html !== void 0 ? ["text/html", html] : ["text/plain", text ?? ""];
|
|
89
|
+
return `${lines.join("\r\n")}\r
|
|
90
|
+
${part(type, body)}`;
|
|
91
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { assertOk, requireConfig, resolveFrom, toArray } from "./shared.js";
|
|
1
|
+
import { assertOk, hasHeaders, requireConfig, resolveFrom, toArray } from "./shared.js";
|
|
2
2
|
export const createResendDriver = (config) => async (n) => {
|
|
3
3
|
const response = await fetch("https://api.resend.com/emails", {
|
|
4
4
|
method: "POST",
|
|
@@ -7,13 +7,14 @@ export const createResendDriver = (config) => async (n) => {
|
|
|
7
7
|
"Content-Type": "application/json"
|
|
8
8
|
},
|
|
9
9
|
body: JSON.stringify({
|
|
10
|
-
from: resolveFrom(config),
|
|
10
|
+
from: resolveFrom(config, n),
|
|
11
11
|
to: toArray(n.to),
|
|
12
12
|
cc: n.cc ? toArray(n.cc) : void 0,
|
|
13
13
|
subject: n.subject,
|
|
14
14
|
html: n.body,
|
|
15
15
|
text: n.text,
|
|
16
|
-
reply_to: n.replyTo
|
|
16
|
+
reply_to: n.replyTo,
|
|
17
|
+
headers: hasHeaders(n.headers) ? n.headers : void 0
|
|
17
18
|
})
|
|
18
19
|
});
|
|
19
20
|
await assertOk("Resend", response);
|
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
import { assertOk, requireConfig, resolveFrom, toArray } from "./shared.js";
|
|
1
|
+
import { assertOk, hasHeaders, requireConfig, resolveFrom, toArray } from "./shared.js";
|
|
2
2
|
import { signRequest } from "./sigv4.js";
|
|
3
|
+
import { formatAddressHeader } from "./mime.js";
|
|
3
4
|
export const createSesDriver = (config) => async (n) => {
|
|
4
5
|
const region = requireConfig(config.region, "NUXT_NOTIFY_EMAIL_SES_REGION");
|
|
5
6
|
const accessKeyId = requireConfig(config.accessKeyId, "NUXT_NOTIFY_EMAIL_SES_ACCESS_KEY_ID");
|
|
6
7
|
const secretAccessKey = requireConfig(config.secretAccessKey, "NUXT_NOTIFY_EMAIL_SES_SECRET_ACCESS_KEY");
|
|
7
8
|
const url = `https://email.${region}.amazonaws.com/v2/email/outbound-emails`;
|
|
8
9
|
const body = JSON.stringify({
|
|
9
|
-
|
|
10
|
+
// SES takes the header value as it is: a non-ASCII display name (æøå) must be RFC 2047 encoded.
|
|
11
|
+
FromEmailAddress: formatAddressHeader(resolveFrom(config, n)),
|
|
10
12
|
Destination: { ToAddresses: toArray(n.to), ...n.cc ? { CcAddresses: toArray(n.cc) } : {} },
|
|
11
13
|
ReplyToAddresses: n.replyTo ? [n.replyTo] : void 0,
|
|
12
14
|
Content: {
|
|
@@ -15,7 +17,8 @@ export const createSesDriver = (config) => async (n) => {
|
|
|
15
17
|
Body: {
|
|
16
18
|
Html: { Data: n.body, Charset: "UTF-8" },
|
|
17
19
|
...n.text ? { Text: { Data: n.text, Charset: "UTF-8" } } : {}
|
|
18
|
-
}
|
|
20
|
+
},
|
|
21
|
+
...hasHeaders(n.headers) ? { Headers: Object.entries(n.headers).map(([Name, Value]) => ({ Name, Value })) } : {}
|
|
19
22
|
}
|
|
20
23
|
}
|
|
21
24
|
});
|
|
@@ -2,10 +2,21 @@ import type { EmailNotification } from '../../../types.js';
|
|
|
2
2
|
export interface EmailConfig {
|
|
3
3
|
from?: string;
|
|
4
4
|
}
|
|
5
|
+
/** True when `headers` has at least one entry, so a driver leaves an empty object out of the request. */
|
|
6
|
+
export declare const hasHeaders: (headers: Record<string, string> | undefined) => headers is Record<string, string>;
|
|
5
7
|
export declare const toArray: (value: string | string[]) => string[];
|
|
6
8
|
/** Throws a config error naming the env var an operator needs to set. */
|
|
7
9
|
export declare function requireConfig(value: string | undefined, envVar: string): string;
|
|
8
|
-
|
|
10
|
+
/**
|
|
11
|
+
* The sender of an email: the notification's own `from` when it has one, else the configured one
|
|
12
|
+
* (`NUXT_NOTIFY_EMAIL_FROM`).
|
|
13
|
+
*/
|
|
14
|
+
export declare const resolveFrom: (config: EmailConfig, notification?: Pick<EmailNotification, "from">) => string;
|
|
15
|
+
/** `"Name" <a@x.test>` or `Name <a@x.test>` as `{ address, name }`; a bare address as `{ address }`. */
|
|
16
|
+
export declare function parseFromAddress(value: string): {
|
|
17
|
+
address: string;
|
|
18
|
+
name?: string;
|
|
19
|
+
};
|
|
9
20
|
/** Throws with the provider's response body for any non-2xx response. */
|
|
10
21
|
export declare function assertOk(provider: string, response: Response): Promise<void>;
|
|
11
22
|
export type { EmailNotification };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export const hasHeaders = (headers) => !!headers && Object.keys(headers).length > 0;
|
|
1
2
|
export const toArray = (value) => Array.isArray(value) ? value : [value];
|
|
2
3
|
export function requireConfig(value, envVar) {
|
|
3
4
|
if (!value) {
|
|
@@ -5,7 +6,13 @@ export function requireConfig(value, envVar) {
|
|
|
5
6
|
}
|
|
6
7
|
return value;
|
|
7
8
|
}
|
|
8
|
-
export const resolveFrom = (config) => requireConfig(config.from, "NUXT_NOTIFY_EMAIL_FROM");
|
|
9
|
+
export const resolveFrom = (config, notification) => notification?.from || requireConfig(config.from, "NUXT_NOTIFY_EMAIL_FROM");
|
|
10
|
+
export function parseFromAddress(value) {
|
|
11
|
+
const match = /^([^<>]*)<([^<>\s]+)>\s*$/.exec(value.trim());
|
|
12
|
+
if (!match) return { address: value.trim() };
|
|
13
|
+
const name = match[1].trim().replace(/^"|"$/g, "").trim();
|
|
14
|
+
return name ? { address: match[2], name } : { address: match[2] };
|
|
15
|
+
}
|
|
9
16
|
export async function assertOk(provider, response) {
|
|
10
17
|
if (!response.ok) {
|
|
11
18
|
const detail = await response.text().catch(() => "");
|
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import type { EmailNotification, PushDispatchResult, PushNotification, SMSNotification, SimpleNotification } from '../../../types.js';
|
|
1
|
+
import type { EmailNotification, EmailSendResult, NotifyEmailDispatchOptions, PushDispatchResult, PushNotification, SMSNotification, SimpleNotification } from '../../../types.js';
|
|
2
2
|
/**
|
|
3
3
|
* Dispatches an email notification through the driver configured on the `@frigear-nu/notify`
|
|
4
4
|
* module (`notify.email.driver`, see `#notify/email-driver`). Auto-imported wherever this module
|
|
5
5
|
* is installed, so consumers (e.g. `@frigear-nu/users`) only ever build an `EmailNotification`
|
|
6
|
-
* and call this - driver selection stays entirely with the app/consuming layer.
|
|
6
|
+
* and call this - driver selection stays entirely with the app/consuming layer. `options.driver` sends this one email
|
|
7
|
+
* through another built-in driver (configured from the same `NUXT_NOTIFY_EMAIL_*` settings), e.g. the inbox's replies
|
|
8
|
+
* through `cloudflare-binding`. Resolves to what the driver reports (`messageId`), or `undefined`.
|
|
7
9
|
*/
|
|
8
|
-
export declare function dispatchEmailNotification(notification: EmailNotification): Promise<
|
|
10
|
+
export declare function dispatchEmailNotification(notification: EmailNotification, options?: NotifyEmailDispatchOptions): Promise<EmailSendResult | undefined>;
|
|
9
11
|
/**
|
|
10
12
|
* Dispatches an SMS notification through the driver configured on the `@frigear-nu/notify`
|
|
11
13
|
* module (`notify.sms.driver`, see `#notify/sms-driver`). Auto-imported wherever this module is
|
|
@@ -1,10 +1,16 @@
|
|
|
1
1
|
import smsDriver from "#notify/sms-driver";
|
|
2
2
|
import simpleDriver from "#notify/simple-driver";
|
|
3
3
|
import pushDriver from "#notify/push-driver";
|
|
4
|
-
export async function dispatchEmailNotification(notification) {
|
|
4
|
+
export async function dispatchEmailNotification(notification, options = {}) {
|
|
5
5
|
const context = { notification };
|
|
6
6
|
await useNitroApp().hooks.callHook("notify:email", context);
|
|
7
|
-
|
|
7
|
+
if (options.driver) {
|
|
8
|
+
const { isBuiltInEmailDriver, sendWithBuiltInEmailDriver } = await import("../../drivers/email/index.js");
|
|
9
|
+
if (!isBuiltInEmailDriver(options.driver)) throw new Error(`[notify] Unknown email driver "${options.driver}" for this send.`);
|
|
10
|
+
return await sendWithBuiltInEmailDriver(context.notification, options.driver) ?? void 0;
|
|
11
|
+
}
|
|
12
|
+
const { default: emailDriver } = await import("#notify/email-driver");
|
|
13
|
+
return await emailDriver(context.notification) ?? void 0;
|
|
8
14
|
}
|
|
9
15
|
export async function dispatchSMSNotification(notification) {
|
|
10
16
|
await smsDriver(notification);
|
|
@@ -82,13 +82,14 @@ export async function notifyUser(userId, input) {
|
|
|
82
82
|
};
|
|
83
83
|
await run("email", async () => {
|
|
84
84
|
if (!recipient?.email || !input.email) return false;
|
|
85
|
-
const { subject, body, text, replyTo, template, meta } = input.email;
|
|
85
|
+
const { subject, body, text, replyTo, headers, template, meta } = input.email;
|
|
86
86
|
await dispatchEmailNotification({
|
|
87
87
|
to: recipient.email,
|
|
88
88
|
subject,
|
|
89
89
|
body,
|
|
90
90
|
...text !== void 0 ? { text } : {},
|
|
91
91
|
...replyTo !== void 0 ? { replyTo } : {},
|
|
92
|
+
...headers !== void 0 ? { headers } : {},
|
|
92
93
|
...template !== void 0 ? { template: template.locale || !recipient.locale ? template : { ...template, locale: recipient.locale } } : {},
|
|
93
94
|
...meta !== void 0 ? { meta } : {}
|
|
94
95
|
});
|
package/dist/types.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export { default } from './module.mjs'
|
|
2
2
|
|
|
3
|
-
export { type ChannelSettings, type EmailDriver, type EmailNotification, type EmailTemplateRef, type EmailTemplateSource, type ModuleOptions, type NotificationChannel, type NotificationChannelsDto, type NotificationChannelsRow, type NotificationChoices, type NotificationTopic, type NotificationTopicDto, type NotifyChoicesStore, type NotifyEmailContext, type NotifyRecipient, type NotifyRecipientStore, type NotifyUserInput, type NotifyUserResult, type PushDispatchResult, type PushDriver, type PushNotification, type PushText, type SMSDriver, type SMSNotification, type SimpleDriver, type SimpleNotification, type Translated } from './module.mjs'
|
|
3
|
+
export { type ChannelSettings, type EmailDriver, type EmailNotification, type EmailSendResult, type EmailTemplateRef, type EmailTemplateSource, type ModuleOptions, type NotificationChannel, type NotificationChannelsDto, type NotificationChannelsRow, type NotificationChoices, type NotificationTopic, type NotificationTopicDto, type NotifyChoicesStore, type NotifyEmailContext, type NotifyEmailDispatchOptions, type NotifyRecipient, type NotifyRecipientStore, type NotifyUserInput, type NotifyUserResult, type PushDispatchResult, type PushDriver, type PushNotification, type PushText, type SMSDriver, type SMSNotification, type SimpleDriver, type SimpleNotification, type Translated } from './module.mjs'
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@frigear-nu/notify",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Email, SMS, push and generic notification dispatch (pluggable drivers), and notifyUser: per-user channel choices over a topic registry. Shared across Frigear modules.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
],
|
|
31
31
|
"dependencies": {
|
|
32
32
|
"@nuxt/kit": "^4.6.4",
|
|
33
|
-
"@frigear-nu/module-kit": "^1.3.
|
|
33
|
+
"@frigear-nu/module-kit": "^1.3.12",
|
|
34
34
|
"defu": "^6.1.7",
|
|
35
35
|
"ufo": "^1.6.4"
|
|
36
36
|
},
|
|
@@ -41,8 +41,9 @@
|
|
|
41
41
|
"@nuxt/schema": "^4.6.4",
|
|
42
42
|
"@nuxt/test-utils": "^4.4.0",
|
|
43
43
|
"eslint": "^10.15.0",
|
|
44
|
-
"typescript": "^6.0.3",
|
|
45
44
|
"nuxt": "^4.6.4",
|
|
45
|
+
"postal-mime": "^2.7.6",
|
|
46
|
+
"typescript": "^6.0.3",
|
|
46
47
|
"vitest": "^5.1.0",
|
|
47
48
|
"vue-tsc": "^3.3.14"
|
|
48
49
|
},
|