import { TypedObject } from "../../../libs/typescript/object.mjs"; import { die } from "../../internal/exceptions.mjs"; import { isArrayOf, isTupleOf, isUnionOf } from "../../validator/array.mjs"; import type { Validator } from "../../validator/common.mjs"; import { isEnumOf } from "../../validator/enum.mjs"; import { isObject } from "../../validator/object.mjs"; import { isNullish, primitiveOf } from "../../validator/primitive.mjs"; import { is } from "../../validator/utils.mjs"; import { isJSONLike } from "../core/is-json-like.mjs"; import type { CreateObjectTypeBySchema, CreateTypeBySchemaType, JSONObjectSchema, JSONSchema, } from "../interfaces/json-describer.mjs"; const internalCreateValidatorBySchema = ( schema: Schema ): Validator> => { if (schema.type === "object") { type T = CreateObjectTypeBySchema>; const entries = TypedObject.entries(schema.fields); type ValidatorOfT = { [K in keyof T]: Validator; }; const obj = entries.reduce>( (acc, [key, subschema]) => { Reflect.set(acc, key, internalCreateValidatorBySchema(subschema)); return acc; }, {} ); // @ts-expect-error Dynamic impl return isObject(obj); } if (schema.type === "array") { // @ts-expect-error Dynamic impl return isArrayOf(internalCreateValidatorBySchema(schema.item)); } if (schema.type === "tuple") { // @ts-expect-error Dynamic impl return isTupleOf(...schema.items.map(internalCreateValidatorBySchema)); } if (schema.type === "enum") { // @ts-expect-error Dynamic impl return isEnumOf(schema.enumObject); } if (schema.type === "null") { // @ts-expect-error Dynamic impl return isNullish; } if (schema.type === "literal") { // @ts-expect-error Dynamic impl return is(schema.value); } if (schema.type === "union") { return isUnionOf(...schema.unions.map(internalCreateValidatorBySchema)); } // @ts-expect-error Dynamic impl return primitiveOf(schema.type); }; export const createValidatorBySchema = ( schema: Schema ): Validator> => { if (!isJSONLike(schema)) { return die("Invalid JSON Schema."); } return internalCreateValidatorBySchema(schema); };