@tansy/email 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 Mohamed Salah
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,13 @@
1
- # Temporary Holding Version
1
+ <!-- Generated by scripts/package-metadata.mjs. Change that script, not this file. -->
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
+ # @tansy/email
4
+
5
+ Send Tansy's email through an email API instead of SMTP, with a delivery log. Add a provider package, such as @tansy/email-resend.
6
+
7
+ ```bash
8
+ npm install @tansy/email
9
+ ```
10
+
11
+ Add it to `tansy.config.ts`. See [the email plugin documentation](https://github.com/mhmdsalahsebai/tansy/blob/main/docs/plugins/email.md) for what it adds and the options it takes.
12
+
13
+ A first-party plugin for [tansy](https://github.com/mhmdsalahsebai/tansy), a self-hosted, runtime-schema CMS for Next.js. MIT licensed.
package/admin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ declare const _default: import("tansy/admin").AdminPluginParts;
2
+ export default _default;
package/admin.js ADDED
@@ -0,0 +1,14 @@
1
+ import { defineAdminPlugin } from "tansy/admin";
2
+ import { MESSAGES } from "./logic";
3
+ /** An envelope, in the navigation's 16 by 16 box. */
4
+ const ENVELOPE = {
5
+ paths: ["M1.5 3.5A1.5 1.5 0 0 1 3 2h10a1.5 1.5 0 0 1 1.5 1.5v9A1.5 1.5 0 0 1 13 14H3a1.5 1.5 0 0 1-1.5-1.5v-9Zm1.6-.1L8 7.1l4.9-3.7H3.1ZM13 4.9 8.45 8.35a.75.75 0 0 1-.9 0L3 4.9v7.6h10V4.9Z"],
6
+ fillRule: "evenodd",
7
+ };
8
+ export default defineAdminPlugin({
9
+ section: {
10
+ title: "Email",
11
+ icon: ENVELOPE,
12
+ items: [{ collection: MESSAGES }, { settings: true }],
13
+ },
14
+ });
package/index.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import { type EmailProvider } from "./provider";
2
+ export { MESSAGES } from "./logic";
3
+ export type { EmailProvider } from "./provider";
4
+ export interface EmailOptions {
5
+ /**
6
+ * The providers the site can send with, each from its own package, such as `resend()`
7
+ * from @tansy/email-resend. Owners choose one under Email → Settings.
8
+ */
9
+ providers: EmailProvider[];
10
+ /** Which of them sends until changed under Email → Settings. The first when left out. */
11
+ provider?: string;
12
+ }
13
+ /**
14
+ * Sends the site's email, account email and plugins' alike, through an email API instead
15
+ * of SMTP, with the provider adapters a site installs, such as @tansy/email-resend.
16
+ * Until the chosen provider's keys are set, mail goes through SMTP as before. See
17
+ * docs/plugins/email.md.
18
+ */
19
+ export declare function email(options: EmailOptions): import("tansy/plugin").CmsPlugin;
package/index.js ADDED
@@ -0,0 +1,188 @@
1
+ import { z } from "zod";
2
+ import { definePlugin, mergeMessagesByLanguage } from "tansy/plugin";
3
+ import { failureOf, isAddress, logDaysOf, MESSAGES, outgoing, senderOf } from "./logic";
4
+ import { COLLECTION_LABELS, FIELD_LABELS, messages } from "./messages";
5
+ import { ProviderError } from "./provider";
6
+ export { MESSAGES } from "./logic";
7
+ const PROVIDER_ID = /^[a-z][a-z0-9]{0,19}$/;
8
+ const optionsSchema = z.strictObject({
9
+ providers: z.array(z.object({ id: z.string().regex(PROVIDER_ID, "A provider's id is lowercase letters and digits."), label: z.string().min(1) }).loose()).min(1, "Add at least one provider, such as resend() from @tansy/email-resend."),
10
+ provider: z.string(),
11
+ }).superRefine((value, issues) => {
12
+ const ids = value.providers.map((provider) => provider.id);
13
+ const twice = ids.find((id, index) => ids.indexOf(id) !== index);
14
+ if (twice)
15
+ issues.addIssue({ code: "custom", path: ["providers"], message: `The provider "${twice}" is listed twice.` });
16
+ if (!ids.includes(value.provider))
17
+ issues.addIssue({ code: "custom", path: ["provider"], message: `"${value.provider}" isn't one of the providers listed.` });
18
+ });
19
+ const LOCKED = { createRule: null, updateRule: null, deleteRule: null };
20
+ const settingsOf = async (context) => (await context.settings.get());
21
+ /** Email's own settings. Each provider adds its own after them. */
22
+ const sharedSettings = (value, providers) => [
23
+ { name: "provider", type: "select", default: value.provider, label: "Provider", description: "Who sends the site's email. Fill in that provider's settings below. Until its keys are set, email goes through SMTP under Settings → Email.", options: providers.map((provider) => ({ value: provider.id, label: provider.label })) },
24
+ { name: "fromAddress", type: "text", default: "", maxLength: 254, label: "From address", description: "An address at a domain you've verified with the provider. Empty uses the one under Settings → Email." },
25
+ { name: "fromName", type: "text", default: "", maxLength: 100, label: "From name", description: "Empty uses the one under Settings → Email, then the site's name." },
26
+ { name: "replyTo", type: "text", default: "", maxLength: 254, label: "Reply-to address", description: "Where replies go, unless a message names its own, such as a form notification answering the visitor. Empty sends them to the from address." },
27
+ { name: "log", type: "boolean", default: true, label: "Keep a delivery log", description: "Lists each email's recipient, subject and whether the provider took it, under Email → Messages. Never the body, which can hold sign-in links and codes." },
28
+ { name: "logDays", type: "number", default: 30, min: 1, max: 365, integer: true, label: "Keep log entries for (days)" },
29
+ ];
30
+ /** Every setting's name starts with its provider's id, so two providers can't claim one. */
31
+ function providerSettings(providers) {
32
+ return providers.flatMap((provider) => provider.settings().map((field) => {
33
+ if (!field.name.startsWith(provider.id))
34
+ throw new Error(`Email provider "${provider.id}": the setting "${field.name}" must start with "${provider.id}".`);
35
+ return field;
36
+ }));
37
+ }
38
+ /** Writes a log entry. A failed write is only logged: the message has already gone, or already failed. */
39
+ async function logMessage(context, entry) {
40
+ try {
41
+ await context.system.records.create(MESSAGES, entry);
42
+ }
43
+ catch (error) {
44
+ console.error("[email] couldn't log a message", error);
45
+ }
46
+ }
47
+ /** Removes log entries older than the setting, a page at a time. */
48
+ async function forgetOldMessages(context) {
49
+ const before = new Date(Date.now() - logDaysOf(await settingsOf(context)) * 86_400_000).toISOString();
50
+ for (let round = 0; round < 50; round++) {
51
+ const { items } = await context.system.records.list(MESSAGES, { filter: `createdAt < "${before}"`, perPage: 200, fields: "id" });
52
+ if (!items.length)
53
+ return;
54
+ for (const { id } of items)
55
+ await context.system.records.delete(MESSAGES, id);
56
+ }
57
+ }
58
+ /**
59
+ * Sends the site's email, account email and plugins' alike, through an email API instead
60
+ * of SMTP, with the provider adapters a site installs, such as @tansy/email-resend.
61
+ * Until the chosen provider's keys are set, mail goes through SMTP as before. See
62
+ * docs/plugins/email.md.
63
+ */
64
+ export function email(options) {
65
+ const value = optionsSchema.parse({ provider: options.providers?.[0]?.id, ...Object.fromEntries(Object.entries(options).filter(([, option]) => option !== undefined)) });
66
+ const providers = options.providers;
67
+ const byId = new Map(providers.map((provider) => [provider.id, provider]));
68
+ const fields = [...sharedSettings(value, providers), ...providerSettings(providers)];
69
+ /** The chosen provider and the from address, or an error saying what to set up. */
70
+ async function sender(context, authSettings) {
71
+ const settings = await settingsOf(context);
72
+ const provider = byId.get(settings.provider);
73
+ if (!provider?.ready(settings))
74
+ throw new Error("[email] The provider isn't set up.");
75
+ const from = senderOf(settings, { ...authSettings.mail, appName: authSettings.general.appName });
76
+ if (!from)
77
+ throw new Error("[email] Set a from address under Email → Settings.");
78
+ return { settings, provider, from };
79
+ }
80
+ return definePlugin({
81
+ name: "email",
82
+ version: "0.1.0",
83
+ apiVersion: 1,
84
+ requires: { cms: "^0.1.0" },
85
+ admin: { server: "@tansy/email/admin" },
86
+ options: { schema: optionsSchema, value },
87
+ messages: mergeMessagesByLanguage(messages, ...providers.map((provider) => provider.messages)),
88
+ settings: { fields },
89
+ contract: {
90
+ [MESSAGES]: { recipient: "email", subject: "text", kind: "text", provider: "text", state: "text", providerId: "text", error: "text" },
91
+ },
92
+ auth: {
93
+ mail: {
94
+ async ready(context) {
95
+ const settings = await settingsOf(context);
96
+ const provider = byId.get(settings.provider);
97
+ if (!provider?.ready(settings))
98
+ return false;
99
+ // The fallback sender is checked when sending, as it lives in the auth settings.
100
+ return !settings.fromAddress || isAddress(settings.fromAddress.trim());
101
+ },
102
+ async send(message, authSettings, context) {
103
+ const { settings, provider, from } = await sender(context, authSettings);
104
+ const email = outgoing(message, from, settings);
105
+ if (!email)
106
+ throw new Error("[email] The recipient isn't an email address.");
107
+ const entry = { recipient: email.to, subject: email.subject, kind: (message.kind ?? "").slice(0, 100), provider: provider.id };
108
+ try {
109
+ const { id } = await provider.send(email, settings);
110
+ if (settings.log)
111
+ await logMessage(context, { ...entry, state: "sent", providerId: id ?? "" });
112
+ }
113
+ catch (error) {
114
+ if (settings.log)
115
+ await logMessage(context, { ...entry, state: "failed", error: failureOf(error) });
116
+ throw error;
117
+ }
118
+ },
119
+ async sendBatch(messages, authSettings, context) {
120
+ const { settings, provider, from } = await sender(context, authSettings);
121
+ const emails = messages.map((message) => outgoing(message, from, settings));
122
+ const ready = emails.filter((email) => email !== null);
123
+ const refusal = (error) => (error instanceof ProviderError ? error : new ProviderError(provider.label, null));
124
+ // Through the provider's batch API when it has one, else one call after another, as providers limit calls per second.
125
+ let answers = [];
126
+ if (provider.sendBatch)
127
+ answers = ready.length ? await provider.sendBatch(ready, settings).catch((error) => ready.map(() => refusal(error))) : [];
128
+ else
129
+ for (const email of ready)
130
+ answers.push(await provider.send(email, settings).catch(refusal));
131
+ let next = 0;
132
+ const results = emails.map((email, index) => {
133
+ if (!email)
134
+ return { ok: false, error: "not an address", entry: null };
135
+ const answer = answers[next++] ?? new ProviderError(provider.label, null);
136
+ const entry = { recipient: email.to, subject: email.subject, kind: (messages[index].kind ?? "").slice(0, 100), provider: provider.id };
137
+ return answer instanceof ProviderError || !("id" in answer)
138
+ ? { ok: false, error: failureOf(answer), entry: { ...entry, state: "failed", error: failureOf(answer) } }
139
+ : { ok: true, entry: { ...entry, state: "sent", providerId: answer.id ?? "" } };
140
+ });
141
+ if (settings.log)
142
+ for (const { entry } of results)
143
+ if (entry)
144
+ await logMessage(context, entry);
145
+ return results.map((result) => (result.ok ? { ok: true } : { ok: false, error: result.error }));
146
+ },
147
+ },
148
+ },
149
+ jobs: [{ name: "email-forget-messages", cron: "23 3 * * *", handler: forgetOldMessages }],
150
+ migrations: [
151
+ {
152
+ id: "001-messages",
153
+ up: async ({ schema }) => {
154
+ if (await schema.describe(MESSAGES))
155
+ throw new Error(`A collection called "${MESSAGES}" already exists, and the email plugin didn't create it. Rename it under Dashboard → Collections, then start again.`);
156
+ await schema.apply({
157
+ version: 1,
158
+ collections: [{
159
+ slug: MESSAGES,
160
+ name: "Messages",
161
+ description: "Each email the site sent through the provider, and whether the provider took it. Bodies are never kept: they can hold sign-in links and codes.",
162
+ // Only people with permissions on this collection see it. Only the plugin writes it.
163
+ rules: { listRule: null, viewRule: null, ...LOCKED },
164
+ fields: [
165
+ { name: "recipient", type: "email", config: { required: true } },
166
+ { name: "subject", type: "text", config: { maxLength: 300 } },
167
+ { name: "kind", type: "text", config: { maxLength: 100, description: "What sent it, such as auth:reset-password, plugin:blog or test." } },
168
+ { name: "provider", type: "text", config: { maxLength: 20 } },
169
+ { name: "state", type: "text", config: { required: true, maxLength: 20, description: "sent, when the provider took it, or failed." } },
170
+ { name: "providerId", type: "text", config: { maxLength: 255, description: "The provider's id for the message, to look it up there." } },
171
+ { name: "error", type: "text", config: { maxLength: 100, description: "Only the provider's status code, never what it said." } },
172
+ ],
173
+ }],
174
+ });
175
+ },
176
+ },
177
+ {
178
+ id: "002-names-in-languages",
179
+ up: async ({ schema }) => {
180
+ for (const [slug, labels] of Object.entries(COLLECTION_LABELS))
181
+ await schema.addLabels(slug, labels);
182
+ for (const [slug, fields] of Object.entries(FIELD_LABELS))
183
+ await schema.addFieldLabels(slug, fields);
184
+ },
185
+ },
186
+ ],
187
+ });
188
+ }
package/logic.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ import type { EmailSettings, OutgoingEmail } from "./provider";
2
+ export declare const MESSAGES = "email-messages";
3
+ export declare const isAddress: (value: string) => boolean;
4
+ /** A display name with line breaks and control characters taken out, so it can't start a new header. */
5
+ export declare const cleanName: (value: string) => string;
6
+ /** Who mail comes from: this plugin's sender, else the one under Settings → Email, else nothing. */
7
+ export declare function senderOf(settings: EmailSettings, fallback: {
8
+ fromAddress: string;
9
+ fromName: string;
10
+ appName: string;
11
+ }): {
12
+ address: string;
13
+ name: string;
14
+ } | null;
15
+ export declare function outgoing(message: {
16
+ to: string;
17
+ subject: string;
18
+ text: string;
19
+ html: string;
20
+ replyTo?: string;
21
+ headers?: Record<string, string>;
22
+ bulk?: boolean;
23
+ }, from: {
24
+ address: string;
25
+ name: string;
26
+ }, settings: EmailSettings): OutgoingEmail | null;
27
+ /** What the log keeps of a failure: the status, never the provider's words. */
28
+ export declare function failureOf(error: unknown): string;
29
+ /** Log entries are kept this many days. */
30
+ export declare const logDaysOf: (settings: EmailSettings) => number;
package/logic.js ADDED
@@ -0,0 +1,35 @@
1
+ export const MESSAGES = "email-messages";
2
+ const ADDRESS = /^[^\s@<>()",;:\\[\]]+@[^\s@<>()",;:\\[\]]+\.[^\s@<>()",;:\\[\]]+$/;
3
+ export const isAddress = (value) => value.length <= 254 && ADDRESS.test(value);
4
+ /** A display name with line breaks and control characters taken out, so it can't start a new header. */
5
+ export const cleanName = (value) => value.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, 100);
6
+ /** Who mail comes from: this plugin's sender, else the one under Settings → Email, else nothing. */
7
+ export function senderOf(settings, fallback) {
8
+ const address = [settings.fromAddress, fallback.fromAddress].map((value) => (typeof value === "string" ? value.trim() : "")).find(Boolean) ?? "";
9
+ if (!isAddress(address))
10
+ return null;
11
+ const name = cleanName([settings.fromName, fallback.fromName, fallback.appName].map((value) => (typeof value === "string" ? value.trim() : "")).find(Boolean) ?? "");
12
+ return { address, name };
13
+ }
14
+ /** One message from core as a provider takes it. Null when the recipient isn't an address. */
15
+ /** The only headers a message may carry to a provider, each one line. */
16
+ const HEADERS = new Set(["List-Unsubscribe", "List-Unsubscribe-Post"]);
17
+ export function outgoing(message, from, settings) {
18
+ const to = message.to.trim();
19
+ if (!isAddress(to))
20
+ return null;
21
+ // The message's own reply-to, such as a form's visitor, wins over the site-wide one.
22
+ const replyTo = [message.replyTo, settings.replyTo].map((value) => (typeof value === "string" ? value.trim() : "")).find((value) => value && isAddress(value)) ?? null;
23
+ const headers = Object.fromEntries(Object.entries(message.headers ?? {}).filter(([name, value]) => HEADERS.has(name) && typeof value === "string" && !/[\r\n]/.test(value)));
24
+ return { from, to, replyTo, subject: cleanName(message.subject).slice(0, 200) || "(no subject)", text: message.text, html: message.html, headers, bulk: message.bulk === true };
25
+ }
26
+ /** What the log keeps of a failure: the status, never the provider's words. */
27
+ export function failureOf(error) {
28
+ if (error && typeof error === "object" && error.name === "ProviderError") {
29
+ const status = error.status;
30
+ return typeof status === "number" ? `HTTP ${status}` : "unreachable";
31
+ }
32
+ return "error";
33
+ }
34
+ /** Log entries are kept this many days. */
35
+ export const logDaysOf = (settings) => (Number.isInteger(settings.logDays) && settings.logDays >= 1 ? Math.min(settings.logDays, 365) : 30);
package/messages.d.ts ADDED
@@ -0,0 +1,66 @@
1
+ /** The email plugin's dashboard words, read as `t("ext.email.<key>")`. Each provider package adds its own settings' words. */
2
+ export declare const messages: {
3
+ en: {
4
+ section: string;
5
+ settings: {
6
+ provider: {
7
+ label: string;
8
+ description: string;
9
+ };
10
+ fromAddress: {
11
+ label: string;
12
+ description: string;
13
+ };
14
+ fromName: {
15
+ label: string;
16
+ description: string;
17
+ };
18
+ replyTo: {
19
+ label: string;
20
+ description: string;
21
+ };
22
+ log: {
23
+ label: string;
24
+ description: string;
25
+ };
26
+ logDays: {
27
+ label: string;
28
+ };
29
+ };
30
+ };
31
+ ar: {
32
+ section: string;
33
+ settings: {
34
+ provider: {
35
+ label: string;
36
+ description: string;
37
+ };
38
+ fromAddress: {
39
+ label: string;
40
+ description: string;
41
+ };
42
+ fromName: {
43
+ label: string;
44
+ description: string;
45
+ };
46
+ replyTo: {
47
+ label: string;
48
+ description: string;
49
+ };
50
+ log: {
51
+ label: string;
52
+ description: string;
53
+ };
54
+ logDays: {
55
+ label: string;
56
+ };
57
+ };
58
+ };
59
+ };
60
+ /** The collection's name in other interface languages. Added by a migration, so a name the owner set stays. */
61
+ export declare const COLLECTION_LABELS: Record<string, Record<string, string>>;
62
+ /** The collection's fields in other interface languages, added the same way. */
63
+ export declare const FIELD_LABELS: Record<string, Record<string, {
64
+ labels?: Record<string, string>;
65
+ descriptions?: Record<string, string>;
66
+ }>>;
package/messages.js ADDED
@@ -0,0 +1,41 @@
1
+ /** The email plugin's dashboard words, read as `t("ext.email.<key>")`. Each provider package adds its own settings' words. */
2
+ export const messages = {
3
+ en: {
4
+ section: "Email",
5
+ settings: {
6
+ provider: { label: "Provider", description: "Who sends the site's email. Fill in that provider's settings below. Until its keys are set, email goes through SMTP under Settings → Email." },
7
+ fromAddress: { label: "From address", description: "An address at a domain you've verified with the provider. Empty uses the one under Settings → Email." },
8
+ fromName: { label: "From name", description: "Empty uses the one under Settings → Email, then the site's name." },
9
+ replyTo: { label: "Reply-to address", description: "Where replies go, unless a message names its own, such as a form notification answering the visitor. Empty sends them to the from address." },
10
+ log: { label: "Keep a delivery log", description: "Lists each email's recipient, subject and whether the provider took it, under Email → Messages. Never the body, which can hold sign-in links and codes." },
11
+ logDays: { label: "Keep log entries for (days)" },
12
+ },
13
+ },
14
+ ar: {
15
+ section: "البريد الإلكتروني",
16
+ settings: {
17
+ provider: { label: "المزوّد", description: "الجهة التي ترسل بريد الموقع. املأ إعدادات ذلك المزوّد أدناه. حتى تُضبط مفاتيحه، يُرسل البريد عبر SMTP من الإعدادات ← البريد الإلكتروني." },
18
+ fromAddress: { label: "عنوان المرسل", description: "عنوان في نطاق وثّقته لدى المزوّد. إن تُرك فارغًا يُستخدم العنوان في الإعدادات ← البريد الإلكتروني." },
19
+ fromName: { label: "اسم المرسل", description: "إن تُرك فارغًا يُستخدم الاسم في الإعدادات ← البريد الإلكتروني، ثم اسم الموقع." },
20
+ replyTo: { label: "عنوان الرد", description: "حيث تذهب الردود، ما لم تحدد الرسالة عنوانها، مثل إشعار نموذج يرد على الزائر. إن تُرك فارغًا تذهب إلى عنوان المرسل." },
21
+ log: { label: "احتفظ بسجل الإرسال", description: "يسرد مستلم كل رسالة وموضوعها وهل قبلها المزوّد، في البريد الإلكتروني ← الرسائل. لا يحفظ النص أبدًا، فقد يحوي روابط ورموز الدخول." },
22
+ logDays: { label: "احتفظ بسجلات الإرسال لمدة (أيام)" },
23
+ },
24
+ },
25
+ };
26
+ /** The collection's name in other interface languages. Added by a migration, so a name the owner set stays. */
27
+ export const COLLECTION_LABELS = {
28
+ "email-messages": { ar: "الرسائل" },
29
+ };
30
+ /** The collection's fields in other interface languages, added the same way. */
31
+ export const FIELD_LABELS = {
32
+ "email-messages": {
33
+ recipient: { labels: { ar: "المستلم" } },
34
+ subject: { labels: { ar: "الموضوع" } },
35
+ kind: { labels: { ar: "النوع" }, descriptions: { ar: "ما الذي أرسلها، مثل auth:reset-password أو plugin:blog أو test." } },
36
+ provider: { labels: { ar: "المزوّد" } },
37
+ state: { labels: { ar: "الحالة" }, descriptions: { ar: "sent حين قبلها المزوّد، أو failed." } },
38
+ providerId: { labels: { ar: "معرّف المزوّد" }, descriptions: { ar: "معرّف الرسالة لدى المزوّد، للبحث عنها هناك." } },
39
+ error: { labels: { ar: "الخطأ" }, descriptions: { ar: "رمز الحالة من المزوّد فقط، لا ما قاله أبدًا." } },
40
+ },
41
+ };
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@tansy/email",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Send Tansy's email through an email API instead of SMTP, with a delivery log. Add a provider package, such as @tansy/email-resend.",
5
+ "keywords": [
6
+ "tansy",
7
+ "tansy-plugin",
8
+ "cms",
9
+ "nextjs"
10
+ ],
11
+ "license": "MIT",
12
+ "author": "Mohamed Salah <mohamedsalahsebai@gmail.com>",
13
+ "homepage": "https://github.com/mhmdsalahsebai/tansy",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/mhmdsalahsebai/tansy.git",
17
+ "directory": "plugins/email"
18
+ },
19
+ "bugs": "https://github.com/mhmdsalahsebai/tansy/issues",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./index.d.ts",
23
+ "default": "./index.js"
24
+ },
25
+ "./admin": {
26
+ "types": "./admin.d.ts",
27
+ "default": "./admin.js"
28
+ },
29
+ "./provider": {
30
+ "types": "./provider.d.ts",
31
+ "default": "./provider.js"
32
+ }
33
+ },
34
+ "peerDependencies": {
35
+ "next": "^16.4.6",
36
+ "react": "^19.3.0",
37
+ "tansy": "^0.1.0"
38
+ },
39
+ "dependencies": {
40
+ "zod": "^4.6.7"
41
+ }
42
+ }
package/provider.d.ts ADDED
@@ -0,0 +1,85 @@
1
+ import type { Messages, PluginSettingField } from "tansy/plugin";
2
+ /**
3
+ * What an email provider adapter implements, such as @tansy/email-resend. Email keeps
4
+ * everything providers share: choosing one, the sender, the delivery log. An adapter only
5
+ * turns one message into one API call. See docs/plugins/email.md.
6
+ */
7
+ /** Email's own settings, and each installed provider's, by name. */
8
+ export interface EmailSettings {
9
+ /** The id of the provider sending mail. */
10
+ provider: string;
11
+ fromAddress: string;
12
+ fromName: string;
13
+ replyTo: string;
14
+ log: boolean;
15
+ logDays: number;
16
+ [name: string]: unknown;
17
+ }
18
+ /** One message, ready to send. Every address has been checked, and no value holds a line break where a header would break. */
19
+ export interface OutgoingEmail {
20
+ from: {
21
+ address: string;
22
+ name: string;
23
+ };
24
+ to: string;
25
+ replyTo: string | null;
26
+ subject: string;
27
+ text: string;
28
+ html: string;
29
+ /** Only List-Unsubscribe and List-Unsubscribe-Post, on mail sent to many. Send them as headers. Empty otherwise. */
30
+ headers: Record<string, string>;
31
+ /** Mail to many people at once, such as a newsletter. A provider with a separate bulk stream sends it there. */
32
+ bulk: boolean;
33
+ }
34
+ /** What became of one message of a batch: its id at the provider, or the refusal. */
35
+ export type BatchResult = {
36
+ id: string | null;
37
+ } | ProviderError;
38
+ export interface EmailProvider {
39
+ /** Lowercase letters and digits, such as "resend". Every setting's name starts with it. */
40
+ id: string;
41
+ label: string;
42
+ /** Its keys and options on Email → Settings. */
43
+ settings(): PluginSettingField[];
44
+ /**
45
+ * Its settings' words in other interface languages, by language code, as
46
+ * `{ ar: { settings: { <name>: { label, description } } } }`. Email adds them to its own
47
+ * `messages`, and the setting's `label` and `description` cover any language missing.
48
+ */
49
+ messages?: Record<string, Messages>;
50
+ /** Whether the keys it needs are set. */
51
+ ready(settings: EmailSettings): boolean;
52
+ /** Sends one message. Returns the provider's id for it, when it gives one. Throw `ProviderError` on a refusal. */
53
+ send(email: OutgoingEmail, settings: EmailSettings): Promise<{
54
+ id: string | null;
55
+ }>;
56
+ /**
57
+ * Sends up to 100 messages in one call, through the provider's batch API, and answers for
58
+ * each in order. Throw `ProviderError` when the whole call is refused. Email sends one at a
59
+ * time when it's left out.
60
+ */
61
+ sendBatch?(emails: OutgoingEmail[], settings: EmailSettings): Promise<BatchResult[]>;
62
+ }
63
+ /** Types an adapter. */
64
+ export declare const defineEmailProvider: (provider: EmailProvider) => EmailProvider;
65
+ /**
66
+ * A provider refused or failed to take a message. Only the status reaches the message and
67
+ * the log: a provider's answer can quote the site's account, keys or the recipient.
68
+ */
69
+ export declare class ProviderError extends Error {
70
+ readonly provider: string;
71
+ readonly status: number | null;
72
+ constructor(provider: string, status: number | null);
73
+ }
74
+ /**
75
+ * Calls a provider's API and returns its JSON answer, or `{}` when it has none. Times out
76
+ * after 15 seconds. Anything but a 2xx throws a `ProviderError` with only the status.
77
+ */
78
+ export declare function callProvider(provider: string, url: string, init: RequestInit, fetcher?: typeof fetch): Promise<Record<string, unknown>>;
79
+ /** "Name <address>", quoting the name when it needs it. */
80
+ export declare function mailbox({ address, name }: {
81
+ address: string;
82
+ name: string;
83
+ }): string;
84
+ export declare const str: (value: unknown) => string;
85
+ export declare const idOf: (value: unknown) => string | null;
package/provider.js ADDED
@@ -0,0 +1,52 @@
1
+ /** Types an adapter. */
2
+ export const defineEmailProvider = (provider) => provider;
3
+ /**
4
+ * A provider refused or failed to take a message. Only the status reaches the message and
5
+ * the log: a provider's answer can quote the site's account, keys or the recipient.
6
+ */
7
+ export class ProviderError extends Error {
8
+ provider;
9
+ status;
10
+ constructor(provider, status) {
11
+ super(status ? `${provider} answered ${status}` : `${provider} couldn't be reached`);
12
+ this.provider = provider;
13
+ this.status = status;
14
+ this.name = "ProviderError";
15
+ }
16
+ }
17
+ const TIMEOUT_MS = 15_000;
18
+ /**
19
+ * Calls a provider's API and returns its JSON answer, or `{}` when it has none. Times out
20
+ * after 15 seconds. Anything but a 2xx throws a `ProviderError` with only the status.
21
+ */
22
+ export async function callProvider(provider, url, init, fetcher = fetch) {
23
+ let response;
24
+ try {
25
+ response = await fetcher(url, { ...init, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
26
+ }
27
+ catch {
28
+ throw new ProviderError(provider, null);
29
+ }
30
+ if (!response.ok) {
31
+ // Read and dropped, so the connection can be reused. What it said stays out of logs.
32
+ await response.body?.cancel().catch(() => { });
33
+ throw new ProviderError(provider, response.status);
34
+ }
35
+ const body = await response.text().catch(() => "");
36
+ try {
37
+ const parsed = body ? JSON.parse(body) : {};
38
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
39
+ }
40
+ catch {
41
+ return {};
42
+ }
43
+ }
44
+ /** "Name <address>", quoting the name when it needs it. */
45
+ export function mailbox({ address, name }) {
46
+ if (!name)
47
+ return address;
48
+ const plain = /^[A-Za-z0-9 !#$%&'*+\-/=?^_`{|}~]+$/.test(name);
49
+ return `${plain ? name : `"${name.replace(/["\\]/g, "\\$&")}"`} <${address}>`;
50
+ }
51
+ export const str = (value) => (typeof value === "string" ? value.trim() : "");
52
+ export const idOf = (value) => (typeof value === "string" && value ? value.slice(0, 255) : null);