import type { FieldElement, Issue, PathSegment, ValidationResponse } from './definitions'; import type { StandardSchemaV1 } from '@standard-schema/spec'; export function isValidationSchema(schema: unknown): schema is StandardSchemaV1 { return ( schema !== undefined && typeof schema === 'object' && (schema as Partial)['~standard'] !== undefined ); } export async function validateSchema( data: unknown, schema: StandardSchemaV1 ): Promise> { return await schema['~standard'].validate(data); } export function normalizePathSegment(segment: PropertyKey | PathSegment): PropertyKey { return typeof segment === 'object' ? segment.key : segment; } export function transformSchemaPath( path: (PropertyKey | PathSegment)[] | undefined ): string | undefined { return path === undefined ? undefined : path .map((segment) => normalizePathSegment(segment)) .map((segment) => { return typeof segment === 'number' ? `[${segment}]` : segment; }) .join('.') .replaceAll('.[', '['); } export function transformValidationResponse(response: ValidationResponse): Issue[] { const responses = Array.isArray(response) ? response : [response]; const issues = responses .filter((r) => r !== undefined) .map((r): Issue => { if (typeof r === 'string') { return { message: r }; } return r; }); return issues; } export function validateNativeField(element: FieldElement): ValidationResponse { // custom controls (build with aria do not have a validity object to them) // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!element.validity) { return; } if (element.validity.valid) { return; } return { element: element, ...('value' in element ? { value: element.value } : {}), path: [element.name], message: element.validationMessage }; } export function validateNativeFields(elements: FieldElement[]): Issue[] { const seenRadioOptions = new Set(); return ( elements // filter out `` with the same name, as they would all // produce the same error .filter((elem) => { const { type, name } = elem; if (type !== 'radio') { return true; } if (!seenRadioOptions.has(name)) { seenRadioOptions.add(name); return true; } return false; }) .flatMap((e) => transformValidationResponse(validateNativeField(e))) ); }