UNPKG

@conform-to/zod

Version:

Conform helpers for integrating with Zod

61 lines (58 loc) 2.02 kB
import { parse, formatPaths } from '@conform-to/dom'; import { coerceFormValue } from './coercion.mjs'; function getError(zodError, formatError) { var result = {}; for (var issue of zodError.errors) { var name = formatPaths(issue.path); switch (issue.message) { case conformZodMessage.VALIDATION_UNDEFINED: return null; case conformZodMessage.VALIDATION_SKIPPED: result[name] = null; break; default: { var _issues = result[name]; if (_issues !== null) { if (_issues) { result[name] = _issues.concat(issue); } else { result[name] = [issue]; } } break; } } } return Object.entries(result).reduce((result, _ref) => { var [name, issues] = _ref; result[name] = issues ? formatError(issues) : null; return result; }, {}); } function parseWithZod(payload, options) { return parse(payload, { resolve(payload, intent) { var errorMap = options.errorMap; var baseSchema = typeof options.schema === 'function' ? options.schema(intent) : options.schema; var schema = !options.disableAutoCoercion ? coerceFormValue(baseSchema) : baseSchema; var resolveSubmission = result => { var _options$formatError; return { value: result.success ? result.data : undefined, error: !result.success ? getError(result.error, (_options$formatError = options.formatError) !== null && _options$formatError !== void 0 ? _options$formatError : issues => issues.map(issue => issue.message)) : undefined }; }; return options.async ? schema.safeParseAsync(payload, { errorMap }).then(result => resolveSubmission(result)) : resolveSubmission(schema.safeParse(payload, { errorMap })); } }); } var conformZodMessage = { VALIDATION_SKIPPED: '__skipped__', VALIDATION_UNDEFINED: '__undefined__' }; export { conformZodMessage, parseWithZod };