import { day } from '@vrplatform/utils'; import * as z from 'zod'; const postmarkErrorCodeSchema = z.number().int().nonnegative(); const postmarkResponseErrorCodeSchema = z .object({ ErrorCode: postmarkErrorCodeSchema }) .transform(({ ErrorCode }) => ErrorCode); const postmarkHeaderErrorCodeSchema = z .string() .regex(/^\d+$/) .transform(Number) .pipe(postmarkErrorCodeSchema); const postmarkSuccessResponseSchema = z.object({ ErrorCode: z.literal(0), MessageID: z.string().min(1), SubmittedAt: z.string().refine((value) => day(value).isValid()), }); function parseOptional(schema: z.ZodType, value: unknown) { const result = schema.safeParse(value); if (result.success) return result.data; } type EmailDeliveryFailureDetails = { httpStatus: number; postmarkErrorCode?: number; provider: 'postmark'; providerCategory: 'inactiveRecipient' | 'rejected'; }; type EmailDeliveryErrorDetails = | EmailDeliveryFailureDetails | { failureCount: number; failures: EmailDeliveryFailureDetails[]; }; export class EmailDeliveryError extends Error { constructor( message: string, public readonly details?: EmailDeliveryErrorDetails, public readonly expected = false, public readonly retryable = true ) { super(message); this.name = 'EmailDeliveryError'; } } /** * Formats a verified sender address with a display name for the From header. * Registrations store bare addresses; recipients should still see the company * name the way they see `VRPlatform `. */ export function formatSenderIdentity( name: string | null | undefined, address: string ) { const display = (name ?? '').replace(/[\r\n"<>]/g, '').trim(); return display ? `"${display}" <${address}>` : address; } export async function sendEmail( data: { to: string; subject: string; text: string; html: string; replyTo?: string; tag?: string; metadata?: Record; from?: string; headers?: Record; }, options: { fetch?: ( input: string | URL | Request, init?: RequestInit ) => Promise; postmarkToken?: string; } ) { if (!options.postmarkToken) { throw new EmailDeliveryError( 'Postmark is not configured', undefined, false, false ); } const response = await (options.fetch ?? fetch)( 'https://api.postmarkapp.com/email', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-Postmark-Server-Token': options.postmarkToken, }, body: JSON.stringify({ From: data.from ?? 'VRPlatform ', To: data.to, Subject: data.subject, ReplyTo: data.replyTo, TextBody: data.text, HtmlBody: data.html, MessageStream: 'outbound', Tag: data.tag, Metadata: data.metadata, Headers: data.headers ? Object.entries(data.headers).map(([Name, Value]) => ({ Name, Value, })) : undefined, }), } ); const providerResponse: unknown = await response.json().catch(() => ({})); const postmarkErrorCode = parseOptional(postmarkResponseErrorCodeSchema, providerResponse) ?? parseOptional( postmarkHeaderErrorCodeSchema, response.headers.get('X-PM-ApiErrorCode') ); if ( !response.ok || (postmarkErrorCode !== undefined && postmarkErrorCode !== 0) ) { const inactiveRecipient = response.status === 422 && postmarkErrorCode === 406; const details: EmailDeliveryFailureDetails = { provider: 'postmark', providerCategory: inactiveRecipient ? 'inactiveRecipient' : 'rejected', httpStatus: response.status, ...(postmarkErrorCode !== undefined ? { postmarkErrorCode } : {}), }; if (inactiveRecipient) { throw new EmailDeliveryError( 'Postmark recipient is inactive', details, true, false ); } throw new EmailDeliveryError( 'Postmark rejected the email', details, false, response.status === 429 || response.status >= 500 ); } const result = postmarkSuccessResponseSchema.safeParse(providerResponse); if (!result.success) { throw new EmailDeliveryError('Postmark returned an invalid response', { provider: 'postmark', providerCategory: 'rejected', httpStatus: response.status, ...(postmarkErrorCode !== undefined ? { postmarkErrorCode } : {}), }); } return { httpStatus: response.status, messageId: result.data.MessageID, submittedAt: result.data.SubmittedAt, }; } export async function settleEmailDeliveries(deliveries: Promise[]) { const failures = (await Promise.allSettled(deliveries)).filter( (result) => result.status === 'rejected' ); if (failures.length === 0) return; const unexpectedDeliveryError = failures.find( (failure) => failure.reason instanceof EmailDeliveryError && !failure.reason.expected )?.reason; const allExpected = failures.every( (failure) => failure.reason instanceof EmailDeliveryError && failure.reason.expected ); const firstDeliveryError = failures.find( (failure) => failure.reason instanceof EmailDeliveryError )?.reason; const failureDetails = failures.flatMap((failure) => { if ( !(failure.reason instanceof EmailDeliveryError) || !failure.reason.details || !('provider' in failure.reason.details) ) { return []; } const { httpStatus, postmarkErrorCode, provider, providerCategory } = failure.reason.details; return [ { httpStatus, provider, providerCategory, ...(postmarkErrorCode !== undefined ? { postmarkErrorCode } : {}), }, ]; }); const details: EmailDeliveryErrorDetails = { failureCount: failures.length, failures: failureDetails, }; if (unexpectedDeliveryError instanceof EmailDeliveryError) { if (unexpectedDeliveryError.message === 'Postmark is not configured') { throw new EmailDeliveryError( 'Postmark is not configured', details, false, false ); } throw new EmailDeliveryError( 'Postmark rejected the email', details, false, unexpectedDeliveryError.retryable ); } if (allExpected && firstDeliveryError instanceof EmailDeliveryError) { throw new EmailDeliveryError( 'Postmark recipient is inactive', details, true, false ); } throw new EmailDeliveryError('Email delivery failed', details); }