|
| 1 | +import { PartialDeep } from 'type-fest'; |
| 2 | +import type { TypedSchema, TypedSchemaError } from 'vee-validate'; |
| 3 | +import { Output, Input, BaseSchema, safeParseAsync, parse, Issue } from 'valibot'; |
| 4 | +import { normalizeFormPath } from '../../shared'; |
| 5 | + |
| 6 | +export function toTypedSchema< |
| 7 | + TSchema extends BaseSchema, |
| 8 | + TOutput = Output<TSchema>, |
| 9 | + TInput = PartialDeep<Input<TSchema>>, |
| 10 | +>(valibotSchema: TSchema): TypedSchema<TInput, TOutput> { |
| 11 | + const schema: TypedSchema = { |
| 12 | + __type: 'VVTypedSchema', |
| 13 | + async parse(value) { |
| 14 | + const result = await safeParseAsync(valibotSchema, value); |
| 15 | + if (result.success) { |
| 16 | + return { |
| 17 | + value: result.data, |
| 18 | + errors: [], |
| 19 | + }; |
| 20 | + } |
| 21 | + |
| 22 | + const errors: Record<string, TypedSchemaError> = {}; |
| 23 | + processIssues(result.error.issues, errors); |
| 24 | + |
| 25 | + return { |
| 26 | + errors: Object.values(errors), |
| 27 | + }; |
| 28 | + }, |
| 29 | + cast(values) { |
| 30 | + try { |
| 31 | + return parse(valibotSchema, values); |
| 32 | + } catch { |
| 33 | + return values; |
| 34 | + } |
| 35 | + }, |
| 36 | + }; |
| 37 | + |
| 38 | + return schema; |
| 39 | +} |
| 40 | + |
| 41 | +function processIssues(issues: Issue[], errors: Record<string, TypedSchemaError>): void { |
| 42 | + issues.forEach(issue => { |
| 43 | + const path = normalizeFormPath((issue.path || []).map(p => p.key).join('.')); |
| 44 | + if (issue.issues?.length) { |
| 45 | + processIssues( |
| 46 | + issue.issues.flatMap(ue => ue.issues || []), |
| 47 | + errors, |
| 48 | + ); |
| 49 | + |
| 50 | + if (!path) { |
| 51 | + return; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + if (!errors[path]) { |
| 56 | + errors[path] = { errors: [], path }; |
| 57 | + } |
| 58 | + |
| 59 | + errors[path].errors.push(issue.message); |
| 60 | + }); |
| 61 | +} |
0 commit comments