validup 0.2.1 → 0.3.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 CHANGED
@@ -1,11 +1,14 @@
1
- # Validup 🛡️
1
+ # validup 🛡️
2
2
 
3
- [![main](https://github.com/tada5hi/validup/actions/workflows/main.yml/badge.svg)](https://github.com/tada5hi/validup/actions/workflows/main.yml)
4
- [![CodeQL](https://github.com/tada5hi/validup/actions/workflows/codeql.yml/badge.svg)](https://github.com/tada5hi/validup/actions/workflows/codeql.yml)
5
- [![Known Vulnerabilities](https://snyk.io/test/github/tada5hi/validup/badge.svg)](https://snyk.io/test/github/tada5hi/validup)
6
- [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-%23FE5196?logo=conventionalcommits&logoColor=white)](https://conventionalcommits.org)
3
+ [![npm version][npm-version-src]][npm-version-href]
4
+ [![Master Workflow][workflow-src]][workflow-href]
5
+ [![CodeQL][codeql-src]][codeql-href]
6
+ [![Known Vulnerabilities][snyk-src]][snyk-href]
7
+ [![Conventional Commits][conventional-src]][conventional-href]
7
8
 
8
- This is a library to create domain specific validators.
9
+ A composable, path-based validation library for TypeScript.
10
+
11
+ Mount any validator function (or nested container) onto any path of your input, run them in groups, collect structured issues, and bridge to existing libraries via integration packages. No decorators, no schema DSL, no metadata reflection.
9
12
 
10
13
  > 🚧 **Work in Progress**
11
14
  >
@@ -13,168 +16,720 @@ This is a library to create domain specific validators.
13
16
 
14
17
  **Table of Contents**
15
18
 
16
- - [Features](#features)
17
19
  - [Installation](#installation)
18
- - [Usage](#usage)
19
- - [Concepts](#concepts)
20
- - [Errors](#errors)
21
- - [Mounting](#mounting)
22
- - [Nesting](#nesting)
23
- - [Groups](#groups)
24
- - [API](#api)
20
+ - [Quick Start](#quick-start)
21
+ - [Key Concepts](#key-concepts)
22
+ - [Validators](#validators)
23
+ - [Containers](#containers)
24
+ - [Issues & Errors](#issues--errors)
25
+ - [Builder API (compile-time typing)](#builder-api-compile-time-typing)
26
+ - [Mounting](#mounting)
27
+ - [Path Patterns](#path-patterns)
28
+ - [Nested Containers](#nested-containers)
29
+ - [Mounting Without a Path](#mounting-without-a-path)
30
+ - [Subclassing](#subclassing)
31
+ - [Groups](#groups)
32
+ - [Optional Values](#optional-values)
33
+ - [oneOf Branches](#oneof-branches)
34
+ - [Path Filtering](#path-filtering)
35
+ - [Defaults](#defaults)
36
+ - [Context](#context)
37
+ - [Cancellation](#cancellation)
38
+ - [Parallel Execution](#parallel-execution)
39
+ - [Safe Run](#safe-run)
40
+ - [Sync Fast Path](#sync-fast-path)
41
+ - [Localized Messages](#localized-messages)
42
+ - [Error Handling](#error-handling)
43
+ - [ValidupError](#validuperror)
44
+ - [Issue Shape](#issue-shape)
45
+ - [Issue Codes](#issue-codes)
46
+ - [API Reference](#api-reference)
47
+ - [Container](#container)
48
+ - [defineSchema](#defineschema)
49
+ - [Issue Helpers](#issue-helpers)
50
+ - [Type Guards](#type-guards)
51
+ - [Integrations](#integrations)
25
52
  - [License](#license)
26
53
 
27
- ## Features
28
-
29
- - ✨ Simple API
30
- - 🌐 Works in any (Node.Js, browser & workers) environment
31
- - ❌ Dedicated errors for different scenarios
32
- - 🚀 Nesting of Validators and Containers
33
- - 🎭 Easy integrate third-party validators/sanitizers (zod, validator.js, ...)
34
-
35
54
  ## Installation
36
55
 
37
56
  ```bash
38
57
  npm install validup --save
39
58
  ```
40
59
 
41
- ## Usage
42
-
43
- A validator is an (async) function to validate (and modify) any piece of information.
44
- Each validator receives a [context](#validatorcontext) containing the actual value, key (aka path), ...
60
+ ## Quick Start
45
61
 
46
62
  ```typescript
47
- import {
48
- Validator,
49
- ValidatorContext,
50
- ValidupValidatorError
51
- } from 'validup';
63
+ import { Container, ValidupError, type Validator } from 'validup';
52
64
 
53
- const isString: Validator = (ctx: ValidatorContext) => {
65
+ const isString: Validator = (ctx) => {
54
66
  if (typeof ctx.value !== 'string') {
55
- throw new ValidupValidatorError({
56
- message: `The validator for ${ctx.path} expected a string as input.`,
57
- expected: 'string',
58
- path: ctx.path
59
- })
67
+ throw new Error('Value is not a string');
60
68
  }
61
-
62
69
  return ctx.value;
70
+ };
71
+
72
+ const container = new Container<{ name: string; email: string }>();
73
+
74
+ container.mount('name', isString);
75
+ container.mount('email', isString);
76
+
77
+ const valid = await container.run({
78
+ name: 'Peter',
79
+ email: 'peter@example.com',
80
+ });
81
+ // valid is { name: 'Peter', email: 'peter@example.com' }
82
+ ```
83
+
84
+ When a validator throws, the container collects the failure into a structured `ValidupError`:
85
+
86
+ ```typescript
87
+ try {
88
+ await container.run({ name: 42, email: 'peter@example.com' });
89
+ } catch (error) {
90
+ if (error instanceof ValidupError) {
91
+ console.log(error.issues);
92
+ // [{ type: 'item', code: 'value_invalid', path: ['name'], message: '...' }]
93
+ }
63
94
  }
64
95
  ```
65
96
 
66
- This validator can than be mounted on a specific path to a container. A mount path can either be
67
- a regular string or a glob pattern.
97
+ ## Key Concepts
98
+
99
+ ### Validators
100
+
101
+ A validator is a (sync or async) function that receives a `ValidatorContext` and either returns the validated/transformed value or throws.
68
102
 
69
103
  ```typescript
70
- import { Container } from 'validup';
104
+ type Validator<C = unknown, Out = unknown> = (ctx: ValidatorContext<C>) => Out | Promise<Out>;
105
+
106
+ type ValidatorContext<C = unknown> = {
107
+ key: string; // expanded mount path within the current container
108
+ path: PropertyKey[]; // global mount path including parent containers
109
+ value: unknown; // the value to validate
110
+ data: Record<string, any>; // input of the current container
111
+ group?: string; // active execution group, if any
112
+ context: C; // caller-supplied context (see [Context](#context))
113
+ signal?: AbortSignal; // cancellation signal (see [Cancellation](#cancellation))
114
+ };
115
+ ```
71
116
 
72
- const container = new Container();
73
- container.mount('foo', isString);
117
+ A validator's **return value** becomes the output for that path — so validators double as transformers/sanitizers. The optional second generic `Out` lets callers (and the [Builder API](#builder-api-compile-time-typing)) infer per-field types from the validator's return type — `Out` defaults to `unknown`, so existing call sites compile unchanged.
74
118
 
75
- const output = await container.run({
76
- foo: 'bar',
77
- bar: 'baz'
78
- });
119
+ ### Containers
120
+
121
+ A `Container<T, C>` holds an ordered list of mounts and runs them against an input object. The optional generic `T` constrains mount keys and shapes the resolved output; the optional `C` types the caller-supplied [context](#context).
122
+
123
+ ```typescript
124
+ const container = new Container<{ name: string; age: number }>();
79
125
 
80
- console.log(output);
81
- // { foo: 'bar' }
126
+ container.mount('name', isString); // ✅ 'name' is a key of T
127
+ container.mount('email', isString); // ⚠️ 'email' is not — allowed via fallback type
82
128
  ```
83
129
 
84
- > [!NOTE]
85
- > The container run method throws an error if an error occurred during the execution of a validator.
130
+ ### Issues & Errors
86
131
 
87
- ## Concepts
132
+ When validation fails, the container throws a `ValidupError` containing a list of `Issue`s. Issues are a discriminated union — each one is either a leaf `IssueItem` or an `IssueGroup` containing children.
88
133
 
89
- ### Errors
134
+ ```typescript
135
+ type Issue = IssueItem | IssueGroup;
136
+ ```
90
137
 
91
- During the execution of a [validator](#validator), a ValidupError can be thrown.
92
- An error can contain multiple issues.
138
+ This recursive structure preserves the path of failure, so consumers can render rich field-level error messages.
93
139
 
94
- When the execution of a Container fails, the container will always throw a ValidupError.
95
- Unknown errors will be converted.
140
+ ## Builder API (compile-time typing)
96
141
 
97
- ### Mounting
142
+ `new Container<T>()` happily accepts mounts that don't cover every required key of `T`, and `run()` returns `T` regardless. The TypeScript shape is a promise the runtime can't keep:
98
143
 
99
- > 🚧 **Work in Progress**
100
- > ...
144
+ ```typescript
145
+ const c = new Container<{ foo: string; bar: number }>();
146
+ c.mount('foo', isString); // ⚠️ bar is never validated
147
+ const out = await c.run({}); // out: { foo, bar } — bar is undefined at runtime
148
+ ```
101
149
 
102
- ### Nesting
150
+ `defineSchema()` is an opt-in, type-accumulating wrapper around `Container` that derives `T` *from the registered mounts* — so `run()`'s static return type reflects exactly what was registered:
103
151
 
104
- > 🚧 **Work in Progress**
105
- >
152
+ ```typescript
153
+ import { defineSchema } from 'validup';
154
+ import { createValidator } from '@validup/zod';
155
+ import { z } from 'zod';
156
+
157
+ const schema = defineSchema()
158
+ .mount('foo', createValidator(z.string())) // { foo: string }
159
+ .mount('age', { optional: true }, createValidator(z.number().int())) // { foo: string; age?: number }
160
+ .mount('address', defineSchema().mount('city', isString)) // { …; address: { city: string } }
161
+ .build();
162
+
163
+ const out = await schema.run(input);
164
+ // out: { foo: string; age?: number; address: { city: string } } — inferred, not declared
165
+ ```
166
+
167
+ The integration packages' `createValidator(...)` functions (`@validup/zod`, `@validup/standard-schema`) infer the per-field `Out` type from the underlying schema, so the builder pulls real types through. Hand-written validators participate too — annotate the return type via `Validator<C, Out>` (or just write the function inline so TypeScript can infer it).
168
+
169
+ The builder mirrors `Container.mount`'s keyed forms — `.mount(key, target)` and `.mount(key, options, target)` — and dispatches on the target type:
170
+
171
+ | Target type | Effect on `T` |
172
+ |------------------------------------|-------------------------------------------------------------------------|
173
+ | `Validator<C, Out>` | adds `{ [K]: Awaited<Out> }` (or `{ [K]?: Awaited<Out> }` when `options.optional`) |
174
+ | `IBuilder<U, C>` | adds `{ [K]: U }` and auto-`.build()`s the child |
175
+ | `IContainer<U, C>` (e.g. `Container<U, C>`) | adds `{ [K]: U }` |
176
+
177
+ Builders are immutable — every method returns a new instance, so chains can fork without leaking state — and `.build()` materializes a `Container<T, C>`:
178
+
179
+ ```typescript
180
+ interface IBuilder<T extends Record<string, any>, C = unknown> {
181
+ mount<K extends string, V extends Validator<C, any> | IBuilder<any, C> | IContainer<any, C>>(
182
+ key: K,
183
+ target: V,
184
+ ): IBuilder<T & Mounted<K, V, undefined>, C>;
185
+
186
+ mount<K extends string, const O extends MountOptions, V extends Validator<C, any> | IBuilder<any, C> | IContainer<any, C>>(
187
+ key: K,
188
+ options: O,
189
+ target: V,
190
+ ): IBuilder<T & Mounted<K, V, O>, C>;
191
+
192
+ oneOf(): IBuilder<T, C>;
193
+ pathsToInclude(...paths: (keyof T & string)[]): IBuilder<T, C>;
194
+ pathsToExclude(...paths: (keyof T & string)[]): IBuilder<T, C>;
195
+ build(): Container<T, C>;
196
+ }
197
+ ```
198
+
199
+ > **Note** — the `?`-widening on `optional: true` only fires when TypeScript sees the value as the literal `true` (or a predicate function). The `const` modifier on the second overload preserves literals from inline option objects, so the common case (`mount('email', { optional: true }, ...)`) just works. A pre-typed `MountOptions` variable whose `optional` is `boolean` will keep the field required.
200
+
201
+ Pass the context type as a generic to flow it through the chain:
202
+
203
+ ```typescript
204
+ type AppContext = { userId: string };
205
+
206
+ const schema = defineSchema<AppContext>()
207
+ .mount('slug', async (ctx) => {
208
+ // ctx.context is typed as AppContext
209
+ await assertSlugAvailable(ctx.value, ctx.context.userId);
210
+ return ctx.value;
211
+ })
212
+ .build();
213
+
214
+ await schema.run(input, { context: { userId: 'u-42' } });
215
+ ```
216
+
217
+ When to reach for which API:
218
+
219
+ | Goal | API |
220
+ |--------------------------------------------------------------------|------------------------------------|
221
+ | Static schema, want compile-time exhaustiveness | `defineSchema()` builder |
222
+ | Dynamic mounts (loops, conditional registration, `initialize()` hook) | `new Container<T>()` |
223
+ | Ship a domain-scoped, reusable validator class | `class extends Container<T>` |
224
+
225
+ The imperative `Container` API is **not** deprecated — it remains the runtime substrate (`.build()` calls `Container.mount(...)`) and the right tool whenever the schema isn't fully known up front.
226
+
227
+ > **Note on `oneOf()`** — only one branch's keys actually appear in the runtime output, but the accumulated type stays as the intersection of every branch (honest about *possible* keys). Wrap the result with your own discriminated union when that fits better.
228
+
229
+ ## Mounting
230
+
231
+ `container.mount(...)` is variadic. Pass any combination of:
232
+
233
+ | Argument | Meaning |
234
+ |------------------|----------------------------------|
235
+ | `string` | path |
236
+ | `function` | `Validator` |
237
+ | `Container` | nested container |
238
+ | plain object | `MountOptions` |
239
+
240
+ ```typescript
241
+ container.mount('foo', validator); // path + validator
242
+ container.mount('foo', { group: 'create' }, validator); // path + options + validator
243
+ container.mount('foo', childContainer); // path + nested container
244
+ container.mount({ optional: true }, childContainer); // options + nested container (no path)
245
+ container.mount(childContainer); // nested container at root
246
+ ```
247
+
248
+ ### Path Patterns
249
+
250
+ Paths are resolved via [pathtrace](https://www.npmjs.com/package/pathtrace) and support dot notation, bracket notation, and glob patterns:
106
251
 
107
- ### Groups
108
- When mounting a validator or container, it is possible to restrict the execution to explicit execution groups.
252
+ ```typescript
253
+ container.mount('foo.bar', validator); // nested key
254
+ container.mount('foo[1]', validator); // array index
255
+ container.mount('foo.**.bar', validator); // any depth
256
+ container.mount('**.id', validator); // every `id` anywhere in the tree
257
+ ```
258
+
259
+ ### Nested Containers
260
+
261
+ A container can mount another container at any path. The child's results are merged into the parent's output.
262
+
263
+ ```typescript
264
+ const address = new Container<{ city: string; country: string }>();
265
+ address.mount('city', isString);
266
+ address.mount('country', isString);
267
+
268
+ const user = new Container<{ name: string; address: { city: string; country: string } }>();
269
+ user.mount('name', isString);
270
+ user.mount('address', address);
271
+
272
+ const valid = await user.run({
273
+ name: 'Peter',
274
+ address: { city: 'Berlin', country: 'DE' },
275
+ });
276
+ ```
277
+
278
+ ### Mounting Without a Path
279
+
280
+ A container (but **not** a validator) can be mounted without a path. Its mounts then operate on the parent's input directly — useful for splitting validation rules across multiple files while keeping a flat output shape.
281
+
282
+ ```typescript
283
+ const credentials = new Container();
284
+ credentials.mount('email', isString);
285
+ credentials.mount('password', isString);
286
+
287
+ const profile = new Container();
288
+ profile.mount('name', isString);
109
289
 
110
- ```ts
290
+ const signup = new Container();
291
+ signup.mount(credentials); // no path — flatten into root
292
+ signup.mount(profile);
293
+ ```
294
+
295
+ ## Subclassing
296
+
297
+ For reusable, self-contained validators it's idiomatic to extend `Container<T>` and register your mounts inside the protected `initialize()` hook. The hook is called by the constructor, so consumers can simply `new RoleValidator()` and run it.
298
+
299
+ ```typescript
111
300
  import { Container } from 'validup';
301
+ import { createValidator } from '@validup/zod';
302
+ import { z } from 'zod';
303
+
304
+ type Role = { name: string; description?: string };
305
+
306
+ class RoleValidator extends Container<Role> {
307
+ protected override initialize() {
308
+ super.initialize();
309
+
310
+ const nameValidator = createValidator(z.string().min(3).max(128));
112
311
 
113
- const container = new Container();
114
- container.mount('id', { group: ['update', 'delete'] }, isString);
115
- container.mount('name', { group: ['craete', 'update', 'delete']}, isString);
116
-
117
- const output = await container.run(
118
- {
119
- id: 'xxx',
120
- name: 'foo'
121
- },
122
- {
123
- group: 'create'
312
+ // Required on create, optional on update — same validator, different groups.
313
+ this.mount('name', { group: 'create' }, nameValidator);
314
+ this.mount('name', { group: 'update', optional: true }, nameValidator);
315
+
316
+ this.mount(
317
+ 'description',
318
+ { optional: true },
319
+ createValidator(z.string().max(4096).nullable()),
320
+ );
124
321
  }
125
- );
322
+ }
126
323
 
127
- console.log(output);
128
- // { name: 'foo' }
324
+ const validator = new RoleValidator();
325
+
326
+ const onCreate = await validator.run(input, { group: 'create' });
327
+ const onUpdate = await validator.run(input, { group: 'update' });
129
328
  ```
130
329
 
131
- In this example the output will only contain the value of the key name.
132
- The reason for this is, that the id key is not registered for the create group.
330
+ This pattern keeps validators close to the entities they validate and makes them easy to share across HTTP layers, queue handlers, and CLI tools.
133
331
 
134
- > [!NOTE]
135
- > To always execute a mounted container/validator do not specify
136
- > any group or use the `*` group.
332
+ ## Groups
137
333
 
334
+ Each mount can opt into one or more **groups**. The `run()` call's `group` option then selects which mounts are executed.
138
335
 
139
- ## API
336
+ ```typescript
337
+ const container = new Container<{ id: string; name: string }>();
140
338
 
141
- ### Validator
142
- ```ts
143
- type Validator = (ctx: ValidatorContext) => Promise<unknown> | unknown;
339
+ container.mount('id', { group: ['update', 'delete'] }, isString);
340
+ container.mount('name', { group: ['create', 'update'] }, isString);
341
+
342
+ await container.run({ id: 'x', name: 'foo' }, { group: 'create' });
343
+ // → { name: 'foo' } — `id` is not in the 'create' group
344
+
345
+ await container.run({ id: 'x', name: 'foo' }, { group: '*' });
346
+ // → { id: 'x', name: 'foo' } — wildcard runs everything
144
347
  ```
145
348
 
146
- ### ValidatorContext
147
- ```ts
148
- type ValidatorContext = {
149
- /**
150
- * The expanded mount path in the current container.
151
- */
152
- key: string,
349
+ The wildcard token `'*'` (also exported as `GroupKey.WILDCARD`) bypasses the filter — either as the active group, or to mark a mount as always-run.
350
+
351
+ ## Optional Values
153
352
 
154
- /**
155
- * The global mount path of the parent container.
156
- */
157
- path: PropertyKey[],
353
+ Mark a mount as `optional` to skip it when the input value is "missing". You decide what counts as missing via `optionalValue`:
354
+
355
+ | `optionalValue` | Treats as optional |
356
+ |---------------------------|-----------------------------------------------|
357
+ | `'undefined'` (default) | only `undefined` |
358
+ | `'null'` | `null` and `undefined` |
359
+ | `'falsy'` | any falsy value (`null`, `undefined`, `''`, `0`, `false`) |
360
+
361
+ ```typescript
362
+ import { OptionalValue } from 'validup';
363
+
364
+ container.mount('age',
365
+ { optional: true, optionalValue: OptionalValue.NULL },
366
+ isNumber,
367
+ );
368
+
369
+ await container.run({ age: null }); // ✅ age is skipped
370
+ await container.run({}); // ✅ age is skipped
371
+ await container.run({ age: 28 }); // ✅ age is validated
372
+ ```
373
+
374
+ Set `optionalInclude: true` to copy the optional value through into the output instead of dropping it:
375
+
376
+ ```typescript
377
+ container.mount('nickname',
378
+ { optional: true, optionalInclude: true },
379
+ isString,
380
+ );
381
+
382
+ await container.run({}); // → { nickname: undefined }
383
+ ```
384
+
385
+ For cases the `optionalValue` enum can't express (e.g. "drop empty string but keep `0`"), pass `optional` as a predicate. Custom predicates win when present and `optionalValue` is ignored:
386
+
387
+ ```typescript
388
+ container.mount('name',
389
+ { optional: (v) => v === '' || typeof v === 'undefined' },
390
+ isString,
391
+ );
392
+
393
+ await container.run({ name: '', count: 0 }); // ✅ name skipped, count validated
394
+ ```
395
+
396
+ ## oneOf Branches
397
+
398
+ A container created with `{ oneOf: true }` succeeds if **any one** of its mounts succeeds. Failures are aggregated into a single `IssueGroup` only when **all** branches fail.
399
+
400
+ ```typescript
401
+ const credential = new Container({ oneOf: true });
402
+
403
+ credential.mount('email', createEmailValidator());
404
+ credential.mount('username', createUsernameValidator());
405
+
406
+ await credential.run({ email: 'peter@example.com' });
407
+ // → { email: 'peter@example.com' } — username branch failure is ignored
408
+
409
+ await credential.run({ email: 'not-an-email', username: 'invalid' });
410
+ // → throws ValidupError with one IssueGroup (code: 'one_of_failed')
411
+ ```
412
+
413
+ ## Path Filtering
414
+
415
+ Limit or exclude paths at runtime:
416
+
417
+ ```typescript
418
+ await container.run(input, { pathsToInclude: ['name', 'email'] }); // only these
419
+ await container.run(input, { pathsToExclude: ['password'] }); // skip these
420
+ ```
158
421
 
159
- /**
160
- * The actual value, which should be validated.
161
- */
162
- value: unknown,
422
+ The same options can be set at the container level via `new Container({ pathsToInclude: [...] })`. Run-time options take precedence.
163
423
 
164
- /**
165
- * The input data of the current container.
166
- */
167
- data: Record<string, any>,
424
+ ## Defaults
168
425
 
169
- /**
170
- * The group name for which the validator is executed.
171
- */
172
- group?: string
426
+ Provide fallback values for keys that end up missing or `undefined` after validation:
427
+
428
+ ```typescript
429
+ await container.run({}, {
430
+ defaults: { role: 'user', active: true },
431
+ });
432
+ // → { role: 'user', active: true }
433
+ ```
434
+
435
+ Dotted keys target nested-container output and are sliced through to the matching child:
436
+
437
+ ```typescript
438
+ await parent.run({}, {
439
+ defaults: { 'profile.role': 'user' },
440
+ });
441
+ // → { profile: { role: 'user' } }
442
+ ```
443
+
444
+ ## Context
445
+
446
+ Pass request-scoped data (current user, locale, DB connection, request id) to your validators without going through closures or globals. The `context` flows through every nested container unchanged.
447
+
448
+ ```typescript
449
+ type AppContext = { userId: string };
450
+
451
+ const container = new Container<{ slug: string }, AppContext>();
452
+
453
+ container.mount('slug', async (ctx) => {
454
+ // ctx.context is typed as AppContext
455
+ const exists = await db.slugExists(ctx.value, ctx.context.userId);
456
+ if (exists) {
457
+ throw new Error('Slug already taken');
458
+ }
459
+ return ctx.value;
460
+ });
461
+
462
+ await container.run({ slug: 'my-post' }, { context: { userId: 'u-42' } });
463
+ ```
464
+
465
+ The `C` parameter on `Container<T, C>`, `Validator<C>`, and `ValidatorContext<C>` defaults to `unknown`, so existing code without a context type compiles unchanged.
466
+
467
+ ## Cancellation
468
+
469
+ Pass an `AbortSignal` to abort a run between mounts. The container checks `signal.aborted` before each mount and rethrows `signal.reason`; the signal is also forwarded into `ValidatorContext.signal` so async validators can cancel their own I/O (e.g. `fetch(url, { signal: ctx.signal })`).
470
+
471
+ ```typescript
472
+ const controller = new AbortController();
473
+ setTimeout(() => controller.abort(), 100);
474
+
475
+ try {
476
+ await container.run(input, { signal: controller.signal });
477
+ } catch (e) {
478
+ // AbortError — not a ValidupError
479
+ }
480
+ ```
481
+
482
+ `safeRun()` rethrows the abort reason (it is never wrapped into a `Result.failure`) so callers can distinguish "validation failed" from "operation cancelled".
483
+
484
+ ## Parallel Execution
485
+
486
+ By default mounts run sequentially in registration order. For containers whose mounts hit independent slow async resources (multiple DB lookups, HTTP calls), opt into parallel mode:
487
+
488
+ ```typescript
489
+ await container.run(input, { parallel: true });
490
+ ```
491
+
492
+ All mounts kick off concurrently and the results merge in registration order — `issues[]` ordering is unchanged. The flag is forwarded into nested containers so the whole tree runs concurrently.
493
+
494
+ **Trade-off**: in parallel mode each mount captures its `value` from the input `data` *before* any sibling mount runs, so a later mount can no longer read an earlier mount's transformed `output[key]`. Stick with sequential mode (the default) for chained-key sanitize-then-validate patterns.
495
+
496
+ ## Safe Run
497
+
498
+ `safeRun()` returns a discriminated `Result<T>` instead of throwing — handy when you want to deal with errors without `try/catch`:
499
+
500
+ ```typescript
501
+ const result = await container.safeRun(input);
502
+
503
+ if (result.success) {
504
+ console.log(result.data); // T
505
+ } else {
506
+ console.error(result.error.issues); // ValidupError
507
+ }
508
+ ```
509
+
510
+ ## Sync Fast Path
511
+
512
+ When every mounted validator (and every nested container's `runSync`) is synchronous, use `runSync()` / `safeRunSync()` to skip the per-mount microtask overhead of `await`:
513
+
514
+ ```typescript
515
+ const out = container.runSync(input); // returns T directly, not Promise<T>
516
+ ```
517
+
518
+ `runSync()` throws synchronously if a validator returns a Promise or if a nested container does not implement `runSync` — those are *structural* failures (not validation outcomes), so they're surfaced verbatim and never wrapped into `Result.failure` by `safeRunSync`. Use the async `run()` for any graph that mixes sync and async validators.
519
+
520
+ ## Localized Messages
521
+
522
+ `Issue.message` is rendered eagerly in English at construction time. For i18n / custom locales, every issue also carries a structured `params?: Record<string, unknown>` field (populated by the runtime where the message references a non-trivial value — e.g. `{ name: 'email' }` on the wrapping group at a failing mount). Pair it with `formatIssue` and a `code → template` map to render at the consumer side:
523
+
524
+ ```typescript
525
+ import { formatIssue, type IssueMessageTemplates } from 'validup';
526
+
527
+ const de: IssueMessageTemplates = {
528
+ value_invalid: 'Feld {name} ist ungültig',
529
+ one_of_failed: 'Keine der Varianten war erfolgreich',
173
530
  };
531
+
532
+ for (const issue of error.issues) {
533
+ console.log(formatIssue(issue, de)); // Feld email ist ungültig
534
+ }
174
535
  ```
175
536
 
537
+ `formatIssue(issue, templates?, fallback?)`:
538
+
539
+ 1. If `templates[issue.code]` exists, returns `interpolate(template, issue.params)` (placeholders use the `{name}` syntax from `@ebec/core`).
540
+ 2. Otherwise returns `issue.message`.
541
+ 3. Otherwise returns `fallback`.
542
+
543
+ Custom validators that want to participate in this flow should pass `params` through `defineIssueItem`/`defineIssueGroup` so consumer-side templates can reference field-specific values. The default `interpolate` is also re-exported for ad-hoc rendering.
544
+
545
+ ## Error Handling
546
+
547
+ ### ValidupError
548
+
549
+ ```typescript
550
+ import type { BaseError } from '@ebec/core';
551
+
552
+ class ValidupError extends BaseError {
553
+ readonly code: string; // 'VALIDUP_ERROR' (auto-derived from class name)
554
+ readonly issues: Issue[];
555
+ cause?: unknown; // inherited from BaseError
556
+ toJSON(): { name, message, code, cause?, issues };
557
+ }
558
+ ```
559
+
560
+ `ValidupError` extends [`@ebec/core`](https://github.com/tada5hi/ebec)'s `BaseError`, so it ships with a `code`, an optional `cause`, and a `toJSON()` for clean transport across HTTP/JSON boundaries. The `message` is auto-built from the failing paths (`Property foo is invalid`, `Properties foo, bar are invalid`).
561
+
562
+ Subclass `ValidupError` (or `BaseError` directly) when you need a domain-specific code — ebec derives it from the class name automatically.
563
+
564
+ Use `isValidupError(err)` to check across package boundaries. It is duck-typed (instanceof OR has a valid `issues` array), so it tolerates the case where two copies of `validup` exist in the dependency tree.
565
+
566
+ ```typescript
567
+ import { isValidupError } from 'validup';
568
+
569
+ if (isValidupError(error)) {
570
+ error.issues.forEach((issue) => console.log(issue.path, issue.message));
571
+ }
572
+ ```
573
+
574
+ ### Issue Shape
575
+
576
+ ```typescript
577
+ interface IssueItem {
578
+ type: 'item';
579
+ code: string; // e.g. IssueCode.VALUE_INVALID
580
+ path: PropertyKey[];
581
+ message: string;
582
+ received?: unknown;
583
+ expected?: unknown;
584
+ meta?: Record<string, unknown>;
585
+ }
586
+
587
+ interface IssueGroup {
588
+ type: 'group';
589
+ code?: string; // e.g. IssueCode.ONE_OF_FAILED
590
+ path: PropertyKey[];
591
+ message: string;
592
+ issues: Issue[]; // recursive
593
+ meta?: Record<string, unknown>;
594
+ }
595
+ ```
596
+
597
+ Use the factories — they set `type` correctly and apply default codes:
598
+
599
+ ```typescript
600
+ import { defineIssueItem, defineIssueGroup, IssueCode } from 'validup';
601
+
602
+ const item = defineIssueItem({
603
+ path: ['email'],
604
+ message: 'Invalid email',
605
+ expected: 'string (email)',
606
+ received: 42,
607
+ });
608
+
609
+ const group = defineIssueGroup({
610
+ path: ['address'],
611
+ message: 'address is invalid',
612
+ issues: [item],
613
+ });
614
+ ```
615
+
616
+ ### Issue Codes
617
+
618
+ | Code | When |
619
+ |-------------------------------|-------------------------------------------------------|
620
+ | `IssueCode.VALUE_INVALID` | Default for any `defineIssueItem(...)` without a code |
621
+ | `IssueCode.ONE_OF_FAILED` | All branches of a `oneOf` container failed |
622
+
623
+ The `IssueCode` const exposes the well-known runtime values; the matching `IssueCode` *type* (declaration-merged with the `IssueCodeRegistry` interface) gives autocomplete on `IssueItem.code`. Third-party packages can register their own codes:
624
+
625
+ ```typescript
626
+ declare module 'validup' {
627
+ interface IssueCodeRegistry {
628
+ EMAIL_TAKEN: 'email_taken';
629
+ }
630
+ }
631
+
632
+ defineIssueItem({ code: 'email_taken', path: ['email'], message: '…' });
633
+ // → autocompletes 'email_taken' alongside the built-ins
634
+ ```
635
+
636
+ Codes that don't need a registry entry still work — `IssueItem.code` is widened to `IssueCode | (string & {})` so ad-hoc strings stay valid.
637
+
638
+ ## API Reference
639
+
640
+ ### Container
641
+
642
+ ```typescript
643
+ class Container<
644
+ T extends Record<string, any> = Record<string, any>,
645
+ C = unknown,
646
+ > implements IContainer<T, C> {
647
+ constructor(options?: ContainerOptions<T>);
648
+
649
+ mount(container: IContainer): void;
650
+ mount(options: MountOptions, container: IContainer): void;
651
+ mount(key: Path<T>, data: IContainer | Validator<C>): void;
652
+ mount(key: Path<T>, options: MountOptions, data: IContainer | Validator<C>): void;
653
+
654
+ run(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Promise<T>;
655
+ safeRun(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Promise<Result<T>>;
656
+
657
+ // Sync variants — throw if any validator returns a Promise.
658
+ runSync(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): T;
659
+ safeRunSync(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Result<T>;
660
+ }
661
+ ```
662
+
663
+ | Option | Where | Description |
664
+ |---------------------------|------------------------|-------------------------------------------------------------------|
665
+ | `oneOf` | `ContainerOptions` | Succeed when any mount succeeds |
666
+ | `pathsToInclude` | `ContainerOptions`, `ContainerRunOptions` | Only mount paths in this list are executed |
667
+ | `pathsToExclude` | `ContainerOptions`, `ContainerRunOptions` | Mount paths in this list are skipped |
668
+ | `defaults` | `ContainerRunOptions` | Fallback values for missing/`undefined` keys |
669
+ | `context` | `ContainerRunOptions` | Caller-supplied value surfaced on `ValidatorContext.context` |
670
+ | `signal` | `ContainerRunOptions` | `AbortSignal` — checked between mounts and forwarded to `ctx.signal` |
671
+ | `parallel` | `ContainerRunOptions` | Run mounts concurrently (forwarded into nested containers) |
672
+ | `group` | `ContainerRunOptions` | Active group (only matching mounts run; `'*'` runs everything) |
673
+ | `flat` | `ContainerRunOptions` | When `true`, the output is a dotted-key map instead of nested |
674
+ | `path` | `ContainerRunOptions` | Used internally when nesting; rarely set by hand |
675
+ | `group` (mount) | `MountOptions` | Group(s) this mount belongs to (`string \| string[]`) |
676
+ | `optional` | `MountOptions` | Skip this mount when value is "optional" |
677
+ | `optionalValue` | `MountOptions` | What counts as optional: `'undefined'` / `'null'` / `'falsy'` |
678
+ | `optionalInclude` | `MountOptions` | Copy optional value into the output instead of dropping it |
679
+
680
+ ### defineSchema
681
+
682
+ ```typescript
683
+ function defineSchema<C = unknown>(): IBuilder<{}, C>;
684
+ ```
685
+
686
+ See [Builder API](#builder-api-compile-time-typing). Each `.mount(...)` call returns a new builder with the accumulated shape; `.build()` materializes a `Container<T, C>`.
687
+
688
+ ### Issue Helpers
689
+
690
+ | Export | Purpose |
691
+ |-----------------------|------------------------------------------------------|
692
+ | `defineIssueItem` | Construct an `IssueItem` (sets `type`, default code) |
693
+ | `defineIssueGroup` | Construct an `IssueGroup` (sets `type`) |
694
+ | `IssueCode` | Built-in issue codes (`VALUE_INVALID`, `ONE_OF_FAILED`) |
695
+ | `GroupKey` | `WILDCARD = '*'` |
696
+ | `OptionalValue` | `UNDEFINED` / `NULL` / `FALSY` |
697
+
698
+ ### Type Guards
699
+
700
+ | Export | Returns |
701
+ |-----------------------|------------------------------------------------------|
702
+ | `isValidupError(e)` | `e is ValidupError` (duck-typed across package copies) |
703
+ | `isError(e)` | `e is Error & {[key: string]: any}` |
704
+ | `isContainer(x)` | `x is IContainer` (duck-typed) |
705
+ | `isIssue(x)` | `x is Issue` |
706
+ | `isIssueItem(x)` | `x is IssueItem` |
707
+ | `isIssueGroup(x)` | `x is IssueGroup` |
708
+
709
+ ## Integrations
710
+
711
+ Use one of the official integration packages to bridge an existing validator library, framework, or UI runtime into validup:
712
+
713
+ | Package | Connects |
714
+ |--------------------------------------------------------------------------------------|--------------------------------------------------------------------------------|
715
+ | [`@validup/standard-schema`](https://npmjs.com/package/@validup/standard-schema) | Any [Standard Schema](https://standardschema.dev) library — zod 3.24+, valibot, arktype, effect-schema, … |
716
+ | [`@validup/zod`](https://npmjs.com/package/@validup/zod) | [zod](https://zod.dev) schemas (vendor-specific issue mapping with `expected` / `received`) |
717
+ | [`@validup/express-validator`](https://npmjs.com/package/@validup/express-validator) | [express-validator](https://express-validator.github.io) chains |
718
+ | [`@validup/vue`](https://npmjs.com/package/@validup/vue) | [Vue 3](https://vuejs.org) composable for reactive client-side form state |
719
+
176
720
  ## License
177
721
 
178
722
  Made with 💚
179
723
 
180
- Published under [MIT License](./LICENSE).
724
+ Published under [Apache 2.0 License](./LICENSE).
725
+
726
+ [npm-version-src]: https://badge.fury.io/js/validup.svg
727
+ [npm-version-href]: https://npmjs.com/package/validup
728
+ [workflow-src]: https://github.com/tada5hi/validup/actions/workflows/main.yml/badge.svg
729
+ [workflow-href]: https://github.com/tada5hi/validup/actions/workflows/main.yml
730
+ [codeql-src]: https://github.com/tada5hi/validup/actions/workflows/codeql.yml/badge.svg
731
+ [codeql-href]: https://github.com/tada5hi/validup/actions/workflows/codeql.yml
732
+ [snyk-src]: https://snyk.io/test/github/tada5hi/validup/badge.svg
733
+ [snyk-href]: https://snyk.io/test/github/tada5hi/validup
734
+ [conventional-src]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-%23FE5196?logo=conventionalcommits&logoColor=white
735
+ [conventional-href]: https://conventionalcommits.org