<div align="center" >
	<h1>variable-value-validator</h1>
    <p>Minimal schema validation for TypeScript and JavaScript.</p>
</div>

## What is it ?

`variable-value-validator` is a minimal ([standard-schema](https://github.com/standard-schema/standard-schema#------standard-schema) compliant) schema validation library enabling type-safe code with unsafe data such as serialized data, API responses, and more.

### Example

```ts
// defining a schema describing the user object :
const userSchema = vvv.object({
	id: vvv.number(),
	name: vvv.string(),
	isActive: vvv.boolean({ optional: true }),
	tags: vvv.array(vvv.string()),
})

// if a TypeScript type is needed it can be inferred from the schema :
type User = SchemaToType<typeof userSchema>

// example unsafe data :
const response = await fetch("api.com/user/1")
const user = await response.json()

if (userSchema.guard(user)) {
	// `user` is now guaranteed to be of type User
}
```

## Installation

```bash
# npm
npm install variable-value-validator
# yarn
yarn add variable-value-validator
# pnpm
pnpm add variable-value-validator
```

## Schema creation methods

- Primitives: `vvv.string()`, `vvv.number()`, `vvv.boolean()`, `vvv.undefined()`, `vvv.null()`, `vvv.nullish()` (null or undefined), `vvv.function()` and `vvv.unknown()` (always valid).
- Objects: `vvv.object(shape: Record<string, Schema>)`, `vvv.array(items: Schema[])`, `record(values: Schema[])`, `set(values: Schema[])`, `map(keys: Schema[], values: Schema[])`, `vvv.instance(constructor: new (...args: any[]) => Object)` (class instances).
- Other: `vvv.union(members: Schema[])` ("OR" schema association).

All of the schema creation methods accept an optional `options` object which can have the following optional properties:

- `optional`: Marks the property as optional when used with `vvv.object` (e.g. `vvv.object({ foo: string({ optional: true }) })`).
- `predicates`: A function or an array of functions to add custom validation (e.g. `vvv.number({ predicates: (num) => Number.isInteger(num) })`).

## Schemas

Every schema has the following methods :

- `guard(value: unknown)`: A [type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) for that schema. If the `value` is valid in respect to that schema it will return `true`, else it will return `false`.
- `errors(value: unknown)`: An array of [issues](https://github.com/standard-schema/standard-schema/blob/4db8364a7fb7facdb5a19e8184f943a53dbbe854/packages/spec/src/index.ts#L40), a valid `value` returns an empty array.
