import Ajv from "ajv"; import { InternalTypeSymbol, JsonValue, SchemaLike } from "./json-schema"; const hiddenField = Symbol("SpecialTypeAnnotationFieldDoNotUse"); type TsjsonString = string & { [hiddenField]: T extends JsonValue ? T : unknown; }; export const TSJSON = { parse: (input: TsjsonString): T => JSON.parse(input) as T, stringify: (input: T): TsjsonString => JSON.stringify(input) as TsjsonString, }; export type Validated = T[typeof InternalTypeSymbol]; export class TsjsonParser { public readonly schema: T; private readonly validator: Ajv.ValidateFunction; constructor(schema: T, ajvOptions: Ajv.Options = {}) { this.schema = schema; const ajv = new Ajv(ajvOptions); this.validator = ajv.compile(schema); } // call this to get the errors from the most recent validation call. public getErrors = (): Ajv.ErrorObject[] | null | undefined => this.validator.errors; public validates(data: unknown): data is Validated { const valid = this.validator(data); if (!valid) { return false; } return true; } public parse = (text: string, skipValidation = false): Validated => { const data: unknown = JSON.parse(text); if (skipValidation) { return data; } if (this.validates(data)) { return data; } throw new Error(JSON.stringify(this.validator.errors)); }; }