import { LiskErrorObject } from './types' ; const errorParamToString = ( param ) : string => { let paramAsString = '' ; if ( typeof param === 'bigint' ) { paramAsString = param . toString ( ) ; } else if ( Buffer . isBuffer ( param ) ) { paramAsString = param . toString ( 'hex' ) ; } else if ( param === undefined ) { paramAsString = '' ; } else { paramAsString = param as string ; } return paramAsString ; } ; type KeywordFormatterFunction = ( error : LiskErrorObject ) => string ; interface KeywordDataFormatters { [ key ] : KeywordFormatterFunction | undefined ; } export const convertErrorsToLegacyFormat = ( errors ) : LiskErrorObject [ ] => errors . map ( e => { const err = e as LiskErrorObject & { instancePath ? : string ; } ; err . dataPath = err . dataPath ?? instancePathToLegacyDataPath ( err . instancePath ?? '' ) ; delete err . instancePath ; return err ; } ) ; const instancePathToLegacyDataPath = ( path ) => path . split ( '/' ) . join ( '.' ) ; const errorFormatterMap = { type : error => `Property '${ error . dataPath ?? '' }' should be of type '${ errorParamToString ( error . params . type ) }'` , additionalProperties : error => `Property '${ error . dataPath ?? '' }' has extraneous property '${ errorParamToString ( error . params . additionalProperty ) }'` , minLength : error => `Property '${ error . dataPath ?? '' }' ${ errorParamToString ( error . message ) }` , maxLength : error => `Property '${ error . dataPath ?? '' }' ${ errorParamToString ( error . message ) }` , format : error => `Property '${ error . dataPath ?? '' }' ${ errorParamToString ( error . message ) }` , required : error => `Missing property, ${ errorParamToString ( error . message ) }` , dataType : error => `Property '${ error . dataPath ?? '' }' ${ errorParamToString ( error . message ) }` , } ; const defaultErrorFormatter = error => error . message ?? 'Unspecified validator error' ; const errorFormatter = ( error ) : string => ( errorFormatterMap [ error . keyword ] ?? defaultErrorFormatter ) ( error ) ; export class LiskValidationError extends Error { public readonly errors : LiskErrorObject [ ] ; public constructor ( errors ) { super ( ) ; this . errors = convertErrorsToLegacyFormat ( errors ) ; this . message = `Lisk validator found ${ this . errors . length } error[s]:\n${ this . _compileErrors ( ) . join ( '\n' ) }` ; } private _compileErrors ( ) { const errorMsgs = this . errors . map ( errorFormatter ) ; return errorMsgs ; } }