import Ajv , { AnySchema , ValidateFunction } from 'ajv' ; import addDefaultFormats from 'ajv-formats' ; import * as formats from './formats' ; import { convertErrorsToLegacyFormat , LiskValidationError } from './errors' ; import { fieldNumberKeyword } from './keywords/field_number' ; import { dataTypeKeyword } from './keywords/data_type' ; import { liskMetaSchema } from './lisk_meta_schema' ; import { LiskErrorObject } from './types' ; export const liskSchemaIdentifier = liskMetaSchema . $id ; class LiskValidator { private readonly _validator : Ajv ; public constructor ( ) { this . _validator = new Ajv ( { strict : true , strictSchema : true , allErrors : true , useDefaults : false , addUsedSchema : false , strictTypes : false , } ) ; addDefaultFormats ( this . _validator ) ; for ( const formatName of Object . keys ( formats ) ) { this . _validator . addFormat ( formatName , formats [ formatName as keyof typeof formats ] ) ; } this . _validator . addKeyword ( { keyword : 'uniqueSignedPublicKeys' , type : 'array' , compile : ( ) => ( data ) => new Set ( data . filter ( datum => typeof datum === 'string' ) . map ( ( key ) => key . slice ( 1 ) ) ) . size === data . length , } ) ; this . _validator . compile ( liskMetaSchema ) ; this . _validator . addMetaSchema ( liskMetaSchema ) ; this . _validator . addKeyword ( fieldNumberKeyword ) ; this . _validator . addKeyword ( dataTypeKeyword ) ; } public validate ( schema , data ) { if ( ! this . _validator . validate ( schema , data ) ) { return convertErrorsToLegacyFormat ( this . _validator . errors as LiskErrorObject [ ] ) ; } return [ ] ; } public validateSchema ( schema ) { if ( ! this . _validator . validateSchema ( schema ) ) { return convertErrorsToLegacyFormat ( this . _validator . errors as LiskErrorObject [ ] ) ; } return [ ] ; } public compile ( schema ) { try { return this . _validator . compile ( schema ) ; } catch ( error ) { if ( error instanceof LiskValidationError ) { throw error ; } throw new LiskValidationError ( [ { message : ( error as Error ) . message . toString ( ) , dataPath : '' , keyword : '' , schemaPath : '' , params : { } , } , ] ) ; } } public removeSchema ( schemaKeyRef ? ) { return this . _validator . removeSchema ( schemaKeyRef ) ; } } export const validator = new LiskValidator ( ) ;