/** * Data validation. * * These functions allow us to ensure that `unknown` data obtained from, e.g., * an API, is of a specified type. */ import type { Ok, Result } from "./result"; import { err, ok } from "./result"; export class ValidationError extends Error {} export class PrimitiveValidationError extends ValidationError { constructor(primitive: "boolean" | "number" | "string") { super(`Validation of primitive ${primitive} failed.`); } } class InvalidDateValidationError extends ValidationError { constructor() { super(`Validation of date failed: invalid date`); } } class TypeDateValidationError extends ValidationError { constructor() { super(`Validation of date failed: invalid type or length`); } } class ConstantValidationError extends ValidationError { constructor() { super(`Validation of constant failed`); } } class TaggedUnionObjectValidationError extends ValidationError { constructor() { super(`Validation of tagged union failed: expected object`); } } class TaggedUnionInvalidTagValidationError extends ValidationError { constructor() { super(`Validation of tagged union failed: invalid tag.`); } } class TaggedUnionValidationError extends ValidationError { constructor(tag: string, cause: ValidationError) { super(`Validation of tagged union failed for tag ${tag}.`, { cause }); } } class ArrayValidationError extends ValidationError { constructor() { super(`Validation of array failed.`); } } class ArrayItemValidationError extends ValidationError { constructor(index: number, cause: ValidationError) { super(`Validation of array failed at key ${index.toString()}.`, { cause }); } } class TupleValidationError extends ValidationError { constructor() { super(`Validation of tuple failed.`); } } class TupleItemValidationError extends ValidationError { constructor(index: number, cause: ValidationError) { super(`Validation of tuple failed at key ${index.toString()}.`, { cause }); } } class ObjectValidationError extends ValidationError { constructor() { super(`Validation of object failed.`); } } class ObjectKeyValidationError extends ValidationError { constructor(key: string, cause: ValidationError) { super(`Validation of object failed at key ${key}.`, { cause }); } } class RecordValidationError extends ValidationError { constructor() { super(`Validation of record failed.`); } } class RecordKeyValidationError extends ValidationError { constructor(key: string, cause: ValidationError) { super(`Validation of record failed at key ${key}.`, { cause }); } } /** * A validator. * * That is, a function that checks an unknown object to be of a specified type. */ export type Validator = (json: unknown) => Result; /** A validator that will never error. */ export type SafeValidator = (json: unknown) => Ok; /** Extract the validated type. */ export type ValidationT = R extends Validator ? T : never; /** * Validate with a default value if validation fails. */ export function defaultValue( validator: Validator, value: () => T, ): SafeValidator { return (json) => { const res = validator(json); return res.is_ok ? res : ok(value()); }; } /** * Validate as unknown (noop, just wrap in ok()). */ export const unknown: SafeValidator = ok; /** * Validate a string. */ export const string: Validator = (json) => typeof json === "string" ? ok(json) : err(new PrimitiveValidationError("string")); /** Validate a string and return the empty string on failure. */ export const optional_string: SafeValidator = (json) => typeof json === "string" ? ok(json) : ok(""); /** * Validate a boolean. */ export const boolean: Validator = (json) => typeof json === "boolean" ? ok(json) : err(new PrimitiveValidationError("boolean")); /** * Validate a number. */ export const number: Validator = (json) => typeof json === "number" ? ok(json) : err(new PrimitiveValidationError("number")); /** * Validate a date (from a string). */ export const date: Validator = (json) => { if (json instanceof Date) { return ok(json); } if (typeof json === "string" && json.length === 10) { const parsed = new Date(json); return Number.isNaN(+parsed) ? err(new InvalidDateValidationError()) : ok(parsed); } return err(new TypeDateValidationError()); }; /** * Validate a value to be equal to a constant value. */ export function constant( value: T, ): Validator { return (json) => json === value ? ok(json as T) : err(new ConstantValidationError()); } /** Helper type to get the union of the types in a tuple. */ type TupleElement = T extends (infer E)[] ? E : T; /** * Validate a value is one of the provided constant values. */ export function constants( ...args: T ): Validator> { return (json) => args.includes(json as null | boolean | string | number) ? ok(json as TupleElement) : err(new ConstantValidationError()); } /** * Validate a value that is of one of the given tagged types. */ export function tagged_union( tag: string, validators: { [t in keyof T]: Validator }, ): Validator { return (json) => { if (!isJsonObject(json)) { return err(new TaggedUnionObjectValidationError()); } const tag_value = json[tag]; if (typeof tag_value != "string" || !Object.hasOwn(validators, tag_value)) { return err(new TaggedUnionInvalidTagValidationError()); } const res = validators[tag_value as keyof T](json); return res.is_ok ? res : err(new TaggedUnionValidationError(tag_value, res.error)); }; } /** * Validator for an object that might be null or undefined. */ export function optional(validator: Validator): Validator { return (json) => (json == null ? ok(null) : validator(json)); } /** * Lazy validator to allow for recursive structures. */ export function lazy(func: () => Validator): Validator { return (json) => func()(json); } /** * Validator for an array of values. */ export function array(validator: Validator): Validator { return (json) => { if (Array.isArray(json)) { const result: T[] = []; let i = 0; for (const element of json) { const res = validator(element); if (res.is_ok) { result.push(res.value); } else { return err(new ArrayItemValidationError(i, res.error)); } i += 1; } return ok(result); } return err(new ArrayValidationError()); }; } /** * Validator for a tuple of fixed length. */ export function tuple( ...args: { [P in keyof T]: Validator } ): Validator { return (json) => { if (Array.isArray(json) && json.length === args.length) { const result = []; let i = 0; for (const decoder of args) { const res = decoder(json[i]); if (res.is_ok) { result[i] = res.value; } else { return err(new TupleItemValidationError(i, res.error)); } i += 1; } return ok(result as T); } return err(new TupleValidationError()); }; } /** * Check whether the given object is a string-indexable object. */ export function isJsonObject(json: unknown): json is Record { return typeof json === "object" && json !== null && !Array.isArray(json); } /** * Validator for an object with some given properties. */ export function object(validators: { [t in keyof T]: Validator; }): Validator { return (json) => { if (isJsonObject(json)) { const obj: Partial = {}; // eslint-disable-next-line no-restricted-syntax for (const key in validators) { if (Object.hasOwn(validators, key)) { const res = validators[key](json[key]); if (res.is_ok) { obj[key] = res.value; } else { return err(new ObjectKeyValidationError(key, res.error)); } } } return ok(obj as T); } return err(new ObjectValidationError()); }; } /** * Validator for a dict-like structure. */ export function record(decoder: Validator): Validator> { return (json) => { if (isJsonObject(json)) { const ret: Record = {}; for (const [key, value] of Object.entries(json)) { const res = decoder(value); if (res.is_ok) { ret[key] = res.value; } else { return err(new RecordKeyValidationError(key, res.error)); } } return ok(ret); } return err(new RecordValidationError()); }; }