import { Option, ParseResult } from 'effect' import { schemaPathToFieldPath } from './path' export interface FormError { readonly path: string readonly message: string } export type FormErrors = Readonly> export const error = (path: string, message: string): FormError => ({ path, message }) export const normalizeErrors = ( value: void | FormError | ReadonlyArray, ): ReadonlyArray => { if (value === undefined) return [] if (Array.isArray(value)) return value as ReadonlyArray return [value as FormError] } export const errorsToRecord = (errors: ReadonlyArray): FormErrors => { const out: Record = {} for (const entry of errors) { if (out[entry.path] === undefined) out[entry.path] = entry.message } return out } export const routeParseError = (parseError: ParseResult.ParseError): FormErrors => { const formatted = ParseResult.ArrayFormatter.formatErrorSync(parseError) const out: Record = {} for (const issue of formatted) { const path = schemaPathToFieldPath(issue.path) if (out[path] === undefined) out[path] = issue.message } return out } export const firstError = (errors: FormErrors, path: string): Option.Option => { const message = errors[path] return message === undefined ? Option.none() : Option.some(message) }