sendrly
Version:
Official Sendrly TypeScript/JavaScript SDK - Simple, type-safe email automation for developers
55 lines (54 loc) • 1.57 kB
JavaScript
import { z } from 'zod';
/**
* Email validation regex
* This matches the regex used in the edge functions
*/
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
/**
* Event payload schema that matches the Edge Function payload structure
*/
export const eventPayloadSchema = z
.object({
contact: z.object({
email: z
.string()
.min(1, 'Email is required')
.transform((email) => email.toLowerCase().trim())
.pipe(z.string().regex(EMAIL_REGEX, 'Invalid email format')),
marketing_opt_out: z.boolean().optional().default(false),
properties: z.record(z.unknown()).optional().default({})
}),
event: z.object({
name: z.string().min(1, 'Event name is required'),
properties: z.record(z.unknown()).optional().default({})
})
})
.strict();
/**
* Validate the user-provided payload
* This is the main validation function used by the SDK
*/
export function validatePayload(payload) {
try {
return eventPayloadSchema.parse(payload);
}
catch (error) {
if (error instanceof z.ZodError) {
const formattedError = formatValidationError(error);
throw new Error(`Validation failed:\n${formattedError}`);
}
throw error;
}
}
/**
* Format validation errors into a readable string
* @internal
*/
export const formatValidationError = (error) => {
return error.errors
.map((err) => {
const path = err.path.join('.');
return `${path}: ${err.message}`;
})
.join('\n');
};