/** * @fileoverview CON-04 Runtime Validation - Payload Validation * @description Centralized validation function using Zod schemas * @version 0.18.4 */ import { z, ZodSchema } from "zod"; import { ValidationError } from "../utils/errors"; /** * Validates a payload against a Zod schema and returns the parsed result * Throws a ValidationError if validation fails * * @param schema - Zod schema to validate against * @param data - Unknown data to validate * @returns Parsed and validated data * @throws {ValidationError} if validation fails * * @example * ```typescript * const userSchema = z.object({ * id: z.string(), * email: z.string().email(), * name: z.string() * }); * * const userData = { id: "123", email: "user@example.com", name: "John" }; * const validUser = validatePayload(userSchema, userData); * // validUser is now typed as { id: string, email: string, name: string } * ``` */ export function validatePayload( schema: ZodSchema, data: unknown ): T { try { return schema.parse(data); } catch (err) { if (err instanceof z.ZodError) { throw new ValidationError( "Payload validation failed", "PAYLOAD_VALIDATION_ERROR", err, { zodError: err.format(), schemaName: schema._def?.description || 'Unknown schema' } ); } throw new ValidationError( "Payload validation failed with unknown error", "PAYLOAD_VALIDATION_ERROR", err instanceof Error ? err : undefined, { schemaName: schema._def?.description || 'Unknown schema', originalError: err } ); } } /** * Safely validates a payload and returns a result object * Does not throw - useful for optional validation or graceful degradation * * @param schema - Zod schema to validate against * @param data - Unknown data to validate * @returns Validation result with success flag and data/error * * @example * ```typescript * const result = safeValidatePayload(userSchema, inputData); * if (result.success) { * // result.data is properly typed * console.log(result.data.email); * } else { * // result.error contains the ZodError * console.error(result.error.format()); * } * ``` */ export function safeValidatePayload( schema: ZodSchema, data: unknown ): { success: true; data: T } | { success: false; error: z.ZodError } { const result = schema.safeParse(data); if (result.success) { return { success: true, data: result.data }; } return { success: false, error: result.error }; }