| 1 |
/** |
| 2 |
* Data validation. |
| 3 |
* |
| 4 |
* These functions allow us to ensure that `unknown` data obtained from, e.g., |
| 5 |
* an API, is of a specified type. |
| 6 |
*/ |
| 7 |
|
| 8 |
import type { Ok, Result } from "./result"; |
| 9 |
import { err, ok } from "./result"; |
| 10 |
|
| 11 |
export class ValidationError extends Error {} |
| 12 |
export class PrimitiveValidationError extends ValidationError { |
| 13 |
constructor(primitive: "boolean" | "number" | "string") { |
| 14 |
super(`Validation of primitive ${primitive} failed.`); |
| 15 |
} |
| 16 |
} |
| 17 |
class InvalidDateValidationError extends ValidationError { |
| 18 |
constructor() { |
| 19 |
super(`Validation of date failed: invalid date`); |
| 20 |
} |
| 21 |
} |
| 22 |
class TypeDateValidationError extends ValidationError { |
| 23 |
constructor() { |
| 24 |
super(`Validation of date failed: invalid type or length`); |
| 25 |
} |
| 26 |
} |
| 27 |
class ConstantValidationError extends ValidationError { |
| 28 |
constructor() { |
| 29 |
super(`Validation of constant failed`); |
| 30 |
} |
| 31 |
} |
| 32 |
class TaggedUnionObjectValidationError extends ValidationError { |
| 33 |
constructor() { |
| 34 |
super(`Validation of tagged union failed: expected object`); |
| 35 |
} |
| 36 |
} |
| 37 |
class TaggedUnionInvalidTagValidationError extends ValidationError { |
| 38 |
constructor() { |
| 39 |
super(`Validation of tagged union failed: invalid tag.`); |
| 40 |
} |
| 41 |
} |
| 42 |
class TaggedUnionValidationError extends ValidationError { |
| 43 |
constructor(tag: string, cause: ValidationError) { |
| 44 |
super(`Validation of tagged union failed for tag ${tag}.`, { cause }); |
| 45 |
} |
| 46 |
} |
| 47 |
class ArrayValidationError extends ValidationError { |
| 48 |
constructor() { |
| 49 |
super(`Validation of array failed.`); |
| 50 |
} |
| 51 |
} |
| 52 |
class ArrayItemValidationError extends ValidationError { |
| 53 |
constructor(index: number, cause: ValidationError) { |
| 54 |
super(`Validation of array failed at key ${index.toString()}.`, { cause }); |
| 55 |
} |
| 56 |
} |
| 57 |
class TupleValidationError extends ValidationError { |
| 58 |
constructor() { |
| 59 |
super(`Validation of tuple failed.`); |
| 60 |
} |
| 61 |
} |
| 62 |
class TupleItemValidationError extends ValidationError { |
| 63 |
constructor(index: number, cause: ValidationError) { |
| 64 |
super(`Validation of tuple failed at key ${index.toString()}.`, { cause }); |
| 65 |
} |
| 66 |
} |
| 67 |
class ObjectValidationError extends ValidationError { |
| 68 |
constructor() { |
| 69 |
super(`Validation of object failed.`); |
| 70 |
} |
| 71 |
} |
| 72 |
class ObjectKeyValidationError extends ValidationError { |
| 73 |
constructor(key: string, cause: ValidationError) { |
| 74 |
super(`Validation of object failed at key ${key}.`, { cause }); |
| 75 |
} |
| 76 |
} |
| 77 |
class RecordValidationError extends ValidationError { |
| 78 |
constructor() { |
| 79 |
super(`Validation of record failed.`); |
| 80 |
} |
| 81 |
} |
| 82 |
class RecordKeyValidationError extends ValidationError { |
| 83 |
constructor(key: string, cause: ValidationError) { |
| 84 |
super(`Validation of record failed at key ${key}.`, { cause }); |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
/** |
| 89 |
* A validator. |
| 90 |
* |
| 91 |
* That is, a function that checks an unknown object to be of a specified type. |
| 92 |
*/ |
| 93 |
export type Validator<T> = (json: unknown) => Result<T, ValidationError>; |
| 94 |
/** A validator that will never error. */ |
| 95 |
export type SafeValidator<T> = (json: unknown) => Ok<T>; |
| 96 |
|
| 97 |
/** Extract the validated type. */ |
| 98 |
export type ValidationT<R> = R extends Validator<infer T> ? T : never; |
| 99 |
|
| 100 |
/** |
| 101 |
* Validate with a default value if validation fails. |
| 102 |
*/ |
| 103 |
export function defaultValue<T>( |
| 104 |
validator: Validator<T>, |
| 105 |
value: () => T, |
| 106 |
): SafeValidator<T> { |
| 107 |
return (json) => { |
| 108 |
const res = validator(json); |
| 109 |
return res.is_ok ? res : ok(value()); |
| 110 |
}; |
| 111 |
} |
| 112 |
|
| 113 |
/** |
| 114 |
* Validate as unknown (noop, just wrap in ok()). |
| 115 |
*/ |
| 116 |
export const unknown: SafeValidator<unknown> = ok; |
| 117 |
|
| 118 |
/** |
| 119 |
* Validate a string. |
| 120 |
*/ |
| 121 |
export const string: Validator<string> = (json) => |
| 122 |
typeof json === "string" |
| 123 |
? ok(json) |
| 124 |
: err(new PrimitiveValidationError("string")); |
| 125 |
|
| 126 |
/** Validate a string and return the empty string on failure. */ |
| 127 |
export const optional_string: SafeValidator<string> = (json) => |
| 128 |
typeof json === "string" ? ok(json) : ok(""); |
| 129 |
|
| 130 |
/** |
| 131 |
* Validate a boolean. |
| 132 |
*/ |
| 133 |
export const boolean: Validator<boolean> = (json) => |
| 134 |
typeof json === "boolean" |
| 135 |
? ok(json) |
| 136 |
: err(new PrimitiveValidationError("boolean")); |
| 137 |
|
| 138 |
/** |
| 139 |
* Validate a number. |
| 140 |
*/ |
| 141 |
export const number: Validator<number> = (json) => |
| 142 |
typeof json === "number" |
| 143 |
? ok(json) |
| 144 |
: err(new PrimitiveValidationError("number")); |
| 145 |
|
| 146 |
/** |
| 147 |
* Validate a date (from a string). |
| 148 |
*/ |
| 149 |
export const date: Validator<Date> = (json) => { |
| 150 |
if (json instanceof Date) { |
| 151 |
return ok(json); |
| 152 |
} |
| 153 |
if (typeof json === "string" && json.length === 10) { |
| 154 |
const parsed = new Date(json); |
| 155 |
return Number.isNaN(+parsed) |
| 156 |
? err(new InvalidDateValidationError()) |
| 157 |
: ok(parsed); |
| 158 |
} |
| 159 |
return err(new TypeDateValidationError()); |
| 160 |
}; |
| 161 |
|
| 162 |
/** |
| 163 |
* Validate a value to be equal to a constant value. |
| 164 |
*/ |
| 165 |
export function constant<T extends null | boolean | string | number>( |
| 166 |
value: T, |
| 167 |
): Validator<T> { |
| 168 |
return (json) => |
| 169 |
json === value ? ok(json as T) : err(new ConstantValidationError()); |
| 170 |
} |
| 171 |
|
| 172 |
/** Helper type to get the union of the types in a tuple. */ |
| 173 |
type TupleElement<T extends unknown[]> = T extends (infer E)[] ? E : T; |
| 174 |
|
| 175 |
/** |
| 176 |
* Validate a value is one of the provided constant values. |
| 177 |
*/ |
| 178 |
export function constants<const T extends (null | boolean | string | number)[]>( |
| 179 |
...args: T |
| 180 |
): Validator<TupleElement<T>> { |
| 181 |
return (json) => |
| 182 |
args.includes(json as null | boolean | string | number) |
| 183 |
? ok(json as TupleElement<T>) |
| 184 |
: err(new ConstantValidationError()); |
| 185 |
} |
| 186 |
|
| 187 |
/** |
| 188 |
* Validate a value that is of one of the given tagged types. |
| 189 |
*/ |
| 190 |
export function tagged_union<T>( |
| 191 |
tag: string, |
| 192 |
validators: { [t in keyof T]: Validator<T[t]> }, |
| 193 |
): Validator<T[keyof T]> { |
| 194 |
return (json) => { |
| 195 |
if (!isJsonObject(json)) { |
| 196 |
return err(new TaggedUnionObjectValidationError()); |
| 197 |
} |
| 198 |
const tag_value = json[tag]; |
| 199 |
if (typeof tag_value != "string" || !Object.hasOwn(validators, tag_value)) { |
| 200 |
return err(new TaggedUnionInvalidTagValidationError()); |
| 201 |
} |
| 202 |
const res = validators[tag_value as keyof T](json); |
| 203 |
return res.is_ok |
| 204 |
? res |
| 205 |
: err(new TaggedUnionValidationError(tag_value, res.error)); |
| 206 |
}; |
| 207 |
} |
| 208 |
|
| 209 |
/** |
| 210 |
* Validator for an object that might be null or undefined. |
| 211 |
*/ |
| 212 |
export function optional<T>(validator: Validator<T>): Validator<T | null> { |
| 213 |
return (json) => (json == null ? ok(null) : validator(json)); |
| 214 |
} |
| 215 |
|
| 216 |
/** |
| 217 |
* Lazy validator to allow for recursive structures. |
| 218 |
*/ |
| 219 |
export function lazy<T>(func: () => Validator<T>): Validator<T> { |
| 220 |
return (json) => func()(json); |
| 221 |
} |
| 222 |
|
| 223 |
/** |
| 224 |
* Validator for an array of values. |
| 225 |
*/ |
| 226 |
export function array<T>(validator: Validator<T>): Validator<T[]> { |
| 227 |
return (json) => { |
| 228 |
if (Array.isArray(json)) { |
| 229 |
const result: T[] = []; |
| 230 |
let i = 0; |
| 231 |
for (const element of json) { |
| 232 |
const res = validator(element); |
| 233 |
if (res.is_ok) { |
| 234 |
result.push(res.value); |
| 235 |
} else { |
| 236 |
return err(new ArrayItemValidationError(i, res.error)); |
| 237 |
} |
| 238 |
i += 1; |
| 239 |
} |
| 240 |
return ok(result); |
| 241 |
} |
| 242 |
return err(new ArrayValidationError()); |
| 243 |
}; |
| 244 |
} |
| 245 |
|
| 246 |
/** |
| 247 |
* Validator for a tuple of fixed length. |
| 248 |
*/ |
| 249 |
export function tuple<const T extends unknown[]>( |
| 250 |
...args: { [P in keyof T]: Validator<T[P]> } |
| 251 |
): Validator<T> { |
| 252 |
return (json) => { |
| 253 |
if (Array.isArray(json) && json.length === args.length) { |
| 254 |
const result = []; |
| 255 |
let i = 0; |
| 256 |
for (const decoder of args) { |
| 257 |
const res = decoder(json[i]); |
| 258 |
if (res.is_ok) { |
| 259 |
result[i] = res.value; |
| 260 |
} else { |
| 261 |
return err(new TupleItemValidationError(i, res.error)); |
| 262 |
} |
| 263 |
i += 1; |
| 264 |
} |
| 265 |
return ok(result as T); |
| 266 |
} |
| 267 |
return err(new TupleValidationError()); |
| 268 |
}; |
| 269 |
} |
| 270 |
|
| 271 |
/** |
| 272 |
* Check whether the given object is a string-indexable object. |
| 273 |
*/ |
| 274 |
export function isJsonObject(json: unknown): json is Record<string, unknown> { |
| 275 |
return typeof json === "object" && json !== null && !Array.isArray(json); |
| 276 |
} |
| 277 |
|
| 278 |
/** |
| 279 |
* Validator for an object with some given properties. |
| 280 |
*/ |
| 281 |
export function object<T>(validators: { |
| 282 |
[t in keyof T]: Validator<T[t]>; |
| 283 |
}): Validator<T> { |
| 284 |
return (json) => { |
| 285 |
if (isJsonObject(json)) { |
| 286 |
const obj: Partial<T> = {}; |
| 287 |
// eslint-disable-next-line no-restricted-syntax |
| 288 |
for (const key in validators) { |
| 289 |
if (Object.hasOwn(validators, key)) { |
| 290 |
const res = validators[key](json[key]); |
| 291 |
if (res.is_ok) { |
| 292 |
obj[key] = res.value; |
| 293 |
} else { |
| 294 |
return err(new ObjectKeyValidationError(key, res.error)); |
| 295 |
} |
| 296 |
} |
| 297 |
} |
| 298 |
return ok(obj as T); |
| 299 |
} |
| 300 |
return err(new ObjectValidationError()); |
| 301 |
}; |
| 302 |
} |
| 303 |
|
| 304 |
/** |
| 305 |
* Validator for a dict-like structure. |
| 306 |
*/ |
| 307 |
export function record<T>(decoder: Validator<T>): Validator<Record<string, T>> { |
| 308 |
return (json) => { |
| 309 |
if (isJsonObject(json)) { |
| 310 |
const ret: Record<string, T> = {}; |
| 311 |
for (const [key, value] of Object.entries(json)) { |
| 312 |
const res = decoder(value); |
| 313 |
if (res.is_ok) { |
| 314 |
ret[key] = res.value; |
| 315 |
} else { |
| 316 |
return err(new RecordKeyValidationError(key, res.error)); |
| 317 |
} |
| 318 |
} |
| 319 |
return ok(ret); |
| 320 |
} |
| 321 |
return err(new RecordValidationError()); |
| 322 |
}; |
| 323 |
} |