Files
HiveGrid-Wireframes/hivegrid-cloud/packages/mail/src/mailjet.ts
T

477 lines
15 KiB
TypeScript

import { MailProviderError, type MailAddress, type MailAddressInput, type MailProvider, type SendMailInput, type SendMailResult } from "./types.js";
export const mailjetApiBaseUrl = "https://api.mailjet.com";
const DEFAULT_MAILJET_TIMEOUT_MS = 10_000;
const DEFAULT_RESPONSE_BODY_LIMIT_BYTES = 4_096;
type Fetch = typeof fetch;
type MailjetAddress = {
Email: string;
Name?: string;
};
type MailjetAttachment = {
ContentType: string;
Filename: string;
Base64Content: string;
ContentID?: string;
};
type MailjetMessage = {
From: MailjetAddress;
To: MailjetAddress[];
Cc?: MailjetAddress[];
Bcc?: MailjetAddress[];
ReplyTo?: MailjetAddress;
Subject?: string;
TextPart?: string;
HTMLPart?: string;
TemplateID?: number;
TemplateLanguage?: boolean;
Variables?: Record<string, unknown>;
Attachments?: MailjetAttachment[];
InlinedAttachments?: MailjetAttachment[];
Headers?: Record<string, string>;
CustomCampaign?: string;
TrackOpens?: "enabled" | "disabled";
TrackClicks?: "enabled" | "disabled";
CustomID?: string;
};
type MailjetSendRequest = {
Messages: MailjetMessage[];
SandboxMode?: boolean;
};
export type MailMetricsHook = (input: { provider: "mailjet"; status: "delivered" | "failed" }) => void;
export type MailjetProviderOptions = {
apiKey: string;
secretKey: string;
fromEmail: string;
fromName?: string;
baseUrl?: string;
fetch?: Fetch;
timeoutMs?: number;
responseBodyLimitBytes?: number;
/**
* When true, the request is sent with Mailjet's `SandboxMode` flag so the
* payload is validated (auth, addresses, mapping) without actually
* delivering mail. Wire this to a staging/test toggle — never enable in
* production paths.
*/
sandbox?: boolean;
/**
* Optional hook invoked once per send (`status: "delivered"` on HTTP 2xx
* with all messages accepted, `"failed"` otherwise). The hook MUST NOT throw
* — the provider wraps it in a try/catch so a misbehaving hook can't block
* mail delivery. Wire to mail_sent_total in the host app's metrics package.
*/
onMetric?: MailMetricsHook;
};
export type MailjetEnv = Record<string, string | undefined> & {
MAILJET_API_KEY?: string;
MAILJET_SECRET_KEY?: string;
MAILJET_FROM_EMAIL?: string;
MAILJET_FROM_NAME?: string;
};
export class MailjetProvider implements MailProvider {
readonly id = "mailjet" as const;
private readonly authorization: string;
private readonly defaultFrom: MailAddress;
private readonly baseUrl: string;
private readonly fetchImpl: Fetch;
private readonly timeoutMs: number;
private readonly responseBodyLimitBytes: number;
private readonly sandbox: boolean;
private readonly onMetric: MailMetricsHook | undefined;
constructor(options: MailjetProviderOptions) {
const apiKey = requireNonEmpty(options.apiKey, "MAILJET_API_KEY");
const secretKey = requireNonEmpty(options.secretKey, "MAILJET_SECRET_KEY");
this.authorization = `Basic ${Buffer.from(`${apiKey}:${secretKey}`, "utf8").toString("base64")}`;
this.defaultFrom = {
email: requireNonEmpty(options.fromEmail, "MAILJET_FROM_EMAIL"),
...(options.fromName ? { name: options.fromName } : {}),
};
this.baseUrl = (options.baseUrl ?? mailjetApiBaseUrl).replace(/\/+$/, "");
this.fetchImpl = options.fetch ?? fetch;
this.timeoutMs = normalizePositiveInteger(options.timeoutMs, DEFAULT_MAILJET_TIMEOUT_MS);
this.responseBodyLimitBytes = normalizePositiveInteger(options.responseBodyLimitBytes, DEFAULT_RESPONSE_BODY_LIMIT_BYTES);
this.sandbox = options.sandbox ?? false;
this.onMetric = options.onMetric;
}
private emitMetric(status: "delivered" | "failed"): void {
if (!this.onMetric) return;
try {
this.onMetric({ provider: "mailjet", status });
} catch {
// Metric hook must never abort the send flow.
}
}
async send(input: SendMailInput): Promise<SendMailResult> {
const payload = toMailjetSendRequest(input, this.defaultFrom, this.sandbox);
let response: Response;
try {
response = await fetchWithTimeout(
this.fetchImpl,
`${this.baseUrl}/v3.1/send`,
{
method: "POST",
headers: {
Authorization: this.authorization,
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(payload),
},
this.timeoutMs,
);
} catch (error) {
this.emitMetric("failed");
if (isAbortError(error)) {
throw new MailProviderError("Mailjet email request timed out.", { provider: this.id });
}
throw error;
}
const responseBody = await parseResponseBody(response, this.responseBodyLimitBytes);
if (!response.ok) {
this.emitMetric("failed");
throw new MailProviderError(`Mailjet email request failed with ${response.status}.`, {
provider: this.id,
statusCode: response.status,
responseBody,
});
}
// Mailjet returns HTTP 200 even when individual messages fail; the
// per-message Status carries the real outcome.
const messages = extractMessages(responseBody);
const rejected = messages.find((message) => typeof message.Status === "string" && message.Status.toLowerCase() !== "success");
if (rejected) {
this.emitMetric("failed");
throw new MailProviderError("Mailjet rejected at least one message.", {
provider: this.id,
statusCode: response.status,
responseBody,
});
}
this.emitMetric("delivered");
return {
provider: this.id,
status: "queued",
messageId: extractMessageId(messages),
};
}
}
export function createMailjetProvider(options: MailjetProviderOptions): MailProvider {
return new MailjetProvider(options);
}
export function createMailjetProviderFromEnv(env: MailjetEnv, options?: { onMetric?: MailMetricsHook; sandbox?: boolean }): MailProvider {
return new MailjetProvider({
apiKey: requireNonEmpty(env.MAILJET_API_KEY, "MAILJET_API_KEY"),
secretKey: requireNonEmpty(env.MAILJET_SECRET_KEY, "MAILJET_SECRET_KEY"),
fromEmail: requireNonEmpty(env.MAILJET_FROM_EMAIL, "MAILJET_FROM_EMAIL"),
fromName: env.MAILJET_FROM_NAME,
...(options?.onMetric ? { onMetric: options.onMetric } : {}),
...(options?.sandbox ? { sandbox: options.sandbox } : {}),
});
}
function toMailjetSendRequest(input: SendMailInput, defaultFrom: MailAddress, sandbox: boolean): MailjetSendRequest {
if (input.to.length === 0) {
throw new MailProviderError("At least one recipient is required.", { provider: "mailjet" });
}
if (!input.text && !input.html && !input.templateId) {
throw new MailProviderError("Email text, html or templateId is required.", { provider: "mailjet" });
}
const template = normalizeTemplateId(input.templateId);
const { attachments, inlined } = normalizeAttachments(input.attachments);
const headers = buildHeaders(input);
const baseMessage = compactObject<MailjetMessage>({
From: normalizeAddress(input.from ?? defaultFrom),
To: [],
Cc: input.cc?.map(normalizeAddress),
Bcc: input.bcc?.map(normalizeAddress),
ReplyTo: input.replyTo ? normalizeAddress(input.replyTo) : undefined,
Subject: input.subject,
TextPart: input.text,
HTMLPart: input.html,
TemplateID: template,
TemplateLanguage: template !== undefined ? true : undefined,
Attachments: attachments,
InlinedAttachments: inlined,
Headers: headers,
CustomCampaign: input.tags?.[0],
TrackOpens: toTrackingFlag(input.settings?.trackOpens),
TrackClicks: toTrackingFlag(input.settings?.trackClicks),
CustomID: normalizeCustomId(input.idempotencyKey),
});
const personalization = new Map((input.personalization ?? []).map((entry) => [entry.email, entry.data]));
let messages: MailjetMessage[];
if (personalization.size > 1) {
// Per-recipient Variables require one Mailjet message each. Cc/Bcc are
// attached only to the first message so shared recipients aren't copied
// once per personalized message.
messages = input.to.map((addr, index) => {
const recipient = normalizeAddress(addr);
const variables = personalization.get(recipient.Email);
return compactObject<MailjetMessage>({
...baseMessage,
...(index > 0 ? { Cc: undefined, Bcc: undefined } : {}),
To: [recipient],
Variables: variables,
});
});
} else {
messages = [
compactObject<MailjetMessage>({
...baseMessage,
To: input.to.map(normalizeAddress),
Variables: input.personalization?.[0]?.data,
}),
];
}
return compactObject<MailjetSendRequest>({
Messages: messages,
SandboxMode: sandbox ? true : undefined,
});
}
function normalizeAddress(address: MailAddressInput): MailjetAddress {
if (typeof address === "string") {
return { Email: address };
}
return compactObject<MailjetAddress>({
Email: address.email,
Name: address.name,
});
}
function normalizeTemplateId(templateId: string | undefined): number | undefined {
if (templateId === undefined) {
return undefined;
}
const numeric = Number(templateId);
if (!Number.isFinite(numeric)) {
throw new MailProviderError("Mailjet TemplateID must be numeric.", { provider: "mailjet" });
}
return numeric;
}
function normalizeAttachments(attachments: SendMailInput["attachments"]): { attachments?: MailjetAttachment[]; inlined?: MailjetAttachment[] } {
if (!attachments?.length) {
return {};
}
const regular: MailjetAttachment[] = [];
const inlined: MailjetAttachment[] = [];
for (const attachment of attachments) {
const mapped = compactObject<MailjetAttachment>({
ContentType: guessContentType(attachment.filename),
Filename: attachment.filename,
Base64Content: attachment.content,
ContentID: attachment.disposition === "inline" ? attachment.id ?? attachment.filename : undefined,
});
if (attachment.disposition === "inline") {
inlined.push(mapped);
} else {
regular.push(mapped);
}
}
return {
...(regular.length ? { attachments: regular } : {}),
...(inlined.length ? { inlined } : {}),
};
}
function buildHeaders(input: SendMailInput): Record<string, string> | undefined {
const headers: Record<string, string> = {};
for (const header of input.headers ?? []) {
headers[header.name] = header.value;
}
if (input.inReplyTo) {
headers["In-Reply-To"] = input.inReplyTo;
}
if (input.references?.length) {
headers["References"] = input.references.join(" ");
}
if (input.listUnsubscribe) {
headers["List-Unsubscribe"] = input.listUnsubscribe;
}
if (input.precedenceBulk) {
headers["Precedence"] = "bulk";
}
return Object.keys(headers).length > 0 ? headers : undefined;
}
function toTrackingFlag(value: boolean | undefined): "enabled" | "disabled" | undefined {
if (value === undefined) {
return undefined;
}
return value ? "enabled" : "disabled";
}
function normalizeCustomId(idempotencyKey: string | undefined): string | undefined {
if (!idempotencyKey) {
return undefined;
}
// Mailjet caps CustomID at 100 characters.
return idempotencyKey.slice(0, 100);
}
type MailjetResponseMessage = {
Status?: string;
To?: Array<{ MessageUUID?: string; MessageID?: number; MessageHref?: string }>;
};
function extractMessages(responseBody: unknown): MailjetResponseMessage[] {
if (responseBody && typeof responseBody === "object" && "Messages" in responseBody) {
const messages = (responseBody as { Messages?: unknown }).Messages;
if (Array.isArray(messages)) {
return messages as MailjetResponseMessage[];
}
}
return [];
}
function extractMessageId(messages: MailjetResponseMessage[]): string | undefined {
const recipient = messages[0]?.To?.[0];
if (!recipient) {
return undefined;
}
return recipient.MessageUUID ?? (recipient.MessageID !== undefined ? String(recipient.MessageID) : undefined);
}
function guessContentType(filename: string): string {
const extension = filename.includes(".") ? filename.slice(filename.lastIndexOf(".") + 1).toLowerCase() : "";
return CONTENT_TYPE_BY_EXTENSION[extension] ?? "application/octet-stream";
}
const CONTENT_TYPE_BY_EXTENSION: Record<string, string> = {
pdf: "application/pdf",
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
gif: "image/gif",
svg: "image/svg+xml",
csv: "text/csv",
txt: "text/plain",
html: "text/html",
ics: "text/calendar",
json: "application/json",
xml: "application/xml",
zip: "application/zip",
doc: "application/msword",
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
xls: "application/vnd.ms-excel",
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
};
function requireNonEmpty(value: string | undefined, name: string): string {
if (!value?.trim()) {
throw new MailProviderError(`${name} is required for Mailjet email delivery.`, { provider: "mailjet" });
}
return value;
}
function compactObject<T extends Record<string, unknown>>(value: T): T {
return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as T;
}
async function parseResponseBody(response: Response, limitBytes: number): Promise<unknown> {
const text = await readLimitedResponseText(response, limitBytes);
if (!text) {
return undefined;
}
try {
return JSON.parse(text);
} catch {
return text;
}
}
async function fetchWithTimeout(fetchImpl: Fetch, input: Parameters<Fetch>[0], init: RequestInit, timeoutMs: number): Promise<Response> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
return await fetchImpl(input, { ...init, signal: controller.signal });
} finally {
clearTimeout(timeout);
}
}
async function readLimitedResponseText(response: Response, limitBytes: number): Promise<string> {
if (!response.body) {
return "";
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
const chunks: string[] = [];
let bytes = 0;
while (bytes < limitBytes) {
const result = await reader.read();
if (result.done) {
chunks.push(decoder.decode());
return chunks.join("");
}
const chunk = result.value;
const remaining = limitBytes - bytes;
const slice = chunk.byteLength > remaining ? chunk.slice(0, remaining) : chunk;
chunks.push(decoder.decode(slice, { stream: chunk.byteLength <= remaining }));
bytes += slice.byteLength;
if (chunk.byteLength > remaining) {
await reader.cancel();
break;
}
}
chunks.push(decoder.decode());
return chunks.join("");
}
function normalizePositiveInteger(value: number | undefined, fallback: number): number {
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : fallback;
}
function isAbortError(error: unknown) {
return error instanceof Error && error.name === "AbortError";
}