import { JsonSchema, JsonSchemaBuilder, CommonLogger } from '@naturalcycles/js-lib'; import Ajv from 'ajv'; import { AjvValidationError } from './ajvValidationError'; export interface AjvValidationOptions { objectName?: string; objectId?: string; /** * @default to cfg.logErrors, which defaults to true */ logErrors?: boolean; /** * Used to separate multiple validation errors. * * @default cfg.separator || '\n' */ separator?: string; } export interface AjvSchemaCfg { /** * Pass Ajv instance, otherwise Ajv will be created with * AjvSchema default (not the same as Ajv defaults) parameters */ ajv: Ajv; /** * Dependent schemas to pass to Ajv instance constructor. * Simpler than instantiating and passing ajv instance yourself. */ schemas?: (JsonSchema | JsonSchemaBuilder | AjvSchema)[]; objectName?: string; /** * Used to separate multiple validation errors. * * @default '\n' */ separator: string; /** * @default true */ logErrors: boolean; /** * Default to `console` */ logger: CommonLogger; /** * Option of Ajv. * If set to true - will mutate your input objects! * Defaults to false. * * This option is a "shortcut" to skip creating and passing Ajv instance. */ coerceTypes?: boolean; } /** * On creation - compiles ajv validation function. * Provides convenient methods, error reporting, etc. * * @experimental */ export declare class AjvSchema { schema: JsonSchema; private constructor(); /** * Conveniently allows to pass either JsonSchema or JsonSchemaBuilder, or existing AjvSchema. * If it's already an AjvSchema - it'll just return it without any processing. * If it's a Builder - will call `build` before proceeding. * Otherwise - will construct AjvSchema instance ready to be used. * * Implementation note: JsonSchemaBuilder goes first in the union type, otherwise TypeScript fails to infer type * correctly for some reason. */ static create(schema: JsonSchemaBuilder | JsonSchema | AjvSchema, cfg?: Partial): AjvSchema; /** * Create AjvSchema directly from a filePath of json schema. * Convenient method that just does fs.readFileSync for you. */ static readJsonSync(filePath: string, cfg?: Partial): AjvSchema; readonly cfg: AjvSchemaCfg; private readonly validateFunction; /** * It returns the original object just for convenience. * Reminder: Ajv will MUTATE your object under 2 circumstances: * 1. `useDefaults` option (enabled by default!), which will set missing/empty values that have `default` set in the schema. * 2. `coerceTypes` (false by default). * * Returned object is always the same object (`===`) that was passed, so it is returned just for convenience. */ validate(obj: T, opt?: AjvValidationOptions): T; getValidationError(obj: T, opt?: AjvValidationOptions): AjvValidationError | undefined; isValid(obj: T): boolean; }