@cleverbrush/schema 1.1.11 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1314 -101
- package/dist/builders/AnySchemaBuilder.d.ts +54 -14
- package/dist/builders/AnySchemaBuilder.js +2 -112
- package/dist/builders/AnySchemaBuilder.js.map +1 -0
- package/dist/builders/ArraySchemaBuilder.d.ts +124 -23
- package/dist/builders/ArraySchemaBuilder.js +2 -284
- package/dist/builders/ArraySchemaBuilder.js.map +1 -0
- package/dist/builders/BooleanSchemaBuilder.d.ts +94 -19
- package/dist/builders/BooleanSchemaBuilder.js +2 -150
- package/dist/builders/BooleanSchemaBuilder.js.map +1 -0
- package/dist/builders/DateSchemaBuilder.d.ts +134 -34
- package/dist/builders/DateSchemaBuilder.js +2 -433
- package/dist/builders/DateSchemaBuilder.js.map +1 -0
- package/dist/builders/ExternSchemaBuilder.d.ts +200 -0
- package/dist/builders/ExternSchemaBuilder.js +2 -0
- package/dist/builders/ExternSchemaBuilder.js.map +1 -0
- package/dist/builders/FunctionSchemaBuilder.d.ts +57 -14
- package/dist/builders/FunctionSchemaBuilder.js +2 -113
- package/dist/builders/FunctionSchemaBuilder.js.map +1 -0
- package/dist/builders/LazySchemaBuilder.d.ts +167 -0
- package/dist/builders/NullSchemaBuilder.d.ts +162 -0
- package/dist/builders/NumberSchemaBuilder.d.ts +143 -31
- package/dist/builders/NumberSchemaBuilder.js +2 -386
- package/dist/builders/NumberSchemaBuilder.js.map +1 -0
- package/dist/builders/ObjectSchemaBuilder.d.ts +266 -61
- package/dist/builders/ObjectSchemaBuilder.js +2 -589
- package/dist/builders/ObjectSchemaBuilder.js.map +1 -0
- package/dist/builders/PropertyValidationResult.d.ts +68 -0
- package/dist/builders/RecordSchemaBuilder.d.ts +341 -0
- package/dist/builders/RecordSchemaBuilder.js +2 -0
- package/dist/builders/RecordSchemaBuilder.js.map +1 -0
- package/dist/builders/SchemaBuilder.d.ts +818 -30
- package/dist/builders/StringSchemaBuilder.d.ts +152 -37
- package/dist/builders/StringSchemaBuilder.js +2 -414
- package/dist/builders/StringSchemaBuilder.js.map +1 -0
- package/dist/builders/TupleSchemaBuilder.d.ts +248 -0
- package/dist/builders/TupleSchemaBuilder.js +2 -0
- package/dist/builders/TupleSchemaBuilder.js.map +1 -0
- package/dist/builders/UnionSchemaBuilder.d.ts +133 -39
- package/dist/builders/UnionSchemaBuilder.js +2 -216
- package/dist/builders/UnionSchemaBuilder.js.map +1 -0
- package/dist/chunk-BFCMDDTX.js +2 -0
- package/dist/chunk-BFCMDDTX.js.map +1 -0
- package/dist/chunk-CTP4RHDG.js +2 -0
- package/dist/chunk-CTP4RHDG.js.map +1 -0
- package/dist/chunk-EUQ5AE3H.js +2 -0
- package/dist/chunk-EUQ5AE3H.js.map +1 -0
- package/dist/chunk-FWUEUW2N.js +2 -0
- package/dist/chunk-FWUEUW2N.js.map +1 -0
- package/dist/chunk-IJ6FO37G.js +2 -0
- package/dist/chunk-IJ6FO37G.js.map +1 -0
- package/dist/chunk-KESLT5EE.js +2 -0
- package/dist/chunk-KESLT5EE.js.map +1 -0
- package/dist/chunk-KFTO7TMB.js +2 -0
- package/dist/chunk-KFTO7TMB.js.map +1 -0
- package/dist/chunk-MKAYFPAR.js +2 -0
- package/dist/chunk-MKAYFPAR.js.map +1 -0
- package/dist/chunk-NXPH3ZUW.js +2 -0
- package/dist/chunk-NXPH3ZUW.js.map +1 -0
- package/dist/chunk-S5TC6NSU.js +2 -0
- package/dist/chunk-S5TC6NSU.js.map +1 -0
- package/dist/chunk-YWBNVHR6.js +2 -0
- package/dist/chunk-YWBNVHR6.js.map +1 -0
- package/dist/chunk-Z7QZ7IXT.js +2 -0
- package/dist/chunk-Z7QZ7IXT.js.map +1 -0
- package/dist/chunk-ZAN4ZHCJ.js +2 -0
- package/dist/chunk-ZAN4ZHCJ.js.map +1 -0
- package/dist/chunk-ZUPYV5TI.js +2 -0
- package/dist/chunk-ZUPYV5TI.js.map +1 -0
- package/dist/core.d.ts +23 -0
- package/dist/core.js +2 -0
- package/dist/core.js.map +1 -0
- package/dist/extension.d.ts +413 -0
- package/dist/extensions/array.d.ts +112 -0
- package/dist/extensions/enum.d.ts +190 -0
- package/dist/extensions/index.d.ts +108 -0
- package/dist/extensions/nullable.d.ts +26 -0
- package/dist/extensions/number.d.ts +228 -0
- package/dist/extensions/string.d.ts +332 -0
- package/dist/extensions/util.d.ts +45 -0
- package/dist/index.d.ts +7 -20
- package/dist/index.js +2 -19
- package/dist/index.js.map +1 -0
- package/dist/utils/transaction.d.ts +27 -4
- package/package.json +74 -6
- package/dist/builders/SchemaBuilder.js +0 -275
- package/dist/utils/transaction.js +0 -178
package/README.md
CHANGED
|
@@ -1,152 +1,1365 @@
|
|
|
1
|
-
|
|
1
|
+
# @cleverbrush/schema
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://github.com/cleverbrush/framework/actions/workflows/ci.yml)
|
|
4
|
+
[](https://standardschema.dev/)
|
|
5
|
+
<!-- bundle-badge-start -->
|
|
6
|
+
[](https://github.com/cleverbrush/framework/blob/master/libs/schema)
|
|
7
|
+
<!-- bundle-badge-end -->
|
|
8
|
+
[](../../LICENSE)
|
|
9
|
+
<!-- coverage-badge-start -->
|
|
10
|
+

|
|
11
|
+
<!-- coverage-badge-end -->
|
|
12
|
+
|
|
13
|
+
A schema definition and validation library for TypeScript — faster than Zod in 14/15 benchmarks (up to 204× faster on invalid input), 3× smaller than Zod v4, and compatible with 50+ ecosystem tools via [Standard Schema v1](https://standardschema.dev/).
|
|
14
|
+
|
|
15
|
+
Define a schema **once** and get TypeScript type inference, runtime validation, object mapping ([`@cleverbrush/mapper`](../mapper)), auto-generated React forms ([`@cleverbrush/react-form`](../react-form)), and bidirectional JSON Schema conversion ([`@cleverbrush/schema-json`](../schema-json)) — all from the same immutable, fluent API.
|
|
16
|
+
|
|
17
|
+
## Why @cleverbrush/schema?
|
|
18
|
+
|
|
19
|
+
**The problem:** In a typical TypeScript project, types and runtime validation are separate concerns. You define a `User` type in one file, then write Joi / Yup / Zod schemas (or manual `if` checks) in another. Over time these drift apart — the type says a field is required, but the validation allows it to be `undefined`. Tests pass, but production data breaks because the validation didn't match the type.
|
|
20
|
+
|
|
21
|
+
**The solution:** `@cleverbrush/schema` lets you define a schema **once** and derive both the TypeScript type (via `InferType`) and runtime validation from the same source. Because every method returns a **new builder instance** (immutability), you can safely compose and extend schemas without accidentally mutating shared definitions.
|
|
22
|
+
|
|
23
|
+
**What makes it different from Zod / Yup / Joi:**
|
|
24
|
+
|
|
25
|
+
- **PropertyDescriptors** — a runtime descriptor tree that every tool in the ecosystem can introspect. The [`@cleverbrush/mapper`](../mapper) uses it for type-safe property selectors. The [`@cleverbrush/react-form`](../react-form) uses it to auto-generate form fields with correct validation. This makes the schema library a **foundation** for an entire ecosystem — not just a standalone validation tool. No other popular schema library exposes this level of runtime metadata.
|
|
26
|
+
- **Standard Schema v1** — the `['~standard']` getter is implemented on every builder. That means your schema works as-is with tRPC, TanStack Form, React Hook Form, T3 Env, Hono, Elysia, next-safe-action, and every other [Standard Schema consumer](https://standardschema.dev/).
|
|
27
|
+
- **Extension system** — add custom methods to any builder type (`string`, `number`, `date`, …) via `defineExtension()` + `withExtensions()`. Extensions are fully typed, chainable, composable, and appear in `introspect()`. No other popular schema library offers a comparable type-safe plugin system.
|
|
28
|
+
- **Built-in extension pack** — common validators like `email()`, `url()`, `uuid()`, `ip()`, `trim()`, `positive()`, `negative()`, `nonempty()`, `unique()`, and more are included out of the box. The default import has them pre-applied; import from `@cleverbrush/schema/core` to get bare builders without extensions.
|
|
29
|
+
- **14 KB gzipped (full) — 3× smaller than Zod v4** — sub-path imports (`@cleverbrush/schema/string`, `/number`, `/object`, `/array`) drop individual builders to ~4 KB.
|
|
30
|
+
- **First-class nullable support** — `.nullable()` and `.notNullable()` are native methods on every builder. The inferred type automatically includes or excludes `null`, and `introspect()` exposes `isNullable` for runtime metadata.
|
|
31
|
+
- **JSDoc comment preservation** — JSDoc comments on schema properties carry through to the inferred TypeScript type, so IDE tooltips and autocomplete descriptions come from the schema definition itself.
|
|
32
|
+
- **Zero runtime dependencies.**
|
|
33
|
+
|
|
34
|
+
| Feature | @cleverbrush/schema | Zod | Yup | Joi |
|
|
35
|
+
| --- | --- | --- | --- | --- |
|
|
36
|
+
| TypeScript type inference | ✓ | ✓ | ~ | ✗ |
|
|
37
|
+
| [Standard Schema v1](https://standardschema.dev/) | ✓ | ✓ | ✗ | ✗ |
|
|
38
|
+
| **PropertyDescriptors** (runtime introspection) | ✓ | ✗ | ✗ | ✗ |
|
|
39
|
+
| **Type-safe extension system** | ✓ | ✗ | ✗ | ✗ |
|
|
40
|
+
| **Built-in object mapper** | ✓ | ✗ | ✗ | ✗ |
|
|
41
|
+
| **Built-in form generation** | ✓ | ✗ | ✗ | ✗ |
|
|
42
|
+
| Bidirectional JSON Schema | ✓ | ~ (output only) | ✗ | ✗ |
|
|
43
|
+
| **External schema interop** (`extern()`) | ✓ | ✗ | ✗ | ✗ |
|
|
44
|
+
| JSDoc preservation | ✓ | ✗ | ✗ | ✗ |
|
|
45
|
+
| Immutable schemas | ✓ | ✓ | ✗ | ✗ |
|
|
46
|
+
| Zero dependencies | ✓ | ✓ | ✗ | ✗ |
|
|
47
|
+
| Sync + async validation | ✓ | ✓ | ✓ | ✓ |
|
|
48
|
+
| Per-property error inspection | ✓ | ~ | ~ | ~ |
|
|
49
|
+
| Default values | ✓ | ✓ | ✓ | ✓ |
|
|
50
|
+
| Bundle size (full, gzipped) | **14 KB** | 41 KB (v4) | ~19 KB | ~26 KB |
|
|
4
51
|
|
|
5
52
|
## Installation
|
|
6
53
|
|
|
7
54
|
```bash
|
|
8
|
-
|
|
55
|
+
npm install @cleverbrush/schema
|
|
9
56
|
```
|
|
10
57
|
|
|
11
|
-
|
|
58
|
+
## Quick Start
|
|
59
|
+
|
|
60
|
+
[▶ Open in Playground](https://docs.cleverbrush.com/playground/quick-start)
|
|
12
61
|
|
|
13
62
|
```typescript
|
|
14
|
-
import {
|
|
63
|
+
import {
|
|
64
|
+
object,
|
|
65
|
+
string,
|
|
66
|
+
number,
|
|
67
|
+
boolean,
|
|
68
|
+
InferType
|
|
69
|
+
} from '@cleverbrush/schema';
|
|
15
70
|
|
|
71
|
+
// 1. Define a schema with fluent constraints
|
|
16
72
|
const UserSchema = object({
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
73
|
+
name: string().nonempty('Name is required').minLength(2, 'Name must be at least 2 characters'),
|
|
74
|
+
email: string().email('Please enter a valid email'),
|
|
75
|
+
age: number().min(0, 'Age cannot be negative').max(150).positive(),
|
|
76
|
+
isActive: boolean()
|
|
20
77
|
});
|
|
21
78
|
|
|
22
|
-
//
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
};
|
|
79
|
+
// 2. TypeScript type is inferred automatically — no duplication!
|
|
80
|
+
type User = InferType<typeof UserSchema>;
|
|
81
|
+
// Equivalent to: { name: string; email: string; age: number; isActive: boolean }
|
|
26
82
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
83
|
+
// 3. Validate data at runtime — synchronous by default
|
|
84
|
+
const result = UserSchema.validate({
|
|
85
|
+
name: 'Alice',
|
|
86
|
+
email: 'alice@example.com',
|
|
87
|
+
age: 30,
|
|
88
|
+
isActive: true
|
|
89
|
+
});
|
|
31
90
|
|
|
32
|
-
|
|
33
|
-
const
|
|
91
|
+
// Or use validateAsync() when you have async validators/preprocessors
|
|
92
|
+
// const result = await UserSchema.validateAsync({ ... });
|
|
34
93
|
|
|
35
|
-
if (valid) {
|
|
36
|
-
//
|
|
37
|
-
// And `object` has { id: number; name: string; dateOfBirth: Date; } type.
|
|
94
|
+
if (result.valid) {
|
|
95
|
+
console.log('Validated:', result.object); // typed as User
|
|
38
96
|
} else {
|
|
39
|
-
//
|
|
40
|
-
|
|
97
|
+
// For object schemas, prefer getErrorsFor() for per-property error inspection:
|
|
98
|
+
const nameErrors = result.getErrorsFor((p) => p.name);
|
|
99
|
+
console.log(nameErrors.isValid); // false
|
|
100
|
+
console.log(nameErrors.errors); // ['Name must be at least 2 characters']
|
|
101
|
+
|
|
102
|
+
// result.errors on object schemas is deprecated — use getErrorsFor() instead
|
|
103
|
+
console.log('Errors:', result.errors);
|
|
104
|
+
// Array of { message: string }
|
|
41
105
|
}
|
|
42
106
|
```
|
|
43
107
|
|
|
44
|
-
|
|
108
|
+
Type inference works in plain JavaScript too, using JSDoc:
|
|
45
109
|
|
|
46
110
|
```javascript
|
|
47
111
|
/**
|
|
48
112
|
* @type {import('@cleverbrush/schema').InferType<typeof UserSchema>}
|
|
49
113
|
*/
|
|
50
114
|
const user = {
|
|
51
|
-
//
|
|
115
|
+
// type is inferred as { name: string; email: string; age: number; isActive: boolean }
|
|
52
116
|
};
|
|
53
117
|
```
|
|
54
118
|
|
|
55
|
-
See [Documentation](https://docs.cleverbrush.com/modules/_cleverbrush_schema.html) or `docs` folder for more information.
|
|
56
|
-
|
|
57
119
|
## Schema Types
|
|
58
120
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
- `any` - any object. Similar to the `any` type in TypeScript.
|
|
62
|
-
- `string` - string value.
|
|
63
|
-
- `number` - number value.
|
|
64
|
-
- `boolean` - boolean value.
|
|
65
|
-
- `func` - function value.
|
|
66
|
-
- `object` - object schema (you can define list of properties, along with schemas for every property).
|
|
67
|
-
- `date` - defines object of JavaScript `Date` class.
|
|
68
|
-
- `array` - defines array, you can define a schema for Array emelement.
|
|
69
|
-
- `union` - allows to define unions. e.g. `string | number` types (or any combination off schema types from this list).
|
|
70
|
-
- custom schema types. You just need to inherit `SchemaBuilder` abstract class to implement your own schema type.
|
|
71
|
-
|
|
72
|
-
## What is exported from the library?
|
|
73
|
-
|
|
74
|
-
Library exports several functions used to define schemas:
|
|
75
|
-
|
|
76
|
-
- `any`
|
|
77
|
-
- `string`
|
|
78
|
-
- `number`
|
|
79
|
-
- `boolean`
|
|
80
|
-
- `func`
|
|
81
|
-
- `object`
|
|
82
|
-
- `date`
|
|
83
|
-
- `array`
|
|
84
|
-
- `union`
|
|
85
|
-
|
|
86
|
-
All these functions returns so called schema builders.
|
|
87
|
-
Schema builder classes are also exported (in case if you want to develop your own schema builder based on it):
|
|
88
|
-
|
|
89
|
-
- `AnySchemaBuilder`
|
|
90
|
-
- `ArraySchemaBuilder`
|
|
91
|
-
- `BooleanSchemaBuilder`
|
|
92
|
-
- `DateSchemaBuilder`
|
|
93
|
-
- `FunctionSchemaBuilder`
|
|
94
|
-
- `ObjectSchemaBuilder`
|
|
95
|
-
- `NumberSchemaBuilder`
|
|
96
|
-
- `SchemaBuilder` - abstract class.
|
|
97
|
-
- `StringSchemaBuilder`
|
|
98
|
-
- `UnionSchemaBuilder`
|
|
99
|
-
|
|
100
|
-
## Schema Builders Are Immutable
|
|
101
|
-
|
|
102
|
-
All schema builders listed above are immutable, which means that every call of it's methods should return a new Schema builder.
|
|
103
|
-
For example in the example below call to the `.optional()` method will not affect `UserSchema` or any other schemas using it. Instead it will return a new schema builder:
|
|
121
|
+
[▶ Open in Playground](https://docs.cleverbrush.com/playground/schema-types)
|
|
104
122
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
123
|
+
The following builder functions are available:
|
|
124
|
+
|
|
125
|
+
| Function | Description | Key Methods |
|
|
126
|
+
| --------------- | ------------------------------------------------- | --------------------------------------------------------------- |
|
|
127
|
+
| `any()` | Any value. Similar to TypeScript's `any` type. | `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)`, `.addValidator(fn)` |
|
|
128
|
+
| `string()` | String value with constraints. | `.minLength(n)`, `.maxLength(n)`, `.matches(re)`, `.email()`, `.url()`, `.uuid()`, `.ip()`, `.trim()`, `.toLowerCase()`, `.nonempty()`, `.oneOf(...values)`, `.nullable()`, `.notNullable()`, `.default(value)` |
|
|
129
|
+
| `number()` | Numeric value with constraints. | `.min(n)`, `.max(n)`, `.integer()`, `.positive()`, `.negative()`, `.finite()`, `.multipleOf(n)`, `.oneOf(...values)`, `.nullable()`, `.notNullable()`, `.default(value)` |
|
|
130
|
+
| `boolean()` | Boolean value. | `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)` |
|
|
131
|
+
| `date()` | JavaScript `Date` instance. | `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)` |
|
|
132
|
+
| `func()` | Function value. | `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)` |
|
|
133
|
+
| `nul()` | Exactly `null`. Useful in nullable unions. | `.optional()`, `.default(value)` |
|
|
134
|
+
| `object(props)` | Object with typed properties. Supports nesting. | `.validate(data)`, `.addProps({...})`, `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)` |
|
|
135
|
+
| `array()` | Array with optional element schema (via `.of()`). | `.minLength(n)`, `.maxLength(n)`, `.of(schema)`, `.nonempty()`, `.unique()`, `.nullable()`, `.notNullable()`, `.default(value)` |
|
|
136
|
+
| `tuple([...schemas])` | Fixed-length array with per-position types. Each index validated against its own schema — mirrors TypeScript tuple types. | `.rest(schema)`, `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)` |
|
|
137
|
+
| `record(keySchema, valSchema)` | Object with dynamic string keys. Every key must satisfy `keySchema` (a string schema) and every value must satisfy `valSchema` — mirrors TypeScript's `Record<K, V>`. | `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)`, `.addValidator(fn)` |
|
|
138
|
+
| `union(schema)` | Union of schemas — e.g. `string \| number`. | `.or(schema)`, `.validate(data)`, `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)` |
|
|
139
|
+
| `enumOf(...values)` | String enum — sugar for `string().oneOf(...)`. | `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)` |
|
|
140
|
+
| `lazy(getter)` | Recursive/self-referential schema. The getter is called once and its result is cached. Enables tree structures, linked lists, and other recursive types. | `.resolve()`, `.optional()`, `.addValidator(fn)`, `.default(value)` |
|
|
141
|
+
|
|
142
|
+
## Immutability
|
|
143
|
+
|
|
144
|
+
[▶ Open in Playground](https://docs.cleverbrush.com/playground/immutability)
|
|
145
|
+
|
|
146
|
+
All schema builders are immutable. Every method call returns a **new** schema builder instance, so existing schemas are never modified:
|
|
147
|
+
|
|
148
|
+
```typescript
|
|
149
|
+
const base = string().minLength(1);
|
|
150
|
+
const strict = base.maxLength(50); // new instance — base is unchanged
|
|
151
|
+
const loose = base.optional(); // another new instance
|
|
152
|
+
|
|
153
|
+
// base still only has minLength(1)
|
|
154
|
+
// strict has minLength(1) + maxLength(50)
|
|
155
|
+
// loose has minLength(1) + optional
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
This is especially powerful when building a library of reusable schema fragments:
|
|
159
|
+
|
|
160
|
+
```typescript
|
|
161
|
+
const Email = string().minLength(5).maxLength(255);
|
|
162
|
+
const Name = string().minLength(1).maxLength(100);
|
|
163
|
+
|
|
164
|
+
const CreateUser = object({ name: Name, email: Email });
|
|
165
|
+
const UpdateUser = object({ name: Name.optional(), email: Email.optional() });
|
|
166
|
+
// Both schemas share the same base constraints but differ in optionality
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## Composing Schemas
|
|
170
|
+
|
|
171
|
+
[▶ Open in Playground](https://docs.cleverbrush.com/playground/composing-schemas)
|
|
172
|
+
|
|
173
|
+
Schemas can be extended with additional properties, combined with unions, or nested inside arrays and objects:
|
|
174
|
+
|
|
175
|
+
```typescript
|
|
176
|
+
import { object, string, number, array, union } from '@cleverbrush/schema';
|
|
177
|
+
|
|
178
|
+
// Extend an existing schema with new properties
|
|
179
|
+
const BaseEntity = object({
|
|
180
|
+
id: string(),
|
|
181
|
+
createdAt: string()
|
|
109
182
|
});
|
|
110
183
|
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
184
|
+
const UserEntity = BaseEntity.addProps({
|
|
185
|
+
name: string().minLength(2),
|
|
186
|
+
email: string().minLength(5)
|
|
114
187
|
});
|
|
188
|
+
|
|
189
|
+
// Nest objects inside arrays
|
|
190
|
+
const TeamSchema = object({
|
|
191
|
+
name: string().minLength(1),
|
|
192
|
+
members: array().of(UserEntity).minLength(1).maxLength(50)
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
// Union types
|
|
196
|
+
const IdOrEmail = union(string().minLength(1)).or(
|
|
197
|
+
string().matches(/^[^@]+@[^@]+$/)
|
|
198
|
+
);
|
|
115
199
|
```
|
|
116
200
|
|
|
117
|
-
|
|
118
|
-
which can be used to validate objects and infer their types.
|
|
201
|
+
## Record Schemas
|
|
119
202
|
|
|
120
|
-
|
|
203
|
+
[▶ Open in Playground](https://docs.cleverbrush.com/playground/record-basics)
|
|
121
204
|
|
|
122
|
-
|
|
205
|
+
Use `record(keySchema, valueSchema)` to validate objects with **dynamic string keys** — lookup tables, i18n bundles, caches, or any `Record<string, V>` shape. Unlike `object()`, which requires a fixed set of known property names, `record()` validates objects whose keys are not known at schema-definition time.
|
|
206
|
+
|
|
207
|
+
Both the key and the value schema are enforced at runtime, and the inferred TypeScript type mirrors `Record<K, V>`.
|
|
208
|
+
|
|
209
|
+
```typescript
|
|
210
|
+
import { record, string, number, object, InferType } from '@cleverbrush/schema';
|
|
211
|
+
|
|
212
|
+
// ── Basic: string keys → number values ──────────────────────────────────────
|
|
213
|
+
const scores = record(string(), number().min(0).max(100));
|
|
214
|
+
// InferType<typeof scores> → Record<string, number>
|
|
215
|
+
|
|
216
|
+
scores.validate({ alice: 95, bob: 87 }); // { valid: true }
|
|
217
|
+
scores.validate({ alice: 95, bob: -1 }); // { valid: false } — negative score
|
|
218
|
+
|
|
219
|
+
// ── Key constraint — only locale-style keys allowed ──────────────────────────
|
|
220
|
+
const i18n = record(
|
|
221
|
+
string().matches(/^[a-z]{2}(-[A-Z]{2})?$/),
|
|
222
|
+
string().nonempty()
|
|
223
|
+
);
|
|
224
|
+
|
|
225
|
+
i18n.validate({ en: 'Hello', 'fr-FR': 'Bonjour' }); // { valid: true }
|
|
226
|
+
i18n.validate({ '123': 'oops' }); // { valid: false } — bad key
|
|
227
|
+
|
|
228
|
+
// ── Nested: values are objects ───────────────────────────────────────────────
|
|
229
|
+
const userMap = record(
|
|
230
|
+
string(),
|
|
231
|
+
object({ name: string(), age: number() })
|
|
232
|
+
);
|
|
233
|
+
// InferType<typeof userMap> → Record<string, { name: string; age: number }>
|
|
234
|
+
|
|
235
|
+
// ── Optional with factory default ────────────────────────────────────────────
|
|
236
|
+
const cache = record(string(), number()).optional().default(() => ({}));
|
|
237
|
+
|
|
238
|
+
// ── getErrorsFor(key) — rich per-key result with descriptor ────────────────────
|
|
239
|
+
const schema = record(string(), number().min(0));
|
|
240
|
+
const result = schema.validate(
|
|
241
|
+
{ a: 1, b: -2, c: -3 },
|
|
242
|
+
{ doNotStopOnFirstError: true }
|
|
243
|
+
);
|
|
244
|
+
|
|
245
|
+
if (!result.valid) {
|
|
246
|
+
// Root-level errors (e.g. 'object expected')
|
|
247
|
+
const root = result.getErrorsFor();
|
|
248
|
+
console.log(root.isValid); // false if the container itself is invalid
|
|
249
|
+
|
|
250
|
+
// Per-key errors
|
|
251
|
+
const bResult = result.getErrorsFor('b');
|
|
252
|
+
console.log(bResult.isValid); // false
|
|
253
|
+
console.log(bResult.errors[0]); // 'the value must be >= 0'
|
|
254
|
+
console.log(bResult.seenValue); // -2
|
|
255
|
+
|
|
256
|
+
// Descriptor: read/write the entry on the original object
|
|
257
|
+
const descriptor = bResult.descriptor;
|
|
258
|
+
console.log(descriptor.key); // 'b'
|
|
259
|
+
descriptor.getSchema(); // → NumberSchemaBuilder
|
|
260
|
+
descriptor.getValue(result.object); // → { success: true, value: -2 }
|
|
261
|
+
descriptor.setValue(result.object, 0); // fixes the value in-place
|
|
262
|
+
}
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
## Recursive Schemas
|
|
266
|
+
|
|
267
|
+
[▶ Open in Playground](https://docs.cleverbrush.com/playground/recursive-schemas)
|
|
268
|
+
|
|
269
|
+
Use `lazy(() => schema)` to define recursive or self-referential schemas — tree structures, comment threads, nested menus, org charts, and any other type that refers to itself.
|
|
270
|
+
|
|
271
|
+
The getter function is called **once** on first validation, and the resolved schema is cached. Every subsequent call reuses the cache.
|
|
272
|
+
|
|
273
|
+
> **TypeScript limitation:** TypeScript cannot infer recursive types automatically. You must provide an explicit type annotation on the variable holding the schema.
|
|
274
|
+
|
|
275
|
+
```typescript
|
|
276
|
+
import {
|
|
277
|
+
object,
|
|
278
|
+
string,
|
|
279
|
+
number,
|
|
280
|
+
array,
|
|
281
|
+
lazy,
|
|
282
|
+
type SchemaBuilder
|
|
283
|
+
} from '@cleverbrush/schema';
|
|
284
|
+
|
|
285
|
+
// ── Tree structure ───────────────────────────────────────────────
|
|
286
|
+
type TreeNode = { value: number; children: TreeNode[] };
|
|
287
|
+
|
|
288
|
+
// Explicit annotation required — TypeScript can't infer recursive types
|
|
289
|
+
const treeNode: SchemaBuilder<TreeNode, true> = object({
|
|
290
|
+
value: number(),
|
|
291
|
+
children: array(lazy(() => treeNode))
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
treeNode.validate({
|
|
295
|
+
value: 1,
|
|
296
|
+
children: [
|
|
297
|
+
{ value: 2, children: [] },
|
|
298
|
+
{ value: 3, children: [{ value: 4, children: [] }] }
|
|
299
|
+
]
|
|
300
|
+
});
|
|
301
|
+
// { valid: true, object: { value: 1, children: [...] } }
|
|
302
|
+
|
|
303
|
+
// ── Comment thread ───────────────────────────────────────────────
|
|
304
|
+
type Comment = { text: string; replies: Comment[] };
|
|
305
|
+
|
|
306
|
+
const commentSchema: SchemaBuilder<Comment, true> = object({
|
|
307
|
+
text: string(),
|
|
308
|
+
replies: array(lazy(() => commentSchema))
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
// ── Navigation menu with optional sub-levels ─────────────────────
|
|
312
|
+
type MenuItem = { label: string; submenu?: MenuItem[] };
|
|
313
|
+
|
|
314
|
+
const menuItem: SchemaBuilder<MenuItem, true> = object({
|
|
315
|
+
label: string(),
|
|
316
|
+
submenu: array(lazy(() => menuItem)).optional()
|
|
317
|
+
});
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
`lazy()` is fully compatible with `.optional()`, `.addPreprocessor()`, `.addValidator()`, and all other fluent methods. The wrapper's own preprocessors and validators run before delegating to the resolved schema.
|
|
321
|
+
|
|
322
|
+
```typescript
|
|
323
|
+
// Preprocessors and validators work on the lazy wrapper itself
|
|
324
|
+
const schema = lazy(() => string())
|
|
325
|
+
.addPreprocessor((v) => (typeof v === 'number' ? String(v) : v))
|
|
326
|
+
.addValidator((v) => ({ valid: v !== 'forbidden' }));
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
## Discriminated Unions
|
|
330
|
+
|
|
331
|
+
[▶ Open in Playground](https://docs.cleverbrush.com/playground/discriminated-unions)
|
|
332
|
+
|
|
333
|
+
Some libraries ship a dedicated `.discriminator()` API for tagged unions. With `@cleverbrush/schema` you don't need one — `union()` combined with **string-literal schemas** gives you the same pattern naturally, with full type inference.
|
|
334
|
+
|
|
335
|
+
Use `string('literal')` for the discriminator field. Each branch of the union gets its own object schema whose discriminator can only match one exact value. TypeScript narrows the inferred type automatically:
|
|
336
|
+
|
|
337
|
+
```typescript
|
|
338
|
+
import { object, string, number, union, type InferType } from '@cleverbrush/schema';
|
|
339
|
+
|
|
340
|
+
// Each variant has a literal "type" field acting as the discriminator
|
|
341
|
+
const Circle = object({
|
|
342
|
+
type: string('circle'),
|
|
343
|
+
radius: number().min(0)
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
const Rectangle = object({
|
|
347
|
+
type: string('rectangle'),
|
|
348
|
+
width: number().min(0),
|
|
349
|
+
height: number().min(0)
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
const Triangle = object({
|
|
353
|
+
type: string('triangle'),
|
|
354
|
+
base: number().min(0),
|
|
355
|
+
height: number().min(0)
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
// Combine with union() — no special .discriminator() call needed
|
|
359
|
+
const ShapeSchema = union(Circle).or(Rectangle).or(Triangle);
|
|
360
|
+
|
|
361
|
+
type Shape = InferType<typeof ShapeSchema>;
|
|
362
|
+
// Shape is automatically:
|
|
363
|
+
// | { type: 'circle'; radius: number }
|
|
364
|
+
// | { type: 'rectangle'; width: number; height: number }
|
|
365
|
+
// | { type: 'triangle'; base: number; height: number }
|
|
366
|
+
|
|
367
|
+
// Validation picks the matching branch by the literal field
|
|
368
|
+
const result = ShapeSchema.validate({ type: 'circle', radius: 5 });
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
### Real-World Example: Job Scheduler
|
|
372
|
+
|
|
373
|
+
The `@cleverbrush/scheduler` library uses this exact pattern to validate job schedules. The `every` field acts as the discriminator, and each variant adds its own set of allowed properties:
|
|
374
|
+
|
|
375
|
+
```typescript
|
|
376
|
+
import { object, string, number, array, date, union, type InferType } from '@cleverbrush/schema';
|
|
377
|
+
|
|
378
|
+
// Shared base with common schedule fields
|
|
379
|
+
const ScheduleBase = object({
|
|
380
|
+
interval: number().min(1).max(356),
|
|
381
|
+
hour: number().min(0).max(23).optional(),
|
|
382
|
+
minute: number().min(0).max(59).optional(),
|
|
383
|
+
startsOn: date().acceptJsonString().optional(),
|
|
384
|
+
endsOn: date().acceptJsonString().optional()
|
|
385
|
+
});
|
|
386
|
+
|
|
387
|
+
// Minute schedule — omit hour/minute (they don't apply)
|
|
388
|
+
const EveryMinute = ScheduleBase
|
|
389
|
+
.omit('hour').omit('minute')
|
|
390
|
+
.addProps({ every: string('minute') });
|
|
391
|
+
|
|
392
|
+
// Day schedule
|
|
393
|
+
const EveryDay = ScheduleBase
|
|
394
|
+
.addProps({ every: string('day') });
|
|
395
|
+
|
|
396
|
+
// Week schedule — adds dayOfWeek array
|
|
397
|
+
const EveryWeek = ScheduleBase.addProps({
|
|
398
|
+
every: string('week'),
|
|
399
|
+
dayOfWeek: array().of(number().min(1).max(7)).minLength(1).maxLength(7)
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
// Month schedule — adds day (number or 'last')
|
|
403
|
+
const EveryMonth = ScheduleBase.addProps({
|
|
404
|
+
every: string('month'),
|
|
405
|
+
day: union(string('last')).or(number().min(1).max(28))
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
// Combine all variants in a single union
|
|
409
|
+
const ScheduleSchema = union(EveryMinute)
|
|
410
|
+
.or(EveryDay)
|
|
411
|
+
.or(EveryWeek)
|
|
412
|
+
.or(EveryMonth);
|
|
413
|
+
|
|
414
|
+
type Schedule = InferType<typeof ScheduleSchema>;
|
|
415
|
+
// TypeScript infers a proper discriminated union on "every"
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
Because each branch uses a string literal (`string('minute')`, `string('day')`, etc.) for the `every` field, TypeScript can narrow the full union based on that single property — exactly like zod's `z.discriminatedUnion()`, but without any extra API surface.
|
|
419
|
+
|
|
420
|
+
## JSDoc Comment Preservation
|
|
421
|
+
|
|
422
|
+
When you define an object schema, JSDoc comments on properties are preserved in the inferred TypeScript type. This means your IDE tooltips, hover documentation, and autocomplete descriptions all carry through from the schema definition — no need to maintain separate documentation:
|
|
423
|
+
|
|
424
|
+
```typescript
|
|
123
425
|
const UserSchema = object({
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
.
|
|
128
|
-
.
|
|
129
|
-
|
|
426
|
+
/** Full display name of the user */
|
|
427
|
+
name: string().minLength(1).maxLength(200),
|
|
428
|
+
/** Contact email — must be unique across all users */
|
|
429
|
+
email: string().minLength(5),
|
|
430
|
+
/** Age in years. Must be a positive integer. */
|
|
431
|
+
age: number().min(0).max(150)
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
type User = InferType<typeof UserSchema>;
|
|
435
|
+
// Hovering over User.name in your IDE shows:
|
|
436
|
+
// "Full display name of the user"
|
|
437
|
+
// Hovering over User.email shows:
|
|
438
|
+
// "Contact email — must be unique across all users"
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
## Deep Partial
|
|
442
|
+
|
|
443
|
+
[▶ Open in Playground](https://docs.cleverbrush.com/playground/deep-partial)
|
|
444
|
+
|
|
445
|
+
`.deepPartial()` recursively marks **all properties at every nesting level** as optional. It is the deep-object equivalent of a common `DeepPartial<T>` helper type in TypeScript, and is the recommended way to build PATCH API bodies or partial form state.
|
|
446
|
+
|
|
447
|
+
| Schema type | Effect |
|
|
448
|
+
|-------------|--------|
|
|
449
|
+
| `object(…).deepPartial()` | All top-level and nested object properties become optional |
|
|
450
|
+
| Nested `object(…)` inside an object | Recursed — its properties are made optional too |
|
|
451
|
+
| `array(…)`, `union(…)`, primitives | The property itself is made optional; internals are **not** modified |
|
|
452
|
+
|
|
453
|
+
```typescript
|
|
454
|
+
import { object, string, number, array, type InferType } from '@cleverbrush/schema';
|
|
455
|
+
|
|
456
|
+
const CreateUser = object({
|
|
457
|
+
name: string(),
|
|
458
|
+
address: object({
|
|
459
|
+
street: string(),
|
|
460
|
+
city: string()
|
|
461
|
+
})
|
|
462
|
+
});
|
|
463
|
+
|
|
464
|
+
const PatchUser = CreateUser.deepPartial();
|
|
465
|
+
|
|
466
|
+
type PatchUserPayload = InferType<typeof PatchUser>;
|
|
467
|
+
// {
|
|
468
|
+
// name?: string;
|
|
469
|
+
// address?: { street?: string; city?: string };
|
|
470
|
+
// }
|
|
471
|
+
|
|
472
|
+
// All three are valid:
|
|
473
|
+
PatchUser.validate({}); // { valid: true }
|
|
474
|
+
PatchUser.validate({ address: {} }); // { valid: true }
|
|
475
|
+
PatchUser.validate({ address: { city: 'Paris' } }); // { valid: true }
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
Contrast with `.partial()`, which only affects the top level:
|
|
479
|
+
|
|
480
|
+
```typescript
|
|
481
|
+
const ShallowPartial = CreateUser.partial();
|
|
482
|
+
// { name?: string; address?: { street: string; city: string } }
|
|
483
|
+
// ↑ still required inside
|
|
484
|
+
|
|
485
|
+
ShallowPartial.validate({ address: {} });
|
|
486
|
+
// { valid: false } — street and city are still required
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
Chains naturally with other modifiers:
|
|
490
|
+
|
|
491
|
+
```typescript
|
|
492
|
+
const Schema = CreateUser.deepPartial().readonly();
|
|
493
|
+
type T = InferType<typeof Schema>;
|
|
494
|
+
// Readonly<{ name?: string; address?: { street?: string; city?: string } }>
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
> **Note:** `.deepPartial()` recurses only into nested `object()` schemas. Array element schemas and union option schemas are not modified — `array(object({…}))` becomes an optional array but its element shape is unchanged. If you need deep-partialed array elements, apply `.deepPartial()` to the element schema before passing it to `array()`:
|
|
498
|
+
> ```typescript
|
|
499
|
+
> array(InnerSchema.deepPartial()).optional()
|
|
500
|
+
> ```
|
|
501
|
+
|
|
502
|
+
## Validation
|
|
503
|
+
|
|
504
|
+
[▶ Open in Playground](https://docs.cleverbrush.com/playground/validation-errors)
|
|
505
|
+
|
|
506
|
+
Every schema builder has two validation methods:
|
|
507
|
+
|
|
508
|
+
- **`validate(data)`** — synchronous. Returns a `ValidationResult` directly. Throws if any preprocessor, validator, or error message provider returns a Promise.
|
|
509
|
+
- **`validateAsync(data)`** — asynchronous. Returns a `Promise<ValidationResult>`. Supports async preprocessors, validators, and error message providers.
|
|
510
|
+
|
|
511
|
+
Use `validate()` by default for the best performance. Switch to `validateAsync()` only when your schema includes async operations (e.g. database lookups, API calls in validators).
|
|
512
|
+
|
|
513
|
+
```typescript
|
|
514
|
+
// Synchronous validation (default — use when all validators are sync)
|
|
515
|
+
const result = UserSchema.validate(someObject);
|
|
516
|
+
|
|
517
|
+
if (result.valid) {
|
|
518
|
+
console.log(result.object); // typed as InferType<typeof UserSchema>
|
|
519
|
+
} else {
|
|
520
|
+
// For object schemas, prefer getErrorsFor() for per-property error inspection (see below)
|
|
521
|
+
console.log(result.errors); // deprecated for object schemas — Array of { message: string }
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// Async validation (use when validators/preprocessors are async)
|
|
525
|
+
const asyncResult = await UserSchema.validateAsync(someObject);
|
|
526
|
+
```
|
|
527
|
+
|
|
528
|
+
### Collecting All Errors
|
|
529
|
+
|
|
530
|
+
By default, validation stops at the first error. Pass `{ doNotStopOnFirstError: true }` to collect all errors at once:
|
|
531
|
+
|
|
532
|
+
```typescript
|
|
533
|
+
const result = UserSchema.validate(
|
|
534
|
+
{ name: 'A', email: '', age: -5, isActive: true },
|
|
535
|
+
{ doNotStopOnFirstError: true }
|
|
536
|
+
);
|
|
537
|
+
|
|
538
|
+
console.log(result.errors);
|
|
539
|
+
// [
|
|
540
|
+
// { message: 'Name must be at least 2 characters' },
|
|
541
|
+
// { message: 'Please enter a valid email' },
|
|
542
|
+
// { message: 'Age cannot be negative' }
|
|
543
|
+
// ]
|
|
544
|
+
```
|
|
545
|
+
|
|
546
|
+
### Custom Error Messages
|
|
547
|
+
|
|
548
|
+
[▶ Open in Playground](https://docs.cleverbrush.com/playground/custom-error-messages)
|
|
549
|
+
|
|
550
|
+
Every constraint accepts an optional error message — either a plain string or a function:
|
|
551
|
+
|
|
552
|
+
```typescript
|
|
553
|
+
const Name = string()
|
|
554
|
+
.minLength(2, 'Name is too short')
|
|
555
|
+
.maxLength(50, (seen) => `"${seen}" exceeds 50 characters`);
|
|
556
|
+
|
|
557
|
+
const Age = number()
|
|
558
|
+
.min(0, 'Age cannot be negative')
|
|
559
|
+
.max(150, 'Age seems unrealistic');
|
|
560
|
+
```
|
|
561
|
+
|
|
562
|
+
### Custom Validators
|
|
563
|
+
|
|
564
|
+
[▶ Open in Playground](https://docs.cleverbrush.com/playground/custom-validators)
|
|
565
|
+
|
|
566
|
+
Add custom synchronous or asynchronous validators to any schema:
|
|
567
|
+
|
|
568
|
+
```typescript
|
|
569
|
+
const EmailSchema = string()
|
|
570
|
+
.minLength(5, 'Email is too short')
|
|
571
|
+
.addValidator(async (value) => {
|
|
572
|
+
if (value === 'taken@example.com') {
|
|
573
|
+
return {
|
|
574
|
+
valid: false,
|
|
575
|
+
errors: [{ message: 'This email is already registered' }]
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
return { valid: true };
|
|
130
579
|
});
|
|
131
580
|
```
|
|
132
581
|
|
|
133
|
-
|
|
582
|
+
Object-level validators can validate cross-field constraints:
|
|
583
|
+
|
|
584
|
+
```typescript
|
|
585
|
+
const SignupSchema = object({
|
|
586
|
+
password: string().minLength(8),
|
|
587
|
+
confirmPassword: string().minLength(8)
|
|
588
|
+
}).addValidator(async (value) => {
|
|
589
|
+
if (value.password !== value.confirmPassword) {
|
|
590
|
+
return {
|
|
591
|
+
valid: false,
|
|
592
|
+
errors: [{ message: 'Passwords do not match' }]
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
return { valid: true };
|
|
596
|
+
});
|
|
597
|
+
```
|
|
598
|
+
|
|
599
|
+
### Per-Property Errors with `getErrorsFor()` (Recommended)
|
|
600
|
+
|
|
601
|
+
`ObjectSchemaBuilder.validate()` returns an extended result with a `getErrorsFor()` method for inspecting errors on individual properties — perfect for showing inline form errors. **This is the recommended way to inspect validation errors on object schemas** and replaces the deprecated `errors` array on `ObjectSchemaValidationResult`:
|
|
602
|
+
|
|
603
|
+
```typescript
|
|
604
|
+
const PersonSchema = object({
|
|
605
|
+
name: string().minLength(1),
|
|
606
|
+
address: object({
|
|
607
|
+
city: string(),
|
|
608
|
+
zip: number()
|
|
609
|
+
})
|
|
610
|
+
});
|
|
611
|
+
|
|
612
|
+
const result = PersonSchema.validate(person, {
|
|
613
|
+
doNotStopOnFirstError: true
|
|
614
|
+
});
|
|
615
|
+
|
|
616
|
+
if (!result.valid) {
|
|
617
|
+
// Get errors for a single property
|
|
618
|
+
const nameErrors = result.getErrorsFor((p) => p.name);
|
|
619
|
+
console.log(nameErrors.isValid); // false
|
|
620
|
+
console.log(nameErrors.errors); // ['must be at least 1 character']
|
|
621
|
+
console.log(nameErrors.seenValue); // the value that was validated
|
|
622
|
+
|
|
623
|
+
// Works with nested properties too
|
|
624
|
+
const cityErrors = result.getErrorsFor((p) => p.address.city);
|
|
625
|
+
console.log(cityErrors.errors);
|
|
626
|
+
}
|
|
627
|
+
```
|
|
628
|
+
|
|
629
|
+
## PropertyDescriptors
|
|
630
|
+
|
|
631
|
+
PropertyDescriptors are a runtime metadata tree attached to each property in an object schema. They provide type-safe access to property values, schema builders, and parent descriptors. This is what makes the entire Cleverbrush ecosystem work:
|
|
632
|
+
|
|
633
|
+
- [`@cleverbrush/mapper`](../mapper) uses them as **selectors** (like C# expression trees) to point at source and target properties type-safely.
|
|
634
|
+
- [`@cleverbrush/react-form`](../react-form) uses them to bind form fields to schema properties and read their validation constraints automatically.
|
|
635
|
+
|
|
636
|
+
```typescript
|
|
637
|
+
import {
|
|
638
|
+
object,
|
|
639
|
+
string,
|
|
640
|
+
number,
|
|
641
|
+
ObjectSchemaBuilder
|
|
642
|
+
} from '@cleverbrush/schema';
|
|
643
|
+
|
|
644
|
+
const UserSchema = object({
|
|
645
|
+
name: string().minLength(2),
|
|
646
|
+
address: object({
|
|
647
|
+
city: string(),
|
|
648
|
+
zip: number()
|
|
649
|
+
})
|
|
650
|
+
});
|
|
651
|
+
|
|
652
|
+
// Get the PropertyDescriptor tree
|
|
653
|
+
const tree = ObjectSchemaBuilder.getPropertiesFor(UserSchema);
|
|
654
|
+
|
|
655
|
+
// Use descriptors as selectors in mapper and react-form:
|
|
656
|
+
// mapper: .for((t) => t.name).from((s) => s.name)
|
|
657
|
+
// react-form: <Field selector={(t) => t.address.city} form={form} />
|
|
658
|
+
```
|
|
659
|
+
|
|
660
|
+
## Default Values
|
|
661
|
+
|
|
662
|
+
Every schema builder supports `.default(value)`. When the input is `undefined`, the default value is used instead — and the result is still validated against the schema's constraints.
|
|
663
|
+
|
|
664
|
+
```typescript
|
|
665
|
+
import { string, number, array, object, InferType } from '@cleverbrush/schema';
|
|
666
|
+
|
|
667
|
+
// Static default
|
|
668
|
+
const Name = string().default('Anonymous');
|
|
669
|
+
Name.validate(undefined); // { valid: true, object: 'Anonymous' }
|
|
670
|
+
Name.validate('Alice'); // { valid: true, object: 'Alice' }
|
|
671
|
+
|
|
672
|
+
// Factory function — useful for mutable defaults
|
|
673
|
+
const Tags = array(string()).default(() => []);
|
|
674
|
+
|
|
675
|
+
// Works with .optional() — removes undefined from the type
|
|
676
|
+
const Port = number().optional().default(3000);
|
|
677
|
+
type Port = InferType<typeof Port>; // number (not number | undefined)
|
|
678
|
+
```
|
|
679
|
+
|
|
680
|
+
Use a factory function for mutable values (arrays, objects) to avoid shared references:
|
|
681
|
+
|
|
682
|
+
```typescript
|
|
683
|
+
const Config = object({
|
|
684
|
+
host: string().default('localhost'),
|
|
685
|
+
port: number().default(8080),
|
|
686
|
+
tags: array(string()).default(() => [])
|
|
687
|
+
});
|
|
688
|
+
|
|
689
|
+
type Config = InferType<typeof Config>;
|
|
690
|
+
// { host: string; port: number; tags: string[] }
|
|
691
|
+
// All fields are non-optional — defaults fill in missing values
|
|
692
|
+
```
|
|
693
|
+
|
|
694
|
+
Default values are exposed via `.introspect()`:
|
|
695
|
+
|
|
696
|
+
```typescript
|
|
697
|
+
const schema = string().default('hello');
|
|
698
|
+
const info = schema.introspect();
|
|
699
|
+
console.log(info.hasDefault); // true
|
|
700
|
+
console.log(info.defaultValue); // 'hello'
|
|
701
|
+
```
|
|
702
|
+
|
|
703
|
+
## Catch / Fallback
|
|
134
704
|
|
|
135
|
-
|
|
136
|
-
|
|
705
|
+
Every schema builder supports `.catch(value)`. When validation **fails for any reason** — wrong type, constraint violation, missing required value — the fallback is returned as a successful result instead of errors.
|
|
706
|
+
|
|
707
|
+
Unlike `.default()`, which only fires when the input is `undefined`, `.catch()` fires on **any** validation failure.
|
|
708
|
+
|
|
709
|
+
```typescript
|
|
710
|
+
import { string, number, array, object } from '@cleverbrush/schema';
|
|
711
|
+
|
|
712
|
+
// Static fallback
|
|
713
|
+
const Name = string().catch('unknown');
|
|
714
|
+
Name.validate(42); // { valid: true, object: 'unknown' }
|
|
715
|
+
Name.validate(null); // { valid: true, object: 'unknown' }
|
|
716
|
+
Name.validate('Alice'); // { valid: true, object: 'Alice' }
|
|
717
|
+
|
|
718
|
+
// Constraint violation also triggers catch
|
|
719
|
+
const Age = number().min(0).catch(-1);
|
|
720
|
+
Age.validate(-5); // { valid: true, object: -1 }
|
|
721
|
+
|
|
722
|
+
// .parse() and .parseAsync() never throw when .catch() is set
|
|
723
|
+
Name.parse(42); // 'unknown' (no SchemaValidationError thrown)
|
|
724
|
+
```
|
|
725
|
+
|
|
726
|
+
Use a factory function for mutable fallback values to avoid shared references:
|
|
727
|
+
|
|
728
|
+
```typescript
|
|
729
|
+
const Tags = array(string()).catch(() => []);
|
|
730
|
+
|
|
731
|
+
const r1 = Tags.validate(null); // { valid: true, object: [] }
|
|
732
|
+
const r2 = Tags.validate(null); // { valid: true, object: [] }
|
|
733
|
+
// r1.object !== r2.object — separate array instances each time
|
|
734
|
+
```
|
|
735
|
+
|
|
736
|
+
The fallback state is exposed via `.introspect()`:
|
|
737
|
+
|
|
738
|
+
```typescript
|
|
739
|
+
const schema = string().catch('unknown');
|
|
740
|
+
const info = schema.introspect();
|
|
741
|
+
console.log(info.hasCatch); // true
|
|
742
|
+
console.log(info.catchValue); // 'unknown'
|
|
743
|
+
```
|
|
744
|
+
|
|
745
|
+
## Readonly Modifier
|
|
746
|
+
|
|
747
|
+
Every schema builder supports `.readonly()`. This is a **type-level-only** modifier — it marks the inferred TypeScript type as immutable, but does not alter validation behaviour or freeze the validated value at runtime.
|
|
748
|
+
|
|
749
|
+
| Builder | Effect on `InferType<T>` |
|
|
750
|
+
|---------|--------------------------|
|
|
751
|
+
| `object(…).readonly()` | `Readonly<{ … }>` — all top-level properties become `readonly` |
|
|
752
|
+
| `array(…).readonly()` | `ReadonlyArray<T>` — no `push`, `pop`, etc. at the type level |
|
|
753
|
+
| `string().readonly()` | `string` (identity — primitives are already immutable) |
|
|
754
|
+
| `number().readonly()` | `number` (identity) |
|
|
755
|
+
| `boolean().readonly()` | `boolean` (identity) |
|
|
756
|
+
| `date().readonly()` | `Readonly<Date>` |
|
|
757
|
+
|
|
758
|
+
```typescript
|
|
759
|
+
import { object, array, string, number, InferType } from '@cleverbrush/schema';
|
|
760
|
+
|
|
761
|
+
// Readonly object
|
|
762
|
+
const UserSchema = object({ name: string(), age: number() }).readonly();
|
|
763
|
+
type User = InferType<typeof UserSchema>;
|
|
764
|
+
// Readonly<{ name: string; age: number }>
|
|
765
|
+
|
|
766
|
+
// Readonly array
|
|
767
|
+
const TagsSchema = array(string()).readonly();
|
|
768
|
+
type Tags = InferType<typeof TagsSchema>;
|
|
769
|
+
// ReadonlyArray<string>
|
|
770
|
+
|
|
771
|
+
// Validation behaviour is unchanged
|
|
772
|
+
const result = UserSchema.validate({ name: 'Alice', age: 30 });
|
|
773
|
+
// { valid: true, object: { name: 'Alice', age: 30 } }
|
|
774
|
+
```
|
|
775
|
+
|
|
776
|
+
Chains naturally with `.optional()` and `.default()`:
|
|
777
|
+
|
|
778
|
+
```typescript
|
|
779
|
+
const Schema = object({ id: number() }).readonly().optional();
|
|
780
|
+
type T = InferType<typeof Schema>;
|
|
781
|
+
// Readonly<{ id: number }> | undefined
|
|
782
|
+
```
|
|
783
|
+
|
|
784
|
+
The `isReadonly` flag is exposed via `.introspect()` for tooling:
|
|
785
|
+
|
|
786
|
+
```typescript
|
|
787
|
+
const schema = object({ name: string() }).readonly();
|
|
788
|
+
console.log(schema.introspect().isReadonly); // true
|
|
789
|
+
```
|
|
790
|
+
|
|
791
|
+
> **Note:** `.readonly()` is **shallow** — only top-level object properties or the array itself are marked readonly. For deeply nested immutability consider applying `.readonly()` at each level, or use a `DeepReadonly` utility type post-validation.
|
|
792
|
+
|
|
793
|
+
## Describe
|
|
794
|
+
|
|
795
|
+
Every schema builder supports `.describe(text)`. This is a **metadata-only** modifier — it stores a human-readable description on the schema at runtime with no effect on validation.
|
|
796
|
+
|
|
797
|
+
```typescript
|
|
798
|
+
const UserSchema = object({
|
|
799
|
+
name: string().describe("The user's full name"),
|
|
800
|
+
age: number().optional().describe('Age in years'),
|
|
801
|
+
}).describe('A user object');
|
|
802
|
+
|
|
803
|
+
// Read the description back at runtime
|
|
804
|
+
UserSchema.introspect().description; // 'A user object'
|
|
805
|
+
```
|
|
806
|
+
|
|
807
|
+
The description is accessible via `.introspect().description` and chains naturally with all other modifiers:
|
|
808
|
+
|
|
809
|
+
```typescript
|
|
810
|
+
string().describe('A name').optional().readonly()
|
|
811
|
+
// ^ InferType is string | undefined, isReadonly: true, description: 'A name'
|
|
812
|
+
```
|
|
813
|
+
|
|
814
|
+
When using `@cleverbrush/schema-json`, descriptions round-trip through JSON Schema's standard `description` field:
|
|
815
|
+
|
|
816
|
+
```typescript
|
|
817
|
+
import { toJsonSchema, fromJsonSchema } from '@cleverbrush/schema-json';
|
|
818
|
+
|
|
819
|
+
const spec = toJsonSchema(string().describe('A name'), { $schema: false });
|
|
820
|
+
// { type: 'string', description: 'A name' }
|
|
821
|
+
|
|
822
|
+
const schema = fromJsonSchema({ type: 'string', description: 'A name' } as const);
|
|
823
|
+
schema.introspect().description; // 'A name'
|
|
824
|
+
```
|
|
825
|
+
|
|
826
|
+
## Extensions
|
|
827
|
+
|
|
828
|
+
[▶ Open in Playground](https://docs.cleverbrush.com/playground/custom-extensions)
|
|
829
|
+
|
|
830
|
+
The extension system lets you add **custom methods** to any schema builder type without modifying the core library. Define an extension once, apply it with `withExtensions()`, and every builder produced by the returned factories includes your new methods — fully typed and chainable.
|
|
831
|
+
|
|
832
|
+
### Defining an Extension
|
|
833
|
+
|
|
834
|
+
Use `defineExtension()` to declare which builder types your extension targets and what methods it adds. Extension methods receive `this` bound to the builder instance and must return a builder to support fluent chaining:
|
|
835
|
+
|
|
836
|
+
```typescript
|
|
837
|
+
import {
|
|
838
|
+
defineExtension,
|
|
839
|
+
withExtensions,
|
|
840
|
+
StringSchemaBuilder,
|
|
841
|
+
NumberSchemaBuilder,
|
|
842
|
+
DateSchemaBuilder
|
|
843
|
+
} from '@cleverbrush/schema';
|
|
844
|
+
|
|
845
|
+
// Email extension — adds .email() to string builders
|
|
846
|
+
const emailExt = defineExtension({
|
|
847
|
+
string: {
|
|
848
|
+
email(this: StringSchemaBuilder) {
|
|
849
|
+
return this.addValidator((val) => {
|
|
850
|
+
const valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val as string);
|
|
851
|
+
return {
|
|
852
|
+
valid,
|
|
853
|
+
errors: valid
|
|
854
|
+
? []
|
|
855
|
+
: [{ message: 'Invalid email address' }]
|
|
856
|
+
};
|
|
857
|
+
});
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
});
|
|
861
|
+
|
|
862
|
+
// Port extension — adds .port() to number builders
|
|
863
|
+
const portExt = defineExtension({
|
|
864
|
+
number: {
|
|
865
|
+
port(this: NumberSchemaBuilder) {
|
|
866
|
+
return this.isInteger().min(1).max(65535);
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
});
|
|
870
|
+
|
|
871
|
+
// Slug extension — adds .slug() to string builders
|
|
872
|
+
const slugExt = defineExtension({
|
|
873
|
+
string: {
|
|
874
|
+
slug(this: StringSchemaBuilder) {
|
|
875
|
+
return this.addValidator((val) => {
|
|
876
|
+
const valid = /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(val as string);
|
|
877
|
+
return {
|
|
878
|
+
valid,
|
|
879
|
+
errors: valid
|
|
880
|
+
? []
|
|
881
|
+
: [{ message: 'Must be a valid URL slug' }]
|
|
882
|
+
};
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
});
|
|
887
|
+
```
|
|
888
|
+
|
|
889
|
+
### Using Extensions
|
|
890
|
+
|
|
891
|
+
Pass one or more extension descriptors to `withExtensions()` to get augmented factory functions. All original builder methods remain available and fully chainable alongside the new ones:
|
|
892
|
+
|
|
893
|
+
```typescript
|
|
894
|
+
const s = withExtensions(emailExt, portExt, slugExt);
|
|
895
|
+
|
|
896
|
+
// .email() and .slug() are now available on string builders
|
|
897
|
+
const EmailSchema = s.string().email().minLength(5);
|
|
898
|
+
const SlugSchema = s.string().slug().minLength(1).maxLength(200);
|
|
899
|
+
|
|
900
|
+
// .port() is now available on number builders
|
|
901
|
+
const PortSchema = s.number().port();
|
|
902
|
+
|
|
903
|
+
// Use in object schemas — just like normal builders
|
|
904
|
+
const ServerConfig = s.object({
|
|
905
|
+
adminEmail: s.string().email(),
|
|
906
|
+
port: s.number().port(),
|
|
907
|
+
slug: s.string().slug(),
|
|
908
|
+
name: s.string().minLength(1)
|
|
909
|
+
});
|
|
910
|
+
|
|
911
|
+
// Validate as usual
|
|
912
|
+
const result = ServerConfig.validate({
|
|
913
|
+
adminEmail: 'admin@example.com',
|
|
914
|
+
port: 8080,
|
|
915
|
+
slug: 'my-server',
|
|
916
|
+
name: 'Production'
|
|
917
|
+
});
|
|
918
|
+
```
|
|
919
|
+
|
|
920
|
+
### Multi-Builder Extensions
|
|
921
|
+
|
|
922
|
+
A single extension can target multiple builder types:
|
|
923
|
+
|
|
924
|
+
```typescript
|
|
925
|
+
const timestampsExt = defineExtension({
|
|
926
|
+
string: {
|
|
927
|
+
/** Marks this string property as an ISO timestamp */
|
|
928
|
+
isoTimestamp(this: StringSchemaBuilder) {
|
|
929
|
+
return this.addValidator((val) => {
|
|
930
|
+
const valid = !isNaN(Date.parse(val as string));
|
|
931
|
+
return {
|
|
932
|
+
valid,
|
|
933
|
+
errors: valid
|
|
934
|
+
? []
|
|
935
|
+
: [{ message: 'Must be a valid ISO timestamp' }]
|
|
936
|
+
};
|
|
937
|
+
});
|
|
938
|
+
}
|
|
939
|
+
},
|
|
940
|
+
date: {
|
|
941
|
+
/** Adds a validator that rejects dates in the future */
|
|
942
|
+
pastOnly(this: DateSchemaBuilder) {
|
|
943
|
+
return this.addValidator((val) => {
|
|
944
|
+
const valid = (val as Date) <= new Date();
|
|
945
|
+
return {
|
|
946
|
+
valid,
|
|
947
|
+
errors: valid ? [] : [{ message: 'Date must be in the past' }]
|
|
948
|
+
};
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
});
|
|
953
|
+
```
|
|
954
|
+
|
|
955
|
+
### Extension Metadata & Introspection
|
|
956
|
+
|
|
957
|
+
Extension methods automatically record metadata that can be inspected at runtime via `.introspect().extensions`. The system auto-infers the metadata value based on the arguments passed to the extension method:
|
|
958
|
+
|
|
959
|
+
- **Zero-arg methods** → metadata value is `true`
|
|
960
|
+
- **Single-arg methods** → metadata value is the argument itself
|
|
961
|
+
- **Multi-arg methods** → metadata value is the arguments array
|
|
962
|
+
|
|
963
|
+
```typescript
|
|
964
|
+
const s = withExtensions(emailExt, portExt);
|
|
965
|
+
|
|
966
|
+
// Zero-arg method — metadata is `true`
|
|
967
|
+
const emailSchema = s.string().email();
|
|
968
|
+
console.log(emailSchema.introspect().extensions.email); // true
|
|
969
|
+
|
|
970
|
+
// Single-arg method — metadata is the argument
|
|
971
|
+
const rangeExt = defineExtension({
|
|
972
|
+
number: {
|
|
973
|
+
percentage(this: NumberSchemaBuilder) {
|
|
974
|
+
return this.min(0).max(100);
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
});
|
|
978
|
+
const s2 = withExtensions(rangeExt);
|
|
979
|
+
const pctSchema = s2.number().percentage();
|
|
980
|
+
console.log(pctSchema.introspect().extensions.percentage); // true
|
|
981
|
+
|
|
982
|
+
// Multi-arg method — metadata is the arguments array
|
|
983
|
+
const rangeExt2 = defineExtension({
|
|
984
|
+
number: {
|
|
985
|
+
range(this: NumberSchemaBuilder, min: number, max: number) {
|
|
986
|
+
return this.min(min).max(max);
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
});
|
|
990
|
+
const s3 = withExtensions(rangeExt2);
|
|
991
|
+
const rangeSchema = s3.number().range(0, 100);
|
|
992
|
+
console.log(rangeSchema.introspect().extensions.range); // [0, 100]
|
|
993
|
+
```
|
|
994
|
+
|
|
995
|
+
### Custom Metadata
|
|
996
|
+
|
|
997
|
+
If you need structured metadata (e.g. an object with named fields rather than the raw arguments), call `this.withExtension(key, value)` explicitly inside the method. The auto-infer logic detects the existing key and skips automatic attachment:
|
|
998
|
+
|
|
999
|
+
```typescript
|
|
1000
|
+
const currencyExt = defineExtension({
|
|
1001
|
+
number: {
|
|
1002
|
+
currency(this: NumberSchemaBuilder, opts?: { maxDecimals?: number }) {
|
|
1003
|
+
const maxDec = opts?.maxDecimals ?? 2;
|
|
1004
|
+
// Explicit withExtension() call — auto-infer is skipped
|
|
1005
|
+
return this
|
|
1006
|
+
.withExtension('currency', { maxDecimals: maxDec })
|
|
1007
|
+
.min(0)
|
|
1008
|
+
.addValidator((val) => {
|
|
1009
|
+
const decimals = (String(val).split('.')[1] ?? '').length;
|
|
1010
|
+
const valid = decimals <= maxDec;
|
|
1011
|
+
return {
|
|
1012
|
+
valid,
|
|
1013
|
+
errors: valid
|
|
1014
|
+
? []
|
|
1015
|
+
: [{ message: `Max ${maxDec} decimal places` }]
|
|
1016
|
+
};
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
});
|
|
1021
|
+
|
|
1022
|
+
const s = withExtensions(currencyExt);
|
|
1023
|
+
const priceSchema = s.number().currency({ maxDecimals: 4 });
|
|
1024
|
+
console.log(priceSchema.introspect().extensions.currency);
|
|
1025
|
+
// { maxDecimals: 4 } — structured metadata, not the raw args
|
|
1026
|
+
```
|
|
1027
|
+
|
|
1028
|
+
### Stacking Extensions
|
|
1029
|
+
|
|
1030
|
+
Multiple extensions can be stacked — their methods are merged per builder type. A runtime error is thrown if two extensions define the same method name on the same builder type:
|
|
1031
|
+
|
|
1032
|
+
```typescript
|
|
1033
|
+
// All three extensions target StringSchemaBuilder
|
|
1034
|
+
const s = withExtensions(emailExt, slugExt, trimmedExt);
|
|
1035
|
+
|
|
1036
|
+
// All methods are available and chainable
|
|
1037
|
+
const schema = s.string().email().slug().trimmed().minLength(5);
|
|
1038
|
+
```
|
|
1039
|
+
|
|
1040
|
+
### Validation
|
|
1041
|
+
|
|
1042
|
+
`defineExtension()` validates the configuration eagerly:
|
|
1043
|
+
|
|
1044
|
+
- **Unknown builder type names** throw immediately (e.g. `{ str: { ... } }` instead of `{ string: { ... } }`)
|
|
1045
|
+
- **Reserved method names** cannot be overridden — `validate`, `introspect`, `optional`, `required`, `addValidator`, `addPreprocessor`, `withExtension`, `getExtension`, etc.
|
|
1046
|
+
- **Non-function values** in the method record are rejected
|
|
1047
|
+
|
|
1048
|
+
```typescript
|
|
1049
|
+
// ❌ Throws: Unknown builder type "str"
|
|
1050
|
+
defineExtension({ str: { foo() { return this; } } });
|
|
1051
|
+
|
|
1052
|
+
// ❌ Throws: Cannot override reserved method "validate"
|
|
1053
|
+
defineExtension({ string: { validate() { return this; } } });
|
|
1054
|
+
```
|
|
1055
|
+
|
|
1056
|
+
### Extension API Reference
|
|
1057
|
+
|
|
1058
|
+
| Function / Type | Description |
|
|
1059
|
+
| ------------------------------ | -------------------------------------------------------------------------------------------------------- |
|
|
1060
|
+
| `defineExtension(config)` | Defines an extension. `config` is an `ExtensionConfig` keyed by builder type name. Returns an `ExtensionDescriptor`. |
|
|
1061
|
+
| `withExtensions(...exts)` | Accepts one or more `ExtensionDescriptor`s. Returns an object with augmented factory functions (`string`, `number`, `boolean`, `date`, `object`, `array`, `union`, `func`, `any`). |
|
|
1062
|
+
| `ExtensionConfig` | Type for the configuration object passed to `defineExtension`. Maps builder type names to method records. |
|
|
1063
|
+
| `ExtensionDescriptor` | Branded type returned by `defineExtension`. Pass to `withExtensions()` to apply. |
|
|
1064
|
+
|
|
1065
|
+
## Built-in Extensions
|
|
1066
|
+
|
|
1067
|
+
[▶ Open in Playground](https://docs.cleverbrush.com/playground/builtin-extensions)
|
|
1068
|
+
|
|
1069
|
+
The default import from `@cleverbrush/schema` includes a pre-applied extension pack with common validators. You get these methods automatically — no extra setup required:
|
|
1070
|
+
|
|
1071
|
+
### String Extensions
|
|
1072
|
+
|
|
1073
|
+
| Method | Description | Metadata |
|
|
1074
|
+
| --- | --- | --- |
|
|
1075
|
+
| `.email(errorMessage?)` | Validates email format | `true` |
|
|
1076
|
+
| `.url(opts?, errorMessage?)` | Validates URL format. `opts.protocols` narrows allowed schemes (default: `http`, `https`) | `true` or `{ protocols }` |
|
|
1077
|
+
| `.uuid(errorMessage?)` | Validates RFC 4122 UUID format (versions 1–5) | `true` |
|
|
1078
|
+
| `.ip(opts?, errorMessage?)` | Validates IPv4 or IPv6 address. `opts.version` narrows to `'v4'` or `'v6'` | `true` or `{ version }` |
|
|
1079
|
+
| `.trim()` | Preprocessor — trims whitespace before validation | `true` |
|
|
1080
|
+
| `.toLowerCase()` | Preprocessor — lowercases value before validation | `true` |
|
|
1081
|
+
| `.nonempty(errorMessage?)` | Rejects empty strings | `true` |
|
|
1082
|
+
|
|
1083
|
+
### Number Extensions
|
|
1084
|
+
|
|
1085
|
+
| Method | Description | Metadata |
|
|
1086
|
+
| --- | --- | --- |
|
|
1087
|
+
| `.positive(errorMessage?)` | Value must be > 0 | `true` |
|
|
1088
|
+
| `.negative(errorMessage?)` | Value must be < 0 | `true` |
|
|
1089
|
+
| `.finite(errorMessage?)` | Value must be finite (not `Infinity` / `-Infinity`) | `true` |
|
|
1090
|
+
| `.multipleOf(n, errorMessage?)` | Value must be an exact multiple of `n` (float-safe) | `n` |
|
|
1091
|
+
|
|
1092
|
+
### Array Extensions
|
|
1093
|
+
|
|
1094
|
+
| Method | Description | Metadata |
|
|
1095
|
+
| --- | --- | --- |
|
|
1096
|
+
| `.nonempty(errorMessage?)` | Array must have at least one element | `true` |
|
|
1097
|
+
| `.unique(keyFn?, errorMessage?)` | All elements must be unique. Optional `keyFn` extracts comparison key for objects | `true` or `keyFn` |
|
|
1098
|
+
|
|
1099
|
+
### Nullable / Not Nullable
|
|
1100
|
+
|
|
1101
|
+
`.nullable()` and `.notNullable()` are **native methods** available on every builder — no extension required.
|
|
1102
|
+
|
|
1103
|
+
| Method | Available on | Description |
|
|
1104
|
+
| --- | --- | --- |
|
|
1105
|
+
| `.nullable()` | all builders | Marks the schema as nullable — `null` is accepted as a valid value. The inferred type changes from `T` to `T \| null`. |
|
|
1106
|
+
| `.notNullable()` | all builders | Removes the nullable mark — `null` is no longer accepted. The inferred type changes from `T \| null` back to `T`. |
|
|
1107
|
+
|
|
1108
|
+
```typescript
|
|
1109
|
+
import { string, number, object, InferType } from '@cleverbrush/schema';
|
|
1110
|
+
|
|
1111
|
+
const name = string().nullable();
|
|
1112
|
+
type Name = InferType<typeof name>; // string | null
|
|
1113
|
+
|
|
1114
|
+
// Works with any builder
|
|
1115
|
+
const score = number().positive().nullable(); // number | null
|
|
1116
|
+
|
|
1117
|
+
// Chaining: validators before .nullable()
|
|
1118
|
+
const email = string().email().nullable(); // string | null
|
|
1119
|
+
|
|
1120
|
+
// Optional + nullable: accepts string | null | undefined
|
|
1121
|
+
const bio = string().optional().nullable();
|
|
1122
|
+
|
|
1123
|
+
// Nested inside objects
|
|
1124
|
+
const User = object({
|
|
1125
|
+
name: string().nonempty(),
|
|
1126
|
+
bio: string().nullable(), // string | null
|
|
1127
|
+
age: number().nullable(), // number | null
|
|
1128
|
+
});
|
|
1129
|
+
|
|
1130
|
+
User.validate({ name: 'Alice', bio: null, age: null }); // valid
|
|
1131
|
+
|
|
1132
|
+
// Toggle back with .notNullable()
|
|
1133
|
+
const strictName = string().nullable().notNullable();
|
|
1134
|
+
type StrictName = InferType<typeof strictName>; // string (not string | null)
|
|
1135
|
+
|
|
1136
|
+
strictName.validate(null); // invalid
|
|
1137
|
+
strictName.validate('Alice'); // valid
|
|
1138
|
+
|
|
1139
|
+
// Introspect at runtime
|
|
1140
|
+
string().nullable().introspect().isNullable; // true
|
|
1141
|
+
string().nullable().notNullable().introspect().isNullable; // false
|
|
1142
|
+
```
|
|
1143
|
+
|
|
1144
|
+
### Enum / oneOf Extension
|
|
1145
|
+
|
|
1146
|
+
| Method | Available on | Description |
|
|
1147
|
+
| --- | --- | --- |
|
|
1148
|
+
| `.oneOf(...values)` | `string`, `number` | Constrains the value to one of the given literals and **narrows the inferred type** to the literal union. |
|
|
1149
|
+
| `.oneOf(valuesArray, errorMessage?)` | `string`, `number` | Array-form with an optional custom error message (string or factory). |
|
|
1150
|
+
| `enumOf(...values)` | top-level factory | Sugar for `string().oneOf(...)`. Mirrors Zod's `z.enum()`. |
|
|
1151
|
+
| `enumOf(valuesArray, errorMessage?)` | top-level factory | Array-form with an optional custom error message. |
|
|
1152
|
+
|
|
1153
|
+
```typescript
|
|
1154
|
+
import { string, number, enumOf, InferType } from '@cleverbrush/schema';
|
|
1155
|
+
|
|
1156
|
+
// String enum — infers 'admin' | 'user' | 'guest'
|
|
1157
|
+
const Role = enumOf('admin', 'user', 'guest');
|
|
1158
|
+
type Role = InferType<typeof Role>;
|
|
1159
|
+
|
|
1160
|
+
Role.validate('admin'); // valid
|
|
1161
|
+
Role.validate('other'); // invalid — "must be one of: admin, user, guest"
|
|
1162
|
+
|
|
1163
|
+
// Equivalent long-form
|
|
1164
|
+
const Role2 = string().oneOf('admin', 'user', 'guest');
|
|
1165
|
+
|
|
1166
|
+
// Number enum — infers 1 | 2 | 3
|
|
1167
|
+
const Priority = number().oneOf(1, 2, 3);
|
|
1168
|
+
type Priority = InferType<typeof Priority>;
|
|
1169
|
+
|
|
1170
|
+
// Chains with nullable / optional
|
|
1171
|
+
const OptionalRole = enumOf('admin', 'user').nullable(); // 'admin' | 'user' | null
|
|
1172
|
+
|
|
1173
|
+
// Runtime access to allowed values via introspect
|
|
1174
|
+
Role.introspect().extensions?.oneOf; // ['admin', 'user', 'guest']
|
|
1175
|
+
```
|
|
1176
|
+
|
|
1177
|
+
#### Custom error messages for `.oneOf()`
|
|
1178
|
+
|
|
1179
|
+
`.oneOf()` accepts a custom error message via the **array form**, where the allowed values are passed as an array and the error message is the second argument:
|
|
1180
|
+
|
|
1181
|
+
```typescript
|
|
1182
|
+
import { string, number, enumOf } from '@cleverbrush/schema';
|
|
1183
|
+
|
|
1184
|
+
// String — array form with custom string error message
|
|
1185
|
+
const role = string().oneOf(['admin', 'user', 'guest'], 'Invalid role');
|
|
1186
|
+
role.validate('other'); // invalid — "Invalid role"
|
|
1187
|
+
|
|
1188
|
+
// String — array form with factory function
|
|
1189
|
+
const role2 = string().oneOf(
|
|
1190
|
+
['admin', 'user'],
|
|
1191
|
+
(val) => `"${val}" is not a valid role`
|
|
1192
|
+
);
|
|
1193
|
+
|
|
1194
|
+
// enumOf — array form with custom error message
|
|
1195
|
+
const Role = enumOf(['admin', 'user', 'guest'], 'Invalid role');
|
|
1196
|
+
|
|
1197
|
+
// Number — trailing error message (unambiguous since values are numbers)
|
|
1198
|
+
const priority = number().oneOf(1, 2, 3, 'Priority must be 1, 2, or 3');
|
|
1199
|
+
priority.validate(99); // invalid — "Priority must be 1, 2, or 3"
|
|
1200
|
+
|
|
1201
|
+
// Number — array form
|
|
1202
|
+
const priority2 = number().oneOf([1, 2, 3], 'Invalid priority');
|
|
1203
|
+
|
|
1204
|
+
// Number — factory function
|
|
1205
|
+
const priority3 = number().oneOf(
|
|
1206
|
+
1, 2, 3,
|
|
1207
|
+
(val) => `${val} is not a valid priority`
|
|
1208
|
+
);
|
|
1209
|
+
```
|
|
1210
|
+
|
|
1211
|
+
> **Note on string `.oneOf()` error messages:** Because `.oneOf()` accepts a variadic list of string values, a trailing string argument is treated as another allowed value (not an error message). To provide a string error message for a string enum, use the **array form** — `string().oneOf(['a', 'b'], 'error message')`. A trailing *function* is always unambiguously treated as an error message factory in the rest-params form.
|
|
1212
|
+
|
|
1213
|
+
All validator extensions accept an optional error message as the last parameter — either a string or a function (matching the same `ValidationErrorMessageProvider` pattern used by built-in constraints like `.minLength()`):
|
|
1214
|
+
|
|
1215
|
+
```typescript
|
|
1216
|
+
import { string, number, array } from '@cleverbrush/schema';
|
|
1217
|
+
|
|
1218
|
+
// String error messages
|
|
1219
|
+
const email = string().email('Please enter a valid email');
|
|
1220
|
+
const age = number().positive('Age must be positive');
|
|
1221
|
+
const tags = array().of(string()).nonempty('At least one tag required');
|
|
1222
|
+
|
|
1223
|
+
// Function error messages — receive the invalid value
|
|
1224
|
+
const name = string().nonempty((val) => `"${val}" is not allowed`);
|
|
1225
|
+
const score = number().multipleOf(5, (val) => `${val} is not a multiple of 5`);
|
|
1226
|
+
```
|
|
1227
|
+
|
|
1228
|
+
### The `/core` Sub-path
|
|
1229
|
+
|
|
1230
|
+
If you need bare builders **without** the built-in extensions (e.g. to apply only your own custom extensions), import from the `/core` sub-path:
|
|
1231
|
+
|
|
1232
|
+
```typescript
|
|
1233
|
+
// Bare builders — no built-in extensions
|
|
1234
|
+
import { string, number, array, withExtensions } from '@cleverbrush/schema/core';
|
|
1235
|
+
|
|
1236
|
+
// Apply only your own extensions
|
|
1237
|
+
const s = withExtensions(myCustomExtension);
|
|
1238
|
+
```
|
|
1239
|
+
|
|
1240
|
+
The default import (`@cleverbrush/schema`) re-exports everything from `/core` and overrides the nine factory functions (`string`, `number`, `boolean`, `date`, `object`, `array`, `union`, `func`, `any`) with pre-extended versions. The extension descriptors themselves are also exported (`stringExtensions`, `numberExtensions`, `arrayExtensions`, `nullableExtension`) so you can compose them with your own.
|
|
1241
|
+
|
|
1242
|
+
## Part of the Cleverbrush Ecosystem
|
|
1243
|
+
|
|
1244
|
+
`@cleverbrush/schema` is the foundation of a three-library ecosystem:
|
|
1245
|
+
|
|
1246
|
+
```
|
|
1247
|
+
@cleverbrush/schema → Define once
|
|
1248
|
+
↓ ↓ ↓
|
|
1249
|
+
Validate data Map between schemas Render React forms
|
|
1250
|
+
↓ ↓ ↓
|
|
1251
|
+
.validate() @cleverbrush/mapper @cleverbrush/react-form
|
|
1252
|
+
```
|
|
1253
|
+
|
|
1254
|
+
Define a schema once and use it for runtime validation, object mapping between different shapes, and type-safe React forms — all from a single source of truth.
|
|
1255
|
+
|
|
1256
|
+
## Exports
|
|
1257
|
+
|
|
1258
|
+
**Builder functions:** `any`, `lazy`, `string`, `number`, `boolean`, `func`, `object`, `date`, `array`, `union`
|
|
1259
|
+
|
|
1260
|
+
**Builder classes** (for extending): `SchemaBuilder`, `AnySchemaBuilder`, `ArraySchemaBuilder`, `BooleanSchemaBuilder`, `DateSchemaBuilder`, `FunctionSchemaBuilder`, `LazySchemaBuilder`, `NumberSchemaBuilder`, `ObjectSchemaBuilder`, `StringSchemaBuilder`, `UnionSchemaBuilder`
|
|
1261
|
+
|
|
1262
|
+
**Extension system:** `defineExtension`, `withExtensions`, `stringExtensions`, `numberExtensions`, `arrayExtensions`, `nullableExtension`
|
|
1263
|
+
|
|
1264
|
+
**Sub-path exports:** `@cleverbrush/schema/core` — bare builders without built-in extensions
|
|
1265
|
+
|
|
1266
|
+
**Types:** `InferType`, `ValidationResult`, `ValidationError`, `MakeOptional`, `SchemaPropertySelector`, `PropertyDescriptor`, `PropertyDescriptorTree`, `ExtensionConfig`, `ExtensionDescriptor`
|
|
1267
|
+
|
|
1268
|
+
See [API documentation](https://docs.cleverbrush.com/) for the full reference.
|
|
1269
|
+
|
|
1270
|
+
## Performance
|
|
1271
|
+
|
|
1272
|
+
Benchmarked against Zod v4 with [Vitest bench](https://vitest.dev/guide/features.html#benchmarking). Run the benchmarks yourself from the repo root: `npm run bench`.
|
|
1273
|
+
|
|
1274
|
+
| Benchmark | @cleverbrush/schema | Zod | Ratio |
|
|
1275
|
+
| --- | --- | --- | --- |
|
|
1276
|
+
| Array 100 objects — valid | 35,228 ops/s | 13,277 ops/s | **2.65× faster** |
|
|
1277
|
+
| Array 100 objects — invalid | 899,329 ops/s | 4,396 ops/s | **204× faster** |
|
|
1278
|
+
| Complex order — valid | 198,988 ops/s | 136,090 ops/s | **1.46× faster** |
|
|
1279
|
+
| Complex order — invalid | 884,706 ops/s | 26,106 ops/s | **33.9× faster** |
|
|
1280
|
+
| Flat object — valid | 1,001,194 ops/s | 840,725 ops/s | **1.19× faster** |
|
|
1281
|
+
| Flat object — invalid | 2,653,630 ops/s | 176,222 ops/s | **15.1× faster** |
|
|
1282
|
+
| Nested object — valid | 690,556 ops/s | 368,893 ops/s | **1.87× faster** |
|
|
1283
|
+
| Nested object — invalid | 2,739,319 ops/s | 87,245 ops/s | **31.4× faster** |
|
|
1284
|
+
| String — valid | 5,348,564 ops/s | 3,533,945 ops/s | **1.51× faster** |
|
|
1285
|
+
| String — invalid | 5,749,087 ops/s | 482,961 ops/s | **11.9× faster** |
|
|
1286
|
+
| Number — valid | 7,911,266 ops/s | 4,806,511 ops/s | **1.65× faster** |
|
|
1287
|
+
| Number — invalid | 5,387,475 ops/s | 637,513 ops/s | **8.45× faster** |
|
|
1288
|
+
| Union first branch | 1,925,508 ops/s | 1,529,547 ops/s | **1.26× faster** |
|
|
1289
|
+
| Union last branch | 676,107 ops/s | 732,682 ops/s | 0.92× |
|
|
1290
|
+
| Union no match — invalid | 5,873,118 ops/s | 385,453 ops/s | **15.2× faster** |
|
|
1291
|
+
|
|
1292
|
+
The large gains on invalid data come from the early-exit optimization: validation stops at the first failing constraint in each field and skips the rest of the object. For APIs and form handlers where invalid submissions are common, this translates directly to measurable throughput improvements.
|
|
1293
|
+
|
|
1294
|
+
## External Schema Interop (`extern()`)
|
|
1295
|
+
|
|
1296
|
+
Already using Zod, Valibot, or ArkType? The `extern()` factory wraps any [Standard Schema v1](https://standardschema.dev/) compatible schema into a `@cleverbrush/schema` builder — so you can mix external schemas with native ones inside an `object()` without rewriting anything.
|
|
137
1297
|
|
|
138
1298
|
```ts
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
1299
|
+
import { z } from 'zod';
|
|
1300
|
+
import { object, number, extern, InferType } from '@cleverbrush/schema';
|
|
1301
|
+
|
|
1302
|
+
// Existing Zod schema — keep as-is
|
|
1303
|
+
const ZodAddress = z.object({
|
|
1304
|
+
street: z.string().min(1),
|
|
1305
|
+
city: z.string(),
|
|
1306
|
+
zip: z.string().length(5),
|
|
1307
|
+
});
|
|
1308
|
+
|
|
1309
|
+
// Compose with @cleverbrush/schema
|
|
1310
|
+
const OrderSchema = object({
|
|
1311
|
+
address: extern(ZodAddress),
|
|
1312
|
+
totalCents: number().min(1),
|
|
1313
|
+
});
|
|
1314
|
+
|
|
1315
|
+
// Type is inferred from *both* libraries:
|
|
1316
|
+
type Order = InferType<typeof OrderSchema>;
|
|
1317
|
+
// { address: { street: string; city: string; zip: string }; totalCents: number }
|
|
1318
|
+
|
|
1319
|
+
const result = OrderSchema.validate({
|
|
1320
|
+
address: { street: '5th Ave', city: 'NYC', zip: '10001' },
|
|
1321
|
+
totalCents: 4999,
|
|
1322
|
+
});
|
|
1323
|
+
|
|
1324
|
+
if (!result.valid) {
|
|
1325
|
+
// Navigate into the extern property — no type annotation needed
|
|
1326
|
+
const zipErrors = result.getErrorsFor(t => t.address.zip);
|
|
1327
|
+
console.log(zipErrors.errors);
|
|
1328
|
+
}
|
|
143
1329
|
```
|
|
144
1330
|
|
|
145
|
-
|
|
1331
|
+
Key points:
|
|
1332
|
+
- **One parameter:** `extern(standardSchema)` — types and property descriptors are derived automatically.
|
|
1333
|
+
- **getErrorsFor()** works through extern boundaries: `t => t.address.city` navigates into the Zod schema.
|
|
1334
|
+
- **Validation** is delegated to the external schema’s `['~standard'].validate()` — @cleverbrush/schema never re-implements the external library’s validation logic.
|
|
1335
|
+
- Works with any library that implements Standard Schema v1 (Zod ≥ 3.24, Valibot ≥ 1.0, ArkType, etc.).
|
|
1336
|
+
|
|
1337
|
+
## Standard Schema Interoperability
|
|
1338
|
+
|
|
1339
|
+
`@cleverbrush/schema` implements [Standard Schema v1](https://standardschema.dev/). Every builder exposes a `['~standard']` getter, which means schemas work as-is with any Standard Schema consumer — no adapters, no wrappers, no configuration:
|
|
146
1340
|
|
|
147
1341
|
```ts
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
1342
|
+
import { object, string, number } from '@cleverbrush/schema';
|
|
1343
|
+
|
|
1344
|
+
const UserSchema = object({
|
|
1345
|
+
name: string().nonempty(),
|
|
1346
|
+
age: number().min(18),
|
|
1347
|
+
});
|
|
1348
|
+
|
|
1349
|
+
// Works with tRPC, TanStack Form, React Hook Form, T3 Env, Hono, Elysia, …
|
|
1350
|
+
const standardSchema = UserSchema['~standard'];
|
|
152
1351
|
```
|
|
1352
|
+
|
|
1353
|
+
Confirmed integrations: **tRPC**, **TanStack Form**, **React Hook Form**, **T3 Env**, **Hono**, **Elysia**, **next-safe-action**, and 50+ others listed on [standardschema.dev](https://standardschema.dev/).
|
|
1354
|
+
|
|
1355
|
+
## Code Quality
|
|
1356
|
+
|
|
1357
|
+
- **Linting:** [Biome](https://biomejs.dev/) — strict rules enforced on every PR via CI
|
|
1358
|
+
- **Type checking:** TypeScript strict mode (`strictNullChecks`, `noImplicitAny`, full coverage)
|
|
1359
|
+
- **Unit tests:** [Vitest](https://vitest.dev/) — runtime tests + type-level tests (`expectTypeOf`) covering all builders, extensions, edge cases, and error paths
|
|
1360
|
+
- **Type-level tests:** `expectTypeOf` assertions validate that inferred types are exactly correct, not just assignable
|
|
1361
|
+
- **CI:** Every pull request must pass lint + build + test before merge — see [`.github/workflows/ci.yml`](../../.github/workflows/ci.yml)
|
|
1362
|
+
|
|
1363
|
+
## License
|
|
1364
|
+
|
|
1365
|
+
BSD-3-Clause
|