emdash-plugin-comail 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Work-Right
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,84 @@
1
- # Temporary Holding Version
1
+ # emdash-plugin-comail
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [comail.at](https://comail.at) email transport for [EmDash CMS](https://github.com/emdash-cms/emdash). EmDash sends all of its email through one provider: magic links, invites, and every plugin's `ctx.email.send()`. This plugin makes comail that provider.
4
+
5
+ ## Install
6
+
7
+ Requires EmDash 1.7 or later and Node 22.16 or later.
8
+
9
+ ```sh
10
+ pnpm add emdash-plugin-comail
11
+ ```
12
+
13
+ ```js
14
+ // astro.config.mjs
15
+ import { comailEmail } from "emdash-plugin-comail";
16
+
17
+ export default defineConfig({
18
+ integrations: [
19
+ emdash({
20
+ plugins: [
21
+ comailEmail({
22
+ from: "events@example.com", // bare address on a domain enrolled with comail
23
+ categories: { gathering: "broadcast" }, // optional: comail category per sending plugin
24
+ }),
25
+ ],
26
+ }),
27
+ ],
28
+ });
29
+ ```
30
+
31
+ Then fill in **Admin → Plugins → comail**:
32
+ - **API key**: a secret, encrypted with `EMDASH_ENCRYPTION_KEY`. It's sent as `Authorization: Bearer <key>`.
33
+ - **DID**: your comail account's DID, sent as `X-Atmos-DID`.
34
+
35
+ EmDash selects comail automatically when it's the only email provider. Otherwise, pick it under **Settings → Email**.
36
+
37
+ Capabilities:
38
+ - `hooks.email-transport:register`, to provide the `email:deliver` hook;
39
+ - `network:request`, for `smtp.atmos.email` only.
40
+
41
+ ## Options
42
+
43
+ | Option | |
44
+ |---|---|
45
+ | `from` | Sender address. comail rejects display names (`Name <addr>`), so it must be a bare address. It's validated at config time. |
46
+ | `categories` | comail category by email **source**: the sending plugin's id, or `"system"` for EmDash's auth mail. Allowed values are `login-link`, `password-reset`, `mfa-otp`, `verification`, `bulk` and `broadcast`. Unlisted sources are sent as transactional. |
47
+
48
+ ## Errors
49
+
50
+ A failed send throws `ComailError` with `code` and `retryable`. Callers that send in bulk, such as [emdash-plugin-gathering](https://github.com/Work-Right/emdash-plugin-gathering)'s broadcasts, use `retryable` to decide whether to stop:
51
+
52
+ | `retryable` | When |
53
+ |---|---|
54
+ | `true`: pause the whole run | Auth (401/403), rate limits (429), comail's `RATE_LIMITED`, `QUEUE_FULL`, `TEMPORARILY_UNAVAILABLE` and `INTERNAL_ERROR`, any 5xx, any 4xx other than 400/422 (e.g. a moved API), `NETWORK`, `BAD_RESPONSE` (a non-JSON error body at any status, including 400/422: it didn't come from comail), `NOT_CONFIGURED` (missing key or DID, or a malformed DID), `TIMEOUT` |
55
+ | `false`: this recipient only | `REJECTED` (comail refused the recipient), a 400/422 with a comail error body such as `INVALID_REQUEST`, `CC_UNSUPPORTED` |
56
+
57
+ **Delivery unknown.** comail may already have accepted a message whose call timed out after 10 s (`TIMEOUT`). Resuming the run can then send that one message twice. A 2xx whose body can't be read, or that names no recipient, counts as delivered. That avoids duplicates, at the risk of missing a message comail silently dropped. It's logged as a warning.
58
+
59
+ comail sends one recipient per message, so a message with `cc` is refused.
60
+
61
+ ## Development
62
+
63
+ ```sh
64
+ pnpm install
65
+ pnpm test # vitest
66
+ pnpm typecheck # tsc --noEmit
67
+ pnpm build # compile src/ to dist/
68
+ pnpm smoke # pack the tarball and load it in plain Node, as EmDash does
69
+ ```
70
+
71
+ ## Releasing
72
+
73
+ 1. Bump `version` in `package.json` and `VERSION` in `src/index.ts` (a test fails if they differ), and move the `CHANGELOG.md` entries under the new version.
74
+ 2. Merge to `main`, then tag the merge commit: `git tag v0.1.1 && git push origin v0.1.1`.
75
+ 3. `.github/workflows/release.yml` checks that the tagged commit is on `main` and that the tag matches `package.json`, runs the tests and the smoke test, and publishes to npm with provenance.
76
+
77
+ Publishing uses npm trusted publishing, so no npm token is stored in GitHub. One-time setup:
78
+ - publish the first version by hand (`npm login`, then `npm publish`; `prepack` builds `dist/`), because trusted publishing is configured on an existing package. Don't push a tag for that hand-published version: the workflow would fail trying to publish it again;
79
+ - give the `work--right` npm org's developers team write access, so the package isn't tied to one account: `npm access grant read-write work--right:developers emdash-plugin-comail`;
80
+ - on npmjs.com, open the package's **Settings → Trusted publishing**, and add GitHub Actions with repository `Work-Right/emdash-plugin-comail` and workflow `release.yml`.
81
+
82
+ ## License
83
+
84
+ MIT. Ported from buildtreat's `src/lib/server/messaging/email.ts`.
@@ -0,0 +1,72 @@
1
+ import type { EmailDeliverEvent, PluginContext } from "emdash";
2
+ /**
3
+ * comail.at's HTTP Send API (cooperative email for the atproto network).
4
+ * One recipient per call. Ported from buildtreat's messaging/email.ts.
5
+ */
6
+ export declare const COMAIL_HOST = "smtp.atmos.email";
7
+ export declare const SEND_URL = "https://smtp.atmos.email/v1/send";
8
+ /** comail's routing hint. Unset means transactional. */
9
+ export type EmailCategory = "login-link" | "password-reset" | "mfa-otp" | "verification" | "bulk" | "broadcast";
10
+ export declare const CATEGORIES: readonly EmailCategory[];
11
+ /**
12
+ * A failed send. `retryable: true` means "the whole run should pause":
13
+ * rate limits, outages, and also auth or configuration problems, which no
14
+ * other recipient would get past either. `retryable: false` is a refusal
15
+ * of this one recipient (rejected, invalid address). Callers such as
16
+ * emdash-plugin-gathering read these two fields off the thrown error.
17
+ */
18
+ export declare class ComailError extends Error {
19
+ readonly code: string;
20
+ readonly retryable: boolean;
21
+ readonly name = "ComailError";
22
+ constructor(code: string, message: string, retryable: boolean);
23
+ }
24
+ export interface ComailCredentials {
25
+ did: string;
26
+ apiKey: string;
27
+ }
28
+ export interface ComailMessage {
29
+ /** Bare address: comail rejects `Name <addr>` and reserves the From header. */
30
+ from: string;
31
+ to: string;
32
+ subject: string;
33
+ text: string;
34
+ html?: string;
35
+ replyTo?: string;
36
+ category?: EmailCategory;
37
+ }
38
+ export interface HttpLike {
39
+ fetch(url: string, init?: RequestInit): Promise<Response>;
40
+ }
41
+ /** Returned when comail took the message (2xx) but its body named no id. */
42
+ export declare const UNKNOWN_MESSAGE_ID = "unknown";
43
+ /**
44
+ * Send one message; resolves with comail's message id, throws ComailError.
45
+ *
46
+ * Classification, read as "should a bulk send stop here?":
47
+ * - 2xx: delivered. A body that can't be read, or names no recipient,
48
+ * still counts: comail took the request, and calling it a failure would
49
+ * make a resumed broadcast send the mail twice. Only an explicit
50
+ * `rejected` entry is a refusal.
51
+ * - 400 / 422: this message or recipient is refused (`retryable: false`),
52
+ * unless the code is one of comail's transient ones.
53
+ * - Any other status (401/403 auth, 404/405/410 a moved API, 408/425/429,
54
+ * 5xx): stop the run (`retryable: true`).
55
+ * - Network error: retryable. A timeout is `TIMEOUT`: also retryable, but
56
+ * comail may have accepted the mail, so resuming can send it twice.
57
+ */
58
+ export declare function sendViaComail(http: HttpLike, creds: ComailCredentials, msg: ComailMessage): Promise<string>;
59
+ export interface ComailOptions {
60
+ /** Sender address. Must be a bare address on a domain enrolled with comail. */
61
+ from: string;
62
+ /**
63
+ * comail category per EmDash email source (the sending plugin's id, or
64
+ * "system" for auth mail), e.g. `{ gathering: "broadcast" }`.
65
+ */
66
+ categories?: Record<string, EmailCategory>;
67
+ }
68
+ type DeliverCtx = Pick<PluginContext, "settings" | "http" | "log">;
69
+ /** The `email:deliver` handler. Exported for tests; use `comailEmail()`. */
70
+ export declare function createComailDeliver(options: ComailOptions): (event: EmailDeliverEvent, ctx: DeliverCtx) => Promise<void>;
71
+ export {};
72
+ //# sourceMappingURL=comail.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"comail.d.ts","sourceRoot":"","sources":["../src/comail.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAE/D;;;GAGG;AAEH,eAAO,MAAM,WAAW,qBAAqB,CAAC;AAC9C,eAAO,MAAM,QAAQ,qCAAmC,CAAC;AAEzD,wDAAwD;AACxD,MAAM,MAAM,aAAa,GAAG,YAAY,GAAG,gBAAgB,GAAG,SAAS,GAAG,cAAc,GAAG,MAAM,GAAG,WAAW,CAAC;AAEhH,eAAO,MAAM,UAAU,EAAE,SAAS,aAAa,EAO9C,CAAC;AAEF;;;;;;GAMG;AACH,qBAAa,WAAY,SAAQ,KAAK;IAGpC,QAAQ,CAAC,IAAI,EAAE,MAAM;IAErB,QAAQ,CAAC,SAAS,EAAE,OAAO;IAJ5B,SAAkB,IAAI,iBAAiB;gBAE7B,IAAI,EAAE,MAAM,EACrB,OAAO,EAAE,MAAM,EACN,SAAS,EAAE,OAAO;CAI5B;AAED,MAAM,WAAW,iBAAiB;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,aAAa;IAC7B,+EAA+E;IAC/E,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,aAAa,CAAC;CACzB;AAED,MAAM,WAAW,QAAQ;IACxB,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CAC1D;AAID,4EAA4E;AAC5E,eAAO,MAAM,kBAAkB,YAAY,CAAC;AAM5C;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,aAAa,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,iBAAiB,EAAE,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC,CAsDjH;AAED,MAAM,WAAW,aAAa;IAC7B,+EAA+E;IAC/E,IAAI,EAAE,MAAM,CAAC;IACb;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;CAC3C;AAUD,KAAK,UAAU,GAAG,IAAI,CAAC,aAAa,EAAE,UAAU,GAAG,MAAM,GAAG,KAAK,CAAC,CAAC;AAEnE,4EAA4E;AAC5E,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,aAAa,IAC3C,OAAO,iBAAiB,EAAE,KAAK,UAAU,KAAG,OAAO,CAAC,IAAI,CAAC,CAuCvE"}
package/dist/comail.js ADDED
@@ -0,0 +1,153 @@
1
+ /**
2
+ * comail.at's HTTP Send API (cooperative email for the atproto network).
3
+ * One recipient per call. Ported from buildtreat's messaging/email.ts.
4
+ */
5
+ export const COMAIL_HOST = "smtp.atmos.email";
6
+ export const SEND_URL = `https://${COMAIL_HOST}/v1/send`;
7
+ export const CATEGORIES = [
8
+ "login-link",
9
+ "password-reset",
10
+ "mfa-otp",
11
+ "verification",
12
+ "bulk",
13
+ "broadcast",
14
+ ];
15
+ /**
16
+ * A failed send. `retryable: true` means "the whole run should pause":
17
+ * rate limits, outages, and also auth or configuration problems, which no
18
+ * other recipient would get past either. `retryable: false` is a refusal
19
+ * of this one recipient (rejected, invalid address). Callers such as
20
+ * emdash-plugin-gathering read these two fields off the thrown error.
21
+ */
22
+ export class ComailError extends Error {
23
+ code;
24
+ retryable;
25
+ name = "ComailError";
26
+ constructor(code, message, retryable) {
27
+ super(message);
28
+ this.code = code;
29
+ this.retryable = retryable;
30
+ }
31
+ }
32
+ const RETRYABLE_CODES = new Set(["RATE_LIMITED", "QUEUE_FULL", "TEMPORARILY_UNAVAILABLE", "INTERNAL_ERROR"]);
33
+ /** Returned when comail took the message (2xx) but its body named no id. */
34
+ export const UNKNOWN_MESSAGE_ID = "unknown";
35
+ function isTimeout(e) {
36
+ return e instanceof Error && (e.name === "TimeoutError" || e.name === "AbortError");
37
+ }
38
+ /**
39
+ * Send one message; resolves with comail's message id, throws ComailError.
40
+ *
41
+ * Classification, read as "should a bulk send stop here?":
42
+ * - 2xx: delivered. A body that can't be read, or names no recipient,
43
+ * still counts: comail took the request, and calling it a failure would
44
+ * make a resumed broadcast send the mail twice. Only an explicit
45
+ * `rejected` entry is a refusal.
46
+ * - 400 / 422: this message or recipient is refused (`retryable: false`),
47
+ * unless the code is one of comail's transient ones.
48
+ * - Any other status (401/403 auth, 404/405/410 a moved API, 408/425/429,
49
+ * 5xx): stop the run (`retryable: true`).
50
+ * - Network error: retryable. A timeout is `TIMEOUT`: also retryable, but
51
+ * comail may have accepted the mail, so resuming can send it twice.
52
+ */
53
+ export async function sendViaComail(http, creds, msg) {
54
+ let res;
55
+ try {
56
+ res = await http.fetch(SEND_URL, {
57
+ method: "POST",
58
+ signal: AbortSignal.timeout(10_000),
59
+ headers: {
60
+ "Content-Type": "application/json",
61
+ "X-Atmos-DID": creds.did,
62
+ Authorization: `Bearer ${creds.apiKey}`,
63
+ },
64
+ body: JSON.stringify({
65
+ from: msg.from,
66
+ to: msg.to,
67
+ subject: msg.subject,
68
+ text: msg.text,
69
+ ...(msg.html ? { html: msg.html } : {}),
70
+ ...(msg.replyTo ? { replyTo: msg.replyTo } : {}),
71
+ ...(msg.category ? { category: msg.category } : {}),
72
+ }),
73
+ });
74
+ }
75
+ catch (e) {
76
+ if (isTimeout(e)) {
77
+ throw new ComailError("TIMEOUT", "comail didn't answer within 10 s; delivery is unknown", true);
78
+ }
79
+ throw new ComailError("NETWORK", String(e), true);
80
+ }
81
+ let body = null;
82
+ let parsed = true;
83
+ try {
84
+ body = await res.json();
85
+ }
86
+ catch {
87
+ parsed = false;
88
+ }
89
+ if (res.ok) {
90
+ const ok = (body ?? {});
91
+ const accepted = ok.accepted?.[0];
92
+ if (accepted?.messageId != null)
93
+ return String(accepted.messageId);
94
+ const rejected = ok.rejected?.[0];
95
+ if (rejected)
96
+ throw new ComailError("REJECTED", rejected.error ?? "Recipient rejected", false);
97
+ return UNKNOWN_MESSAGE_ID;
98
+ }
99
+ if (!parsed)
100
+ throw new ComailError("BAD_RESPONSE", `HTTP ${res.status} with a non-JSON body`, true);
101
+ const err = (body ?? {});
102
+ const code = typeof err.code === "string" ? err.code : `HTTP_${res.status}`;
103
+ const message = typeof err.error === "string" ? err.error : `comail returned HTTP ${res.status}`;
104
+ const perMessage = (res.status === 400 || res.status === 422) && !RETRYABLE_CODES.has(code);
105
+ throw new ComailError(code, message, !perMessage);
106
+ }
107
+ // did:plc is 24 lowercase base32 chars. did:web is a hostname (any case;
108
+ // dot-separated labels that neither start nor end with "-"), an optional
109
+ // %3A-encoded port, then :-separated path parts that may hold %XX escapes.
110
+ const DID_PLC = /^did:plc:[a-z2-7]{24}$/;
111
+ const HOST_LABEL = "[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
112
+ const DID_WEB = new RegExp(`^did:web:${HOST_LABEL}(?:\\.${HOST_LABEL})*(%3a\\d+)?(:([a-z0-9._~-]|%[0-9a-f]{2})+)*$`, "i");
113
+ const isDid = (did) => DID_PLC.test(did) || DID_WEB.test(did);
114
+ /** The `email:deliver` handler. Exported for tests; use `comailEmail()`. */
115
+ export function createComailDeliver(options) {
116
+ return async (event, ctx) => {
117
+ const { message, source } = event;
118
+ if (message.cc?.length) {
119
+ throw new ComailError("CC_UNSUPPORTED", "comail sends to one recipient per message; cc is not supported", false);
120
+ }
121
+ const apiKey = (await ctx.settings.get("apiKey"))?.trim();
122
+ const did = (await ctx.settings.get("did"))?.trim();
123
+ if (!ctx.http) {
124
+ throw new ComailError("NOT_CONFIGURED", "comail has no network access: grant the plugin the network:request capability", true);
125
+ }
126
+ if (!apiKey || !did) {
127
+ throw new ComailError("NOT_CONFIGURED", "Set the comail API key and DID in the plugin settings", true);
128
+ }
129
+ // comail answers a malformed DID with 400 INVALID_REQUEST, which reads
130
+ // as a per-recipient refusal; catch it here so a bulk send stops instead
131
+ // of failing every recipient one by one.
132
+ if (!isDid(did)) {
133
+ throw new ComailError("NOT_CONFIGURED", `The comail DID setting isn't a valid DID: ${did}`, true);
134
+ }
135
+ const category = options.categories?.[source];
136
+ const messageId = await sendViaComail(ctx.http, { apiKey, did }, {
137
+ from: options.from,
138
+ to: message.to,
139
+ subject: message.subject,
140
+ text: message.text,
141
+ ...(message.html ? { html: message.html } : {}),
142
+ ...(message.replyTo ? { replyTo: message.replyTo } : {}),
143
+ ...(category ? { category } : {}),
144
+ });
145
+ if (messageId === UNKNOWN_MESSAGE_ID) {
146
+ ctx.log.warn("comail accepted the email but returned no message id", { source });
147
+ }
148
+ else {
149
+ ctx.log.info("email delivered via comail", { source, messageId });
150
+ }
151
+ };
152
+ }
153
+ //# sourceMappingURL=comail.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"comail.js","sourceRoot":"","sources":["../src/comail.ts"],"names":[],"mappings":"AAEA;;;GAGG;AAEH,MAAM,CAAC,MAAM,WAAW,GAAG,kBAAkB,CAAC;AAC9C,MAAM,CAAC,MAAM,QAAQ,G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CAAC,UAAU,EAAE,CAAC,MAAM,CAAC,CAAC;QAC9C,MAAM,SAAS,GAAG,MAAM,aAAa,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE;YAChE,IAAI,EAAE,OAAO,CAAC,IAAI;YAClB,EAAE,EAAE,OAAO,CAAC,EAAE;YACd,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,IAAI,EAAE,OAAO,CAAC,IAAI;YAClB,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC/C,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACxD,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACjC,CAAC,CAAC;QACH,IAAI,SAAS,KAAK,kBAAkB,EAAE,CAAC;YACtC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,sDAAsD,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;QAClF,CAAC;aAAM,CAAC;YACP,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,4BAA4B,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC;QACnE,CAAC;IACF,CAAC,CAAC;AACH,CAAC"}
@@ -0,0 +1,27 @@
1
+ import type { PluginDescriptor } from "emdash";
2
+ import { type ComailOptions } from "./comail.js";
3
+ export { ComailError, type ComailOptions, type EmailCategory } from "./comail.js";
4
+ export declare const PLUGIN_ID = "comail";
5
+ export declare const VERSION = "0.1.0";
6
+ /** Admin → Plugins → comail. The API key is encrypted with EMDASH_ENCRYPTION_KEY. */
7
+ export declare const SETTINGS_SCHEMA: {
8
+ apiKey: {
9
+ type: "secret";
10
+ label: string;
11
+ description: string;
12
+ };
13
+ did: {
14
+ type: "string";
15
+ label: string;
16
+ description: string;
17
+ };
18
+ };
19
+ /**
20
+ * Register in astro.config.mjs:
21
+ * `emdash({ plugins: [comailEmail({ from: "events@example.com" })] })`,
22
+ * then select comail under Settings → Email if another provider is active.
23
+ */
24
+ export declare function comailEmail(options: ComailOptions): PluginDescriptor<ComailOptions>;
25
+ export declare function createPlugin(options: ComailOptions): import("emdash").ResolvedPlugin<import("emdash").PluginStorageConfig>;
26
+ export default createPlugin;
27
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAgB,MAAM,QAAQ,CAAC;AAG7D,OAAO,EAA2B,KAAK,aAAa,EAAuB,MAAM,aAAa,CAAC;AAE/F,OAAO,EAAE,WAAW,EAAE,KAAK,aAAa,EAAE,KAAK,aAAa,EAAE,MAAM,aAAa,CAAC;AAElF,eAAO,MAAM,SAAS,WAAW,CAAC;AAClC,eAAO,MAAM,OAAO,UAAU,CAAC;AAS/B,qFAAqF;AACrF,eAAO,MAAM,eAAe;;;;;;;;;;;CAGY,CAAC;AAiBzC;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,aAAa,GAAG,gBAAgB,CAAC,aAAa,CAAC,CAYnF;AAED,wBAAgB,YAAY,CAAC,OAAO,EAAE,aAAa,yEAclD;AAED,eAAe,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,62 @@
1
+ import { definePlugin } from "emdash";
2
+ import { CATEGORIES, COMAIL_HOST, createComailDeliver } from "./comail.js";
3
+ export { ComailError } from "./comail.js";
4
+ export const PLUGIN_ID = "comail";
5
+ export const VERSION = "0.1.0";
6
+ /**
7
+ * - `hooks.email-transport:register`: provide the exclusive `email:deliver` hook.
8
+ * - `network:request`: POST to smtp.atmos.email, and nowhere else.
9
+ */
10
+ const CAPABILITIES = ["hooks.email-transport:register", "network:request"];
11
+ const ALLOWED_HOSTS = [COMAIL_HOST];
12
+ /** Admin → Plugins → comail. The API key is encrypted with EMDASH_ENCRYPTION_KEY. */
13
+ export const SETTINGS_SCHEMA = {
14
+ apiKey: { type: "secret", label: "comail API key", description: "Sent as Authorization: Bearer <key>." },
15
+ did: { type: "string", label: "comail account DID", description: "Sent as X-Atmos-DID, e.g. did:plc:…" },
16
+ };
17
+ const BARE_ADDRESS = /^[^\s@<>"]+@[^\s@<>"]+\.[^\s@<>"]+$/;
18
+ function validate(options) {
19
+ if (!options?.from || !BARE_ADDRESS.test(options.from)) {
20
+ throw new Error('[comail] options.from must be a bare address like "events@example.com". comail rejects display names.');
21
+ }
22
+ for (const [source, category] of Object.entries(options.categories ?? {})) {
23
+ if (!CATEGORIES.includes(category)) {
24
+ throw new Error(`[comail] unknown category ${JSON.stringify(category)} for source ${JSON.stringify(source)}`);
25
+ }
26
+ }
27
+ }
28
+ /**
29
+ * Register in astro.config.mjs:
30
+ * `emdash({ plugins: [comailEmail({ from: "events@example.com" })] })`,
31
+ * then select comail under Settings → Email if another provider is active.
32
+ */
33
+ export function comailEmail(options) {
34
+ validate(options);
35
+ return {
36
+ id: PLUGIN_ID,
37
+ version: VERSION,
38
+ entrypoint: "emdash-plugin-comail",
39
+ format: "native",
40
+ options,
41
+ capabilities: [...CAPABILITIES],
42
+ allowedHosts: ALLOWED_HOSTS,
43
+ settingsSchema: SETTINGS_SCHEMA,
44
+ };
45
+ }
46
+ export function createPlugin(options) {
47
+ validate(options);
48
+ return definePlugin({
49
+ id: PLUGIN_ID,
50
+ version: VERSION,
51
+ capabilities: [...CAPABILITIES],
52
+ allowedHosts: ALLOWED_HOSTS,
53
+ admin: { settingsSchema: SETTINGS_SCHEMA },
54
+ hooks: {
55
+ // The send itself times out at 10 s; leave the hook room so that timeout,
56
+ // not the hook's default 5 s, decides (a hook timeout hides the code).
57
+ "email:deliver": { exclusive: true, timeout: 15_000, handler: createComailDeliver(options) },
58
+ },
59
+ });
60
+ }
61
+ export default createPlugin;
62
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EAAE,UAAU,EAAE,WAAW,EAAsB,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAE/F,OAAO,EAAE,WAAW,EAA0C,MAAM,aAAa,CAAC;AAElF,MAAM,CAAC,MAAM,SAAS,GAAG,QAAQ,CAAC;AAClC,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC;AAE/B;;;GAGG;AACH,MAAM,YAAY,GAAG,CAAC,gCAAgC,EAAE,iBAAiB,CAAqD,CAAC;AAC/H,MAAM,aAAa,GAAG,CAAC,WAAW,CAAC,CAAC;AAEpC,qFAAqF;AACrF,MAAM,CAAC,MAAM,eAAe,GAAG;IAC9B,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,gBAAgB,EAAE,WAAW,EAAE,sCAAsC,EAAE;IACxG,GAAG,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,oBAAoB,EAAE,WAAW,EAAE,qCAAqC,EAAE;CACjE,CAAC;AAEzC,MAAM,YAAY,GAAG,qCAAqC,CAAC;AAE3D,SAAS,QAAQ,CAAC,OAAsB;IACvC,IAAI,CAAC,OAAO,EAAE,IAAI,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;QACxD,MAAM,IAAI,KAAK,CACd,uGAAuG,CACvG,CAAC;IACH,CAAC;IACD,KAAK,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,UAAU,IAAI,EAAE,CAAC,EAAE,CAAC;QAC3E,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;YACpC,MAAM,IAAI,KAAK,CAAC,6BAA6B,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,eAAe,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QAC/G,CAAC;IACF,CAAC;AACF,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,OAAsB;IACjD,QAAQ,CAAC,OAAO,CAAC,CAAC;IAClB,OAAO;QACN,EAAE,EAAE,SAAS;QACb,OAAO,EAAE,OAAO;QAChB,UAAU,EAAE,sBAAsB;QAClC,MAAM,EAAE,QAAQ;QAChB,OAAO;QACP,YAAY,EAAE,CAAC,GAAG,YAAY,CAAC;QAC/B,YAAY,EAAE,aAAa;QAC3B,cAAc,EAAE,eAAe;KAC/B,CAAC;AACH,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,OAAsB;IAClD,QAAQ,CAAC,OAAO,CAAC,CAAC;IAClB,OAAO,YAAY,CAAC;QACnB,EAAE,EAAE,SAAS;QACb,OAAO,EAAE,OAAO;QAChB,YAAY,EAAE,CAAC,GAAG,YAAY,CAAC;QAC/B,YAAY,EAAE,aAAa;QAC3B,KAAK,EAAE,EAAE,cAAc,EAAE,eAAe,EAAE;QAC1C,KAAK,EAAE;YACN,0EAA0E;YAC1E,uEAAuE;YACvE,eAAe,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,mBAAmB,CAAC,OAAO,CAAC,EAAE;SAC5F;KACD,CAAC,CAAC;AACJ,CAAC;AAED,eAAe,YAAY,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
- "name": "emdash-plugin-comail",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "emdash-plugin-comail",
3
+ "version": "0.1.0",
4
+ "description": "comail.at email transport for EmDash: every plugin's ctx.email.send() goes out through comail",
5
+ "keywords": [
6
+ "emdash",
7
+ "emdash-plugin",
8
+ "email",
9
+ "email-transport",
10
+ "comail",
11
+ "atproto"
12
+ ],
13
+ "homepage": "https://github.com/Work-Right/emdash-plugin-comail#readme",
14
+ "bugs": "https://github.com/Work-Right/emdash-plugin-comail/issues",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/Work-Right/emdash-plugin-comail.git"
18
+ },
19
+ "author": "Work-Right",
20
+ "license": "MIT",
21
+ "type": "module",
22
+ "sideEffects": false,
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js",
29
+ "default": "./dist/index.js"
30
+ },
31
+ "./package.json": "./package.json"
32
+ },
33
+ "files": [
34
+ "dist",
35
+ "src"
36
+ ],
37
+ "engines": {
38
+ "node": ">=22.16"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "packageManager": "pnpm@12.16.1",
44
+ "scripts": {
45
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
46
+ "test": "vitest run",
47
+ "typecheck": "tsc --noEmit",
48
+ "smoke": "node scripts/smoke-pack.mjs",
49
+ "prepack": "pnpm build"
50
+ },
51
+ "peerDependencies": {
52
+ "emdash": ">=1.7.0"
53
+ },
54
+ "devDependencies": {
55
+ "@types/node": "^26.6.11",
56
+ "emdash": "^1.7.0",
57
+ "typescript": "^6.0.3",
58
+ "vitest": "^4.1.12"
59
+ }
60
+ }
package/src/comail.ts ADDED
@@ -0,0 +1,202 @@
1
+ import type { EmailDeliverEvent, PluginContext } from "emdash";
2
+
3
+ /**
4
+ * comail.at's HTTP Send API (cooperative email for the atproto network).
5
+ * One recipient per call. Ported from buildtreat's messaging/email.ts.
6
+ */
7
+
8
+ export const COMAIL_HOST = "smtp.atmos.email";
9
+ export const SEND_URL = `https://${COMAIL_HOST}/v1/send`;
10
+
11
+ /** comail's routing hint. Unset means transactional. */
12
+ export type EmailCategory = "login-link" | "password-reset" | "mfa-otp" | "verification" | "bulk" | "broadcast";
13
+
14
+ export const CATEGORIES: readonly EmailCategory[] = [
15
+ "login-link",
16
+ "password-reset",
17
+ "mfa-otp",
18
+ "verification",
19
+ "bulk",
20
+ "broadcast",
21
+ ];
22
+
23
+ /**
24
+ * A failed send. `retryable: true` means "the whole run should pause":
25
+ * rate limits, outages, and also auth or configuration problems, which no
26
+ * other recipient would get past either. `retryable: false` is a refusal
27
+ * of this one recipient (rejected, invalid address). Callers such as
28
+ * emdash-plugin-gathering read these two fields off the thrown error.
29
+ */
30
+ export class ComailError extends Error {
31
+ override readonly name = "ComailError";
32
+ constructor(
33
+ readonly code: string,
34
+ message: string,
35
+ readonly retryable: boolean,
36
+ ) {
37
+ super(message);
38
+ }
39
+ }
40
+
41
+ export interface ComailCredentials {
42
+ did: string;
43
+ apiKey: string;
44
+ }
45
+
46
+ export interface ComailMessage {
47
+ /** Bare address: comail rejects `Name <addr>` and reserves the From header. */
48
+ from: string;
49
+ to: string;
50
+ subject: string;
51
+ text: string;
52
+ html?: string;
53
+ replyTo?: string;
54
+ category?: EmailCategory;
55
+ }
56
+
57
+ export interface HttpLike {
58
+ fetch(url: string, init?: RequestInit): Promise<Response>;
59
+ }
60
+
61
+ const RETRYABLE_CODES = new Set(["RATE_LIMITED", "QUEUE_FULL", "TEMPORARILY_UNAVAILABLE", "INTERNAL_ERROR"]);
62
+
63
+ /** Returned when comail took the message (2xx) but its body named no id. */
64
+ export const UNKNOWN_MESSAGE_ID = "unknown";
65
+
66
+ function isTimeout(e: unknown): boolean {
67
+ return e instanceof Error && (e.name === "TimeoutError" || e.name === "AbortError");
68
+ }
69
+
70
+ /**
71
+ * Send one message; resolves with comail's message id, throws ComailError.
72
+ *
73
+ * Classification, read as "should a bulk send stop here?":
74
+ * - 2xx: delivered. A body that can't be read, or names no recipient,
75
+ * still counts: comail took the request, and calling it a failure would
76
+ * make a resumed broadcast send the mail twice. Only an explicit
77
+ * `rejected` entry is a refusal.
78
+ * - 400 / 422: this message or recipient is refused (`retryable: false`),
79
+ * unless the code is one of comail's transient ones.
80
+ * - Any other status (401/403 auth, 404/405/410 a moved API, 408/425/429,
81
+ * 5xx): stop the run (`retryable: true`).
82
+ * - Network error: retryable. A timeout is `TIMEOUT`: also retryable, but
83
+ * comail may have accepted the mail, so resuming can send it twice.
84
+ */
85
+ export async function sendViaComail(http: HttpLike, creds: ComailCredentials, msg: ComailMessage): Promise<string> {
86
+ let res: Response;
87
+ try {
88
+ res = await http.fetch(SEND_URL, {
89
+ method: "POST",
90
+ signal: AbortSignal.timeout(10_000),
91
+ headers: {
92
+ "Content-Type": "application/json",
93
+ "X-Atmos-DID": creds.did,
94
+ Authorization: `Bearer ${creds.apiKey}`,
95
+ },
96
+ body: JSON.stringify({
97
+ from: msg.from,
98
+ to: msg.to,
99
+ subject: msg.subject,
100
+ text: msg.text,
101
+ ...(msg.html ? { html: msg.html } : {}),
102
+ ...(msg.replyTo ? { replyTo: msg.replyTo } : {}),
103
+ ...(msg.category ? { category: msg.category } : {}),
104
+ }),
105
+ });
106
+ } catch (e) {
107
+ if (isTimeout(e)) {
108
+ throw new ComailError("TIMEOUT", "comail didn't answer within 10 s; delivery is unknown", true);
109
+ }
110
+ throw new ComailError("NETWORK", String(e), true);
111
+ }
112
+
113
+ let body: unknown = null;
114
+ let parsed = true;
115
+ try {
116
+ body = await res.json();
117
+ } catch {
118
+ parsed = false;
119
+ }
120
+
121
+ if (res.ok) {
122
+ const ok = (body ?? {}) as {
123
+ accepted?: Array<{ messageId?: number | string }>;
124
+ rejected?: Array<{ recipient?: string; error?: string }>;
125
+ };
126
+ const accepted = ok.accepted?.[0];
127
+ if (accepted?.messageId != null) return String(accepted.messageId);
128
+ const rejected = ok.rejected?.[0];
129
+ if (rejected) throw new ComailError("REJECTED", rejected.error ?? "Recipient rejected", false);
130
+ return UNKNOWN_MESSAGE_ID;
131
+ }
132
+
133
+ if (!parsed) throw new ComailError("BAD_RESPONSE", `HTTP ${res.status} with a non-JSON body`, true);
134
+ const err = (body ?? {}) as { error?: unknown; code?: unknown };
135
+ const code = typeof err.code === "string" ? err.code : `HTTP_${res.status}`;
136
+ const message = typeof err.error === "string" ? err.error : `comail returned HTTP ${res.status}`;
137
+ const perMessage = (res.status === 400 || res.status === 422) && !RETRYABLE_CODES.has(code);
138
+ throw new ComailError(code, message, !perMessage);
139
+ }
140
+
141
+ export interface ComailOptions {
142
+ /** Sender address. Must be a bare address on a domain enrolled with comail. */
143
+ from: string;
144
+ /**
145
+ * comail category per EmDash email source (the sending plugin's id, or
146
+ * "system" for auth mail), e.g. `{ gathering: "broadcast" }`.
147
+ */
148
+ categories?: Record<string, EmailCategory>;
149
+ }
150
+
151
+ // did:plc is 24 lowercase base32 chars. did:web is a hostname (any case;
152
+ // dot-separated labels that neither start nor end with "-"), an optional
153
+ // %3A-encoded port, then :-separated path parts that may hold %XX escapes.
154
+ const DID_PLC = /^did:plc:[a-z2-7]{24}$/;
155
+ const HOST_LABEL = "[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
156
+ const DID_WEB = new RegExp(`^did:web:${HOST_LABEL}(?:\\.${HOST_LABEL})*(%3a\\d+)?(:([a-z0-9._~-]|%[0-9a-f]{2})+)*$`, "i");
157
+ const isDid = (did: string) => DID_PLC.test(did) || DID_WEB.test(did);
158
+
159
+ type DeliverCtx = Pick<PluginContext, "settings" | "http" | "log">;
160
+
161
+ /** The `email:deliver` handler. Exported for tests; use `comailEmail()`. */
162
+ export function createComailDeliver(options: ComailOptions) {
163
+ return async (event: EmailDeliverEvent, ctx: DeliverCtx): Promise<void> => {
164
+ const { message, source } = event;
165
+ if (message.cc?.length) {
166
+ throw new ComailError("CC_UNSUPPORTED", "comail sends to one recipient per message; cc is not supported", false);
167
+ }
168
+ const apiKey = (await ctx.settings.get<string>("apiKey"))?.trim();
169
+ const did = (await ctx.settings.get<string>("did"))?.trim();
170
+ if (!ctx.http) {
171
+ throw new ComailError(
172
+ "NOT_CONFIGURED",
173
+ "comail has no network access: grant the plugin the network:request capability",
174
+ true,
175
+ );
176
+ }
177
+ if (!apiKey || !did) {
178
+ throw new ComailError("NOT_CONFIGURED", "Set the comail API key and DID in the plugin settings", true);
179
+ }
180
+ // comail answers a malformed DID with 400 INVALID_REQUEST, which reads
181
+ // as a per-recipient refusal; catch it here so a bulk send stops instead
182
+ // of failing every recipient one by one.
183
+ if (!isDid(did)) {
184
+ throw new ComailError("NOT_CONFIGURED", `The comail DID setting isn't a valid DID: ${did}`, true);
185
+ }
186
+ const category = options.categories?.[source];
187
+ const messageId = await sendViaComail(ctx.http, { apiKey, did }, {
188
+ from: options.from,
189
+ to: message.to,
190
+ subject: message.subject,
191
+ text: message.text,
192
+ ...(message.html ? { html: message.html } : {}),
193
+ ...(message.replyTo ? { replyTo: message.replyTo } : {}),
194
+ ...(category ? { category } : {}),
195
+ });
196
+ if (messageId === UNKNOWN_MESSAGE_ID) {
197
+ ctx.log.warn("comail accepted the email but returned no message id", { source });
198
+ } else {
199
+ ctx.log.info("email delivered via comail", { source, messageId });
200
+ }
201
+ };
202
+ }
package/src/index.ts ADDED
@@ -0,0 +1,74 @@
1
+ import type { PluginDescriptor, SettingField } from "emdash";
2
+ import { definePlugin } from "emdash";
3
+
4
+ import { CATEGORIES, COMAIL_HOST, type ComailOptions, createComailDeliver } from "./comail.js";
5
+
6
+ export { ComailError, type ComailOptions, type EmailCategory } from "./comail.js";
7
+
8
+ export const PLUGIN_ID = "comail";
9
+ export const VERSION = "0.1.0";
10
+
11
+ /**
12
+ * - `hooks.email-transport:register`: provide the exclusive `email:deliver` hook.
13
+ * - `network:request`: POST to smtp.atmos.email, and nowhere else.
14
+ */
15
+ const CAPABILITIES = ["hooks.email-transport:register", "network:request"] as const satisfies PluginDescriptor["capabilities"];
16
+ const ALLOWED_HOSTS = [COMAIL_HOST];
17
+
18
+ /** Admin → Plugins → comail. The API key is encrypted with EMDASH_ENCRYPTION_KEY. */
19
+ export const SETTINGS_SCHEMA = {
20
+ apiKey: { type: "secret", label: "comail API key", description: "Sent as Authorization: Bearer <key>." },
21
+ did: { type: "string", label: "comail account DID", description: "Sent as X-Atmos-DID, e.g. did:plc:…" },
22
+ } satisfies Record<string, SettingField>;
23
+
24
+ const BARE_ADDRESS = /^[^\s@<>"]+@[^\s@<>"]+\.[^\s@<>"]+$/;
25
+
26
+ function validate(options: ComailOptions): void {
27
+ if (!options?.from || !BARE_ADDRESS.test(options.from)) {
28
+ throw new Error(
29
+ '[comail] options.from must be a bare address like "events@example.com". comail rejects display names.',
30
+ );
31
+ }
32
+ for (const [source, category] of Object.entries(options.categories ?? {})) {
33
+ if (!CATEGORIES.includes(category)) {
34
+ throw new Error(`[comail] unknown category ${JSON.stringify(category)} for source ${JSON.stringify(source)}`);
35
+ }
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Register in astro.config.mjs:
41
+ * `emdash({ plugins: [comailEmail({ from: "events@example.com" })] })`,
42
+ * then select comail under Settings → Email if another provider is active.
43
+ */
44
+ export function comailEmail(options: ComailOptions): PluginDescriptor<ComailOptions> {
45
+ validate(options);
46
+ return {
47
+ id: PLUGIN_ID,
48
+ version: VERSION,
49
+ entrypoint: "emdash-plugin-comail",
50
+ format: "native",
51
+ options,
52
+ capabilities: [...CAPABILITIES],
53
+ allowedHosts: ALLOWED_HOSTS,
54
+ settingsSchema: SETTINGS_SCHEMA,
55
+ };
56
+ }
57
+
58
+ export function createPlugin(options: ComailOptions) {
59
+ validate(options);
60
+ return definePlugin({
61
+ id: PLUGIN_ID,
62
+ version: VERSION,
63
+ capabilities: [...CAPABILITIES],
64
+ allowedHosts: ALLOWED_HOSTS,
65
+ admin: { settingsSchema: SETTINGS_SCHEMA },
66
+ hooks: {
67
+ // The send itself times out at 10 s; leave the hook room so that timeout,
68
+ // not the hook's default 5 s, decides (a hook timeout hides the code).
69
+ "email:deliver": { exclusive: true, timeout: 15_000, handler: createComailDeliver(options) },
70
+ },
71
+ });
72
+ }
73
+
74
+ export default createPlugin;