UNPKG

object-shape-tester

Version:
117 lines (116 loc) 2.73 kB
import { Kind, OptionalKind, Type, } from '@sinclair/typebox'; /** * Checks if a schema is an object schema. * * @category Internal */ export function isObjectSchema(schema) { return schema[Kind] === 'Object'; } /** * Checks if a schema is a union schema. * * @category Internal */ export function isUnionSchema(schema) { return schema[Kind] === 'Union'; } /** * Checks if a schema is an optional schema. * * @category Internal */ export function isOptionalSchema(schema) { return schema[OptionalKind] === 'Optional'; } /** * Checks if a schema is a null schema. * * @category Internal */ export function isNullSchema(schema) { return schema[Kind] === 'Null'; } /** * Checks if a schema is an undefined schema. * * @category Internal */ export function isUndefinedSchema(schema) { return schema[Kind] === 'Undefined'; } /** * Checks if a schema guard matches the schema or a part of the schema's union. * * @category Internal */ export function matchesSchemaGuard(schema, guard) { if (guard(schema)) { return true; } else if (isUnionSchema(schema)) { return schema.anyOf.some((entry) => matchesSchemaGuard(entry, guard)); } else { return false; } } /** * Checks if a schema can be nullable (optional, `undefined`, or `null`). * * @category Internal */ export function canSchemaBeNullable(schema) { return [ isNullSchema, isUndefinedSchema, isOptionalSchema, ].some((guard) => matchesSchemaGuard(schema, guard)); } /** * Inserts a value into a union schema, converting the original schema into a union if it isn't * already. * * @category Internal */ export function insertUnion({ insertion, originalSchema, }) { if (isUnionSchema(originalSchema)) { return Type.Union([ ...originalSchema.anyOf, insertion, ], { default: originalSchema.default, }); } else { return Type.Union([ originalSchema, Type.Undefined(), ], { default: originalSchema.default, }); } } /** * Runs a `transform` function on a schema or any part of its union that matches `guard`. * * @category Internal */ export function operateOnExtraction(originalSchema, guard, transform) { if (isUnionSchema(originalSchema)) { return Type.Union(originalSchema.anyOf.map((entry) => { if (guard(entry)) { return transform(entry); } else { return entry; } })); } else if (guard(originalSchema)) { return transform(originalSchema); } else { return originalSchema; } }