validup 0.3.0 → 0.4.1

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/dist/index.d.mts CHANGED
@@ -1,20 +1,109 @@
1
- import { Path } from "pathtrace";
2
1
  import { BaseError, interpolate } from "@ebec/core";
2
+ import { Path } from "pathtrace";
3
3
 
4
- //#region src/helpers/defaults.d.ts
4
+ //#region src/cache/types.d.ts
5
5
  /**
6
- * Slice a parent `defaults` map down to entries that target paths inside a
7
- * single nested container mount, with the mount-key prefix stripped so the
8
- * child sees them as local keys. Exact-key matches (the default targets the
9
- * mount root itself) are skipped — the parent's post-loop fill handles those
10
- * once the child has returned, since the child is run with `flat: true` and
11
- * cannot address its own root.
6
+ * The three context fields that determine a cached validator's output.
7
+ * Equality is checked by the run loop with `Object.is` (so primitives
8
+ * compare by value, objects/arrays/functions by reference) — a
9
+ * non-side-effect validator's contract is that these three values
10
+ * fully determine its result, so a fresh object literal in `context`
11
+ * invalidates the cache even when its contents are equivalent.
12
12
  */
13
- declare function resolveDefaults(defaults: Record<string, any> | undefined, key: string): Record<string, any> | undefined;
13
+ type ResultCacheSnapshot = {
14
+ value: unknown;
15
+ context: unknown;
16
+ group: string | undefined;
17
+ };
18
+ /**
19
+ * Raw outcome of a validator invocation, captured before any
20
+ * issue-path post-processing the surrounding run loop performs.
21
+ *
22
+ * The cache stores the validator's *return value* (success) or
23
+ * *thrown error* (failure) — NOT the processed `Issue[]`. On replay,
24
+ * the run loop rebuilds issues via `collectExecutionFailure` using
25
+ * the current `keyParts`, so the same cache entry can be reused
26
+ * correctly across runs where the parent `options.path` differs
27
+ * (e.g. the same container mounted in two different parents).
28
+ */
29
+ type ResultCacheOutcome = {
30
+ ok: true;
31
+ value: unknown;
32
+ } | {
33
+ ok: false;
34
+ error: unknown;
35
+ };
36
+ /**
37
+ * One cache slot for a (mount, expanded-key) pair. Stores the
38
+ * snapshot used to gate reuse and the raw outcome to replay.
39
+ */
40
+ type ResultCacheEntry = {
41
+ snapshot: ResultCacheSnapshot;
42
+ outcome: ResultCacheOutcome;
43
+ };
44
+ /**
45
+ * Storage contract for the per-mount result cache. Treated as opaque
46
+ * key/value storage by the run loop — comparison logic (snapshot
47
+ * equality, side-effect bypass) lives in the container, not the cache.
48
+ *
49
+ * Implementations are free to add LRU eviction, TTLs, persistence,
50
+ * etc. on top of the default Map-backed {@link ResultCache}.
51
+ *
52
+ * Keys are (mount, expanded-key) pairs:
53
+ * - `mount` is the framework-internal Mount reference (treated as an
54
+ * opaque object); use a `WeakMap` keyed on it so cache entries are
55
+ * GC'd alongside the owning container.
56
+ * - `expanded-key` is the dotted path produced by `pathtrace`'s
57
+ * `expandPath` for the current run — wildcard mounts produce
58
+ * multiple expanded keys per registration, each needing its own
59
+ * slot.
60
+ */
61
+ interface IResultCache {
62
+ get(mount: object, key: string): ResultCacheEntry | undefined;
63
+ set(mount: object, key: string, entry: ResultCacheEntry): void;
64
+ /**
65
+ * Remove a single (mount, key) entry. When `key` is omitted, drop
66
+ * every entry for the mount (useful when a mount is being
67
+ * structurally invalidated).
68
+ */
69
+ delete(mount: object, key?: string): void;
70
+ clear(): void;
71
+ }
14
72
  //#endregion
15
- //#region src/helpers/error.d.ts
16
- declare function buildErrorMessageForAttribute(key: PropertyKey): string;
17
- declare function buildErrorMessageForAttributes(input: PropertyKey[] | Record<string, any>): string;
73
+ //#region src/cache/check.d.ts
74
+ /**
75
+ * Duck-typed guard for {@link IResultCache}. Avoids `instanceof`
76
+ * checks so caches constructed from a different copy of the package
77
+ * (workspaces with duplicated `validup` installs, adapter bundles)
78
+ * still round-trip cleanly.
79
+ */
80
+ declare function isResultCache(input: unknown): input is IResultCache;
81
+ //#endregion
82
+ //#region src/cache/module.d.ts
83
+ /**
84
+ * Default in-memory {@link IResultCache} implementation.
85
+ *
86
+ * Backed by a two-level `Map`:
87
+ * - outer key — Mount reference (opaque object)
88
+ * - inner key — expanded path (string)
89
+ *
90
+ * `Map` is used for both levels (rather than a `WeakMap` on the outer)
91
+ * so `clear()` is supported. Cache entries become unreachable when the
92
+ * owning composable / caller drops its reference to the
93
+ * `ResultCache` instance; in the typical `@validup/vue` flow that
94
+ * happens on `onScopeDispose`, which lines up with component unmount.
95
+ *
96
+ * Snapshot equality (the "is this still valid?" check) is the run
97
+ * loop's job — see `container/module.ts`. This class is dumb storage.
98
+ */
99
+ declare class ResultCache implements IResultCache {
100
+ private store;
101
+ constructor();
102
+ get(mount: object, key: string): ResultCacheEntry | undefined;
103
+ set(mount: object, key: string, entry: ResultCacheEntry): void;
104
+ delete(mount: object, key?: string): void;
105
+ clear(): void;
106
+ }
18
107
  //#endregion
19
108
  //#region src/constants.d.ts
20
109
  declare enum GroupKey {
@@ -22,88 +111,229 @@ declare enum GroupKey {
22
111
  }
23
112
  declare enum OptionalValue {
24
113
  /**
25
- * value: undefined
114
+ * Treats only `undefined` as optional. Default.
26
115
  */
27
116
  UNDEFINED = "undefined",
28
117
  /**
29
- * value: null & undefined
118
+ * Treats `null` and `undefined` as optional.
30
119
  */
31
120
  NULL = "null",
32
121
  /**
33
- * value: empty string, false, 0
122
+ * Treats any JS falsy value as optional — `undefined`, `null`, `false`,
123
+ * `0`, `''`, `NaN`.
124
+ *
125
+ * **Warning**: this includes `0` and `''`. For quantity / numeric fields
126
+ * where `0` is a meaningful value, prefer the predicate form
127
+ * `optional: (value) => boolean` so you keep control over what counts as
128
+ * missing (e.g. `optional: (v) => v === '' || v === undefined` drops the
129
+ * empty string but keeps `0`).
34
130
  */
35
131
  FALSY = "falsy"
36
132
  }
37
133
  //#endregion
38
- //#region src/helpers/optional-value.d.ts
134
+ //#region src/issue/constants.d.ts
39
135
  /**
40
- * Check if input value (type of) satisfies optional value type constraint.
136
+ * Vocabulary of well-known issue codes. Adapter packages map foreign
137
+ * validator codes onto these so consumer-side translation catalogs
138
+ * (e.g. `@ilingo/validup`) can ship one localized message per code
139
+ * instead of falling back to a generic "invalid value" fallback.
41
140
  *
42
- * @param value
43
- * @param optionalValue
44
- */
45
- declare function isOptionalValue(value: unknown, optionalValue?: `${OptionalValue}`): boolean;
46
- //#endregion
47
- //#region src/helpers/path-filter.d.ts
48
- type PathFilterResolution = {
49
- skip: boolean;
50
- pathsToInclude: string[] | undefined;
51
- pathsToExclude: string[] | undefined;
52
- };
53
- /**
54
- * Resolve `pathsToInclude` / `pathsToExclude` against a single mounted item's
55
- * (already-expanded) local `key`. Returns whether to skip the item, plus the
56
- * filter sub-lists to forward into a child container — with the parent prefix
57
- * stripped so the child can match purely against its own local keys.
141
+ * Tracks the common ground between vuelidate, zod, joi, and yup. The
142
+ * core lifts from vuelidate's catalog (snake_cased to match validup's
143
+ * convention); modern format codes (`PATTERN`, `UUID`, `DATE`,
144
+ * `JSON`, `BASE64`, `STRONG_PASSWORD`, …) cover ground vuelidate
145
+ * predates. Every format code names the format positively (`UUID`,
146
+ * `EMAIL`, `URL`, …) rather than the failure mode (`NOT_UUID`,
147
+ * `INVALID_EMAIL`) so the registry reads consistently.
58
148
  *
59
- * Semantics:
60
- * - Un-keyed container mount (`key === ''`) shares the parent's namespace, so
61
- * filters are forwarded verbatim.
62
- * - Exact match in `pathsToInclude` / `pathsToExclude` matches the whole mount.
63
- * - Prefix match (`<key>.…`) only descends into container mounts; leaf
64
- * validators with deeper-target filters fall through (skipped for include,
65
- * kept for exclude).
66
- */
67
- declare function resolvePathFilter(pathsToInclude: string[] | undefined, pathsToExclude: string[] | undefined, key: string, isContainer: boolean): PathFilterResolution;
68
- //#endregion
69
- //#region src/helpers/path-stringify.d.ts
70
- /**
71
- * Stringify path array to string.
149
+ * Ad-hoc / project-specific codes still work — `IssueItem.code` is
150
+ * widened to `IssueCode | (string & {})`, so `defineIssueItem({ code:
151
+ * 'email_taken', ... })` is valid. If you want a typed const for your
152
+ * own codes, define one alongside this one:
72
153
  *
73
- * @param input
154
+ * ```ts
155
+ * import { IssueCode } from 'validup';
156
+ *
157
+ * export const AppCode = {
158
+ * ...IssueCode,
159
+ * EMAIL_TAKEN: 'email_taken',
160
+ * } as const;
161
+ * ```
162
+ *
163
+ * Each entry's JSDoc documents the structured `data` adapters should
164
+ * attach when constructing the issue — templates can rely on those
165
+ * placeholders being present (`{{min}}`, `{{max}}`, `{{other}}`, etc.).
74
166
  */
75
- declare function stringifyPath(input: PropertyKey[]): string;
76
- //#endregion
77
- //#region src/issue/constants.d.ts
167
+ declare const IssueCode: {
168
+ /** Generic fallback when no more-specific code applies. `data`: — */readonly VALUE_INVALID: "value_invalid"; /** Every branch of a `oneOf` container failed. `data`: — */
169
+ readonly ONE_OF_FAILED: "one_of_failed"; /** Value is missing, `undefined`, `null`, or empty per the validator's semantics. `data`: — */
170
+ readonly REQUIRED: "required"; /** Value contains characters outside the alphabetical set. `data`: — */
171
+ readonly ALPHA: "alpha"; /** Value contains characters outside the alphanumeric set. `data`: — */
172
+ readonly ALPHA_NUM: "alpha_num"; /** Value is not a number. `data`: — */
173
+ readonly NUMERIC: "numeric"; /** Value is not an integer. `data`: — */
174
+ readonly INTEGER: "integer"; /** Value is not a decimal number. `data`: — */
175
+ readonly DECIMAL: "decimal"; /** Value is shorter than the configured minimum. `data`: `{ min: number }` */
176
+ readonly MIN_LENGTH: "min_length"; /** Value is longer than the configured maximum. `data`: `{ max: number }` */
177
+ readonly MAX_LENGTH: "max_length"; /** Numeric value is below the configured minimum. `data`: `{ min: number }` */
178
+ readonly MIN_VALUE: "min_value"; /** Numeric value is above the configured maximum. `data`: `{ max: number }` */
179
+ readonly MAX_VALUE: "max_value"; /** Numeric value falls outside the configured `[min, max]` range. `data`: `{ min: number, max: number }` */
180
+ readonly BETWEEN: "between"; /** Value is not a valid email address. `data`: — */
181
+ readonly EMAIL: "email"; /** Value is not a valid URL. `data`: — */
182
+ readonly URL: "url"; /** Value is not a valid IP address. `data`: — */
183
+ readonly IP_ADDRESS: "ip_address"; /** Value is not a valid MAC address. `data`: — */
184
+ readonly MAC_ADDRESS: "mac_address"; /** Value is not a valid UUID. `data`: — */
185
+ readonly UUID: "uuid"; /** Value is not a valid date / cannot be parsed as a date. `data`: — */
186
+ readonly DATE: "date";
187
+ /**
188
+ * Value does not match the expected regex pattern. `data`:
189
+ * `{ pattern: string }` — source of the regex without flags so
190
+ * catalogs can quote it in human-readable form.
191
+ */
192
+ readonly PATTERN: "pattern"; /** Value is not valid JSON. `data`: — */
193
+ readonly JSON: "json"; /** Value is not valid base64. `data`: — */
194
+ readonly BASE64: "base64";
195
+ /**
196
+ * Value does not meet the configured strong-password rules. `data`:
197
+ * `{ minLength?: number, minLowercase?: number, minUppercase?: number,
198
+ * minNumbers?: number, minSymbols?: number }` — only the keys the
199
+ * adapter chose to surface; missing keys mean "the default for that
200
+ * setting wasn't configured."
201
+ */
202
+ readonly STRONG_PASSWORD: "strong_password";
203
+ /**
204
+ * Value must equal another named field's value (sibling-field assertion,
205
+ * e.g. password-confirm). `data`: `{ other: string }` — the name of
206
+ * the field being compared against.
207
+ */
208
+ readonly SAME_AS: "same_as";
209
+ };
210
+ type IssueCode = typeof IssueCode[keyof typeof IssueCode];
78
211
  /**
79
- * Registry of well-known issue codes. Third-party packages can extend the
80
- * union via TypeScript declaration merging:
212
+ * Per-code `data` contract for the well-known vocabulary. Producers
213
+ * (`defineIssueItem`, `createValidupError`, adapter `error.ts` modules)
214
+ * thread this through their type signatures so TS rejects mismatched
215
+ * payloads at compile time — e.g. `STRONG_PASSWORD` with `data:
216
+ * { pointsPerUnique: 5 }` (a validator.js scoring weight, not a strength
217
+ * requirement) fails to type-check. Codes absent from this map carry no
218
+ * `data`; ad-hoc string codes fall back to the open
219
+ * `Record<string, unknown>` shape on the raw `IssueItem` branch.
220
+ *
221
+ * Extensible via TypeScript declaration merging — third-party adapters
222
+ * and apps that want typed data for their own codes can augment this
223
+ * interface, and the producer-side gatekeep (`defineIssueItem`,
224
+ * `createValidupError`) will type-check their payloads too:
81
225
  *
82
226
  * ```ts
227
+ * // In a third-party package or app:
83
228
  * declare module 'validup' {
84
- * interface IssueCodeRegistry {
85
- * email_taken: 'email_taken';
229
+ * interface IssueDataByCode {
230
+ * email_taken: { existingUserId: string };
86
231
  * }
87
232
  * }
233
+ *
234
+ * defineIssueItem({
235
+ * code: 'email_taken',
236
+ * path: ['email'],
237
+ * message: 'Already in use',
238
+ * data: { existingUserId: 'u_42' }, // typed and required
239
+ * });
88
240
  * ```
89
241
  *
90
- * After augmentation, `IssueCode` widens to include the new literal so
91
- * `defineIssueItem({ code: 'email_taken', ... })` is type-checked.
242
+ * Keep entries here in lockstep with the JSDoc on the corresponding
243
+ * `IssueCode` entry — the type-level enforcement and the documentation
244
+ * are two views of the same contract.
92
245
  */
93
- interface IssueCodeRegistry {
94
- VALUE_INVALID: 'value_invalid';
95
- ONE_OF_FAILED: 'one_of_failed';
246
+ interface IssueDataByCode {
247
+ min_length: {
248
+ min: number;
249
+ };
250
+ max_length: {
251
+ max: number;
252
+ };
253
+ min_value: {
254
+ min: number;
255
+ };
256
+ max_value: {
257
+ max: number;
258
+ };
259
+ between: {
260
+ min: number;
261
+ max: number;
262
+ };
263
+ pattern: {
264
+ pattern: string;
265
+ };
266
+ strong_password: {
267
+ minLength?: number;
268
+ minLowercase?: number;
269
+ minUppercase?: number;
270
+ minNumbers?: number;
271
+ minSymbols?: number;
272
+ };
273
+ same_as: {
274
+ other: string;
275
+ };
96
276
  }
97
- type IssueCode = IssueCodeRegistry[keyof IssueCodeRegistry];
98
- declare const IssueCode: {
99
- readonly VALUE_INVALID: "value_invalid";
100
- readonly ONE_OF_FAILED: "one_of_failed";
101
- };
277
+ /**
278
+ * `IssueCode` values that carry a documented `data` payload — keys of
279
+ * {@link IssueDataByCode}. Producers using one of these codes must
280
+ * supply the matching `data` shape.
281
+ */
282
+ type ParameterizedIssueCode = keyof IssueDataByCode;
283
+ /**
284
+ * `IssueCode` values that carry no `data` (`VALUE_INVALID`, `EMAIL`,
285
+ * `REQUIRED`, …). Producers using one of these codes must omit `data`
286
+ * (or pass `undefined`).
287
+ */
288
+ type BareIssueCode = Exclude<IssueCode, ParameterizedIssueCode>;
102
289
  //#endregion
103
290
  //#region src/issue/types.d.ts
291
+ /**
292
+ * Resolve a possibly-`undefined` `code` to its effective vocabulary entry.
293
+ * When a producer (`defineIssueItem`, `createValidupError`) is called
294
+ * without a `code`, the runtime defaults to `IssueCode.VALUE_INVALID`;
295
+ * this helper reflects that at the type level so the conditional-type
296
+ * signatures pick the bare-data branch instead of the raw catch-all.
297
+ *
298
+ * `[C] extends [undefined]` is the standard idiom for testing the whole
299
+ * `C` against `undefined` *without* distributing over union members.
300
+ */
301
+ type ResolveIssueCode<C> = [C] extends [undefined] ? typeof IssueCode.VALUE_INVALID : C & string;
104
302
  interface IssueBase {
105
303
  /**
106
- * Context in which the issue occurred.
304
+ * Out-of-band provenance about how this issue came to exist — context the
305
+ * consumer cannot reconstruct from `path` + the container's mount config.
306
+ *
307
+ * Library-owned keys (stable, semver-protected):
308
+ *
309
+ * - `optional?: true` — set by the runtime when the originating mount's
310
+ * `optional` declaration resolves truthy for the current value:
311
+ *
312
+ * - `optional: true` → tagged
313
+ * - `optional: false` → not tagged (matches the runtime's truthy filter)
314
+ * - `optional: (v) => boolean` → predicate is invoked with the current
315
+ * value; tagged iff it returns truthy. In practice the run loop only
316
+ * enters the error path when the predicate has already returned
317
+ * false (otherwise the validator would have been skipped), so
318
+ * predicate-optional issues effectively never carry the flag today.
319
+ * - `optional: undefined` → not tagged
320
+ *
321
+ * Reflects only the most-local mount, never inherited from a parent:
322
+ * a leaf inside an optional child container does NOT carry the flag
323
+ * unless its own mount also evaluated truthy. Set on direct leaf
324
+ * emissions and on the wrapping `IssueGroup` produced for the mount
325
+ * itself; never set on issues that bubbled up unchanged through
326
+ * `prefixIssuePath`.
327
+ * - `external?: true` — set by frameworks that inject server-side issues
328
+ * (e.g. `@validup/vue`'s `setExternalIssues`). Distinguishes
329
+ * server-supplied from validator-supplied so consumers can render the
330
+ * distinction.
331
+ *
332
+ * Apps and third-party validators may add their own keys (e.g.
333
+ * `app.componentId`) — the open-shape `Record<string, unknown>` is
334
+ * intentional. New library-owned keys must pass the bar above:
335
+ * provenance, not derivable from path + container config. Presentation
336
+ * tokens (e.g. `severity`) do not qualify and live in consumer code.
107
337
  */
108
338
  meta?: Record<string, unknown>;
109
339
  /**
@@ -117,19 +347,19 @@ interface IssueBase {
117
347
  message: string;
118
348
  /**
119
349
  * Structured parameters used by the default `message` rendering and
120
- * available to consumer-side formatters (i18n, custom locales). For
121
- * built-in issues created by the runtime, `params` is populated where
122
- * the message references a non-trivial value (e.g. attribute name).
350
+ * available to consumer-side formatters (i18n, custom locales). The
351
+ * concrete shape depends on the discriminating `code` — see the
352
+ * `IssueItem` union below for the per-code contract.
123
353
  */
124
- params?: Record<string, unknown>;
354
+ data?: Record<string, unknown>;
125
355
  }
126
- interface IssueItem extends IssueBase {
127
- /**
128
- * Code identifying the issue. Known codes come from `IssueCodeRegistry`
129
- * (extensible via declaration merging); the `string` widening leaves the
130
- * door open for ad-hoc codes that don't need a registry entry.
131
- */
132
- code: IssueCode | (string & {});
356
+ /**
357
+ * Shared shape for every `IssueItem` branch — the discriminant (`type:
358
+ * 'item'`) plus the vendor-passthrough fields. The `code` and `data`
359
+ * fields are intentionally absent here; each branch in the discriminated
360
+ * union below pins them to the right pair.
361
+ */
362
+ interface IssueItemCommon extends IssueBase {
133
363
  /**
134
364
  * Issue Type
135
365
  */
@@ -143,10 +373,67 @@ interface IssueItem extends IssueBase {
143
373
  */
144
374
  expected?: unknown;
145
375
  }
376
+ /**
377
+ * Typed-data branch — one variant per `ParameterizedIssueCode`. The
378
+ * `data` shape is locked to the documented contract via
379
+ * {@link IssueDataByCode}.
380
+ *
381
+ * Distributed (rather than written as a single `code: ParameterizedIssueCode`
382
+ * member) so that `Extract<IssueItem, { code: 'min_length' }>` and structural
383
+ * narrowing on `issue.code === IssueCode.MIN_LENGTH` resolve to the right
384
+ * concrete variant with `data: { min: number }`, not the joined union.
385
+ */
386
+ type IssueItemTyped = { [K in ParameterizedIssueCode]: IssueItemCommon & {
387
+ code: K;
388
+ data: IssueDataByCode[K];
389
+ } }[ParameterizedIssueCode];
390
+ /**
391
+ * Bare-data branch — one variant per `BareIssueCode`. `data` must be
392
+ * absent (or explicitly `undefined`).
393
+ *
394
+ * Distributed for the same reason as {@link IssueItemTyped} — so
395
+ * `Extract<IssueItem, { code: 'email' }>` resolves to the single
396
+ * `code: 'email'` variant.
397
+ */
398
+ type IssueItemBare = { [K in BareIssueCode]: IssueItemCommon & {
399
+ code: K;
400
+ data?: undefined;
401
+ } }[BareIssueCode];
402
+ /**
403
+ * Escape-hatch branch — ad-hoc / project-specific codes outside the
404
+ * shipped vocabulary. `code: string & {}` keeps autocomplete on the
405
+ * `IssueCode` literals while permitting strings the typed branches don't
406
+ * cover; `data` is fully open.
407
+ *
408
+ * Note: because `string & {}` accepts any string at the type level,
409
+ * narrowing on `issue.code === IssueCode.MIN_LENGTH` still pulls this
410
+ * branch in alongside the matching `IssueItemTyped` variant. The
411
+ * producer-side `defineIssueItem` / `createValidupError` signatures
412
+ * gatekeep this so emission is always correct; consumers needing a
413
+ * clean narrow should cast `issue.data` after the code check.
414
+ */
415
+ interface IssueItemRaw extends IssueItemCommon {
416
+ code: string & {};
417
+ data?: Record<string, unknown>;
418
+ }
419
+ /**
420
+ * Discriminated union over `IssueItem`'s three branches:
421
+ *
422
+ * - {@link IssueItemTyped} — known parameterized codes (`MIN_LENGTH`,
423
+ * `PATTERN`, `STRONG_PASSWORD`, …); `data` is required and typed.
424
+ * - {@link IssueItemBare} — known param-less codes (`EMAIL`, `REQUIRED`,
425
+ * …); `data` must be absent.
426
+ * - {@link IssueItemRaw} — ad-hoc string codes; `data` is open.
427
+ *
428
+ * The discriminant is `code`. Build issues with `defineIssueItem` (typed
429
+ * overloads enforce the per-branch contract) rather than constructing
430
+ * literals by hand.
431
+ */
432
+ type IssueItem = IssueItemTyped | IssueItemBare | IssueItemRaw;
146
433
  interface IssueGroup extends IssueBase {
147
434
  /**
148
- * Code identifying the issue. See `IssueItem.code` for the registry
149
- * extension mechanism.
435
+ * Code identifying the issue. See `IssueItem.code` for the
436
+ * vocabulary + ad-hoc widening conventions.
150
437
  */
151
438
  code?: IssueCode | (string & {});
152
439
  /**
@@ -166,8 +453,47 @@ declare function isIssueGroup(input: unknown): input is IssueGroup;
166
453
  declare function isIssue(input: unknown): input is Issue;
167
454
  //#endregion
168
455
  //#region src/issue/define.d.ts
169
- type PartialProps<T extends Record<PropertyKey, any>, K extends keyof T> = Pick<T, Exclude<keyof T, K>> & Partial<Pick<T, K>>;
170
- declare function defineIssueItem(data: Omit<PartialProps<IssueItem, 'code'>, 'type'>): IssueItem;
456
+ interface DefineIssueItemCommon extends Omit<IssueBase, 'data'> {
457
+ received?: unknown;
458
+ expected?: unknown;
459
+ }
460
+ /**
461
+ * Per-call `data` shape for {@link defineIssueItem}. The `data`
462
+ * requirement is selected from the resolved `code`:
463
+ *
464
+ * - Parameterized code → `data` required, typed per {@link IssueDataByCode}.
465
+ * - Bare code (incl. omitted, which resolves to `VALUE_INVALID`)
466
+ * → `data` must be absent / `undefined`.
467
+ * - Ad-hoc string code → `data` optional `Record`.
468
+ */
469
+ type DefineIssueItemData<C> = DefineIssueItemCommon & {
470
+ code?: C;
471
+ } & (ResolveIssueCode<C> extends ParameterizedIssueCode ? {
472
+ data: IssueDataByCode[ResolveIssueCode<C> & ParameterizedIssueCode];
473
+ } : ResolveIssueCode<C> extends BareIssueCode ? {
474
+ data?: undefined;
475
+ } : {
476
+ data?: Record<string, unknown>;
477
+ });
478
+ /**
479
+ * Return type for {@link defineIssueItem} — picks the concrete `IssueItem`
480
+ * variant matching the resolved `code`.
481
+ */
482
+ type DefineIssueItemReturn<C> = ResolveIssueCode<C> extends ParameterizedIssueCode ? Extract<IssueItemTyped, {
483
+ code: ResolveIssueCode<C>;
484
+ }> : ResolveIssueCode<C> extends BareIssueCode ? Extract<IssueItemBare, {
485
+ code: ResolveIssueCode<C>;
486
+ }> : IssueItemRaw;
487
+ /**
488
+ * Build an `IssueItem`. TS uses the supplied `code` to pick the right
489
+ * `data` requirement at the call site — passing `MIN_LENGTH` without
490
+ * `data: { min }` is a compile error; passing `STRONG_PASSWORD` with
491
+ * `data: { pointsPerUnique: 5 }` is a compile error.
492
+ *
493
+ * `code` may be omitted (defaults to `IssueCode.VALUE_INVALID` — bare,
494
+ * no data).
495
+ */
496
+ declare function defineIssueItem<C extends string | undefined = undefined>(data: DefineIssueItemData<C>): DefineIssueItemReturn<C>;
171
497
  declare function defineIssueGroup(data: Omit<IssueGroup, 'type'>): IssueGroup;
172
498
  //#endregion
173
499
  //#region src/issue/flatten.d.ts
@@ -178,7 +504,7 @@ declare function flattenIssueGroups(issues: Issue[]): IssueGroup[];
178
504
  /**
179
505
  * Map of issue `code` → message template. Templates use `{name}` placeholders
180
506
  * — the same syntax `@ebec/core`'s `interpolate` understands — and are
181
- * resolved against `Issue.params` at format time.
507
+ * resolved against `Issue.data` at format time.
182
508
  *
183
509
  * ```ts
184
510
  * const de: IssueMessageTemplates = {
@@ -192,7 +518,7 @@ type IssueMessageTemplates = Partial<Record<IssueCode, string>> & Record<string,
192
518
  * Render an issue's user-facing message.
193
519
  *
194
520
  * Resolution order:
195
- * 1. If `templates[code]` exists, return `interpolate(template, issue.params)`.
521
+ * 1. If `templates[code]` exists, return `interpolate(template, issue.data)`.
196
522
  * 2. Else return `issue.message` (the default English rendering set at
197
523
  * construction time).
198
524
  * 3. Else return `fallback`.
@@ -216,6 +542,8 @@ declare function isValidupError(error: unknown): error is ValidupError;
216
542
  //#endregion
217
543
  //#region src/types.d.ts
218
544
  type ObjectLiteral = Record<string | number, any>;
545
+ //#endregion
546
+ //#region src/validator/types.d.ts
219
547
  type ValidatorContext<C = unknown> = {
220
548
  /**
221
549
  * The expanded mount path in the current container.
@@ -250,6 +578,20 @@ type ValidatorContext<C = unknown> = {
250
578
  * `signal.aborted` between mounts and rethrows the signal's `reason`.
251
579
  */
252
580
  signal?: AbortSignal;
581
+ /**
582
+ * Result cache forwarded from `ContainerRunOptions.cache`. Surfaced so
583
+ * orchestrating validators (notably `compose` with an `IContainer`
584
+ * element) can pass the same cache instance into nested
585
+ * `IContainer.run()` calls — without this thread-through, a
586
+ * container-as-branch would silently bypass the cache and force every
587
+ * mount inside it to re-run on every invocation.
588
+ *
589
+ * Bare validators almost never need to consult this — the Container
590
+ * run loop already handles per-mount cache reads/writes around the
591
+ * validator call. The field is on the public context for
592
+ * composability, not for typical validator authoring.
593
+ */
594
+ cache?: IResultCache;
253
595
  };
254
596
  /**
255
597
  * A `Validator` either returns the (optionally transformed) value or throws.
@@ -262,6 +604,74 @@ type ValidatorContext<C = unknown> = {
262
604
  * second generic to accumulate per-field types.
263
605
  */
264
606
  type Validator<C = unknown, Out = unknown> = (ctx: ValidatorContext<C>) => Out | Promise<Out>;
607
+ /**
608
+ * Authored descriptor for a validator — wraps the run function with metadata
609
+ * the framework can act on (currently: `sideEffect`).
610
+ *
611
+ * Use the {@link defineValidator} factory rather than constructing the object
612
+ * literally, so the descriptor shape stays consistent if more fields are
613
+ * added later.
614
+ *
615
+ * Mounted via the same `mount(...)` signatures that accept a bare `Validator`
616
+ * — the container normalises a bare function into `{ run: fn }` internally.
617
+ * Side-effect-free descriptors participate in the per-mount result cache
618
+ * (see `ContainerRunOptions.cache`); side-effecting ones never do.
619
+ */
620
+ type ValidatorDescriptor<C = unknown, Out = unknown> = {
621
+ /**
622
+ * `true` declares that the validator's output is NOT a pure function of
623
+ * `(ctx.value, ctx.context, ctx.group)` — it may read sibling fields
624
+ * from `ctx.data`, hit the network, observe global state, etc. The
625
+ * framework will never cache its result; the validator runs on every
626
+ * invocation, including per-keystroke runs.
627
+ *
628
+ * `false` (or omitted — the default) declares that the validator's
629
+ * output is fully determined by `(value, context, group)`. When the
630
+ * caller supplies a `ContainerRunOptions.cache`, the framework will
631
+ * reuse the prior result whenever those three inputs match by identity
632
+ * (Object.is for primitives, reference equality for objects).
633
+ *
634
+ * Default = cached. Mark cross-field / async / stateful validators
635
+ * explicitly with `sideEffect: true`.
636
+ */
637
+ sideEffect?: boolean;
638
+ /**
639
+ * The validator function. Same shape as a bare-function mount.
640
+ */
641
+ run: Validator<C, Out>;
642
+ };
643
+ //#endregion
644
+ //#region src/validator/check.d.ts
645
+ /**
646
+ * Duck-typed guard for {@link ValidatorDescriptor}. Used by `mount()` to
647
+ * distinguish a descriptor from a bare `Validator` function and from a
648
+ * nested `IContainer` (which is also an object but carries `run` /
649
+ * `safeRun` methods — the descriptor has a `run` function but no
650
+ * `safeRun`).
651
+ *
652
+ * Duck-typed (not `instanceof`) so descriptors built from a different
653
+ * copy of the package — adapters bundling their own `validup` dependency,
654
+ * pnpm workspaces with multiple installs — still round-trip cleanly.
655
+ */
656
+ declare function isValidatorDescriptor<C = unknown, Out = unknown>(input: unknown): input is ValidatorDescriptor<C, Out>;
657
+ //#endregion
658
+ //#region src/validator/define.d.ts
659
+ /**
660
+ * Factory for a {@link ValidatorDescriptor}. Mirrors the
661
+ * `defineIssueItem` / `defineIssueGroup` shape used elsewhere in the
662
+ * library so authored validators get a stable, typed construction site.
663
+ *
664
+ * @example
665
+ * const validateEmailUnique = defineValidator({
666
+ * sideEffect: true,
667
+ * run: async (ctx) => {
668
+ * const taken = await api.isEmailTaken(ctx.value as string);
669
+ * if (taken) throw new Error('Email is already taken');
670
+ * return ctx.value;
671
+ * },
672
+ * });
673
+ */
674
+ declare function defineValidator<C = unknown, Out = unknown>(descriptor: ValidatorDescriptor<C, Out>): ValidatorDescriptor<C, Out>;
265
675
  //#endregion
266
676
  //#region src/container/types.d.ts
267
677
  type ContainerOptions<T> = {
@@ -284,9 +694,11 @@ type ContainerOptions<T> = {
284
694
  };
285
695
  type ContainerRunOptions<T extends Record<string, any> = Record<string, any>, C = unknown> = {
286
696
  /**
287
- * Default values for the container output.
697
+ * Default values for the container output. Each key is optional — supply
698
+ * only the paths you want to backfill. When the validated output is missing
699
+ * a key (or holds `undefined`), the matching entry from `defaults` is used.
288
700
  */
289
- defaults?: { [Key in Path<T>]: any };
701
+ defaults?: { [Key in Path<T>]?: any };
290
702
  /**
291
703
  * Group to execute.
292
704
  */
@@ -330,13 +742,34 @@ type ContainerRunOptions<T extends Record<string, any> = Record<string, any>, C
330
742
  * resources (DB lookups, HTTP calls). Forwarded unchanged into nested
331
743
  * `run()` calls.
332
744
  *
333
- * Trade-off: in parallel mode each mount captures its `value` from the
334
- * input `data` *before* any other mount runs, so a later mount can no
335
- * longer read an earlier mount's transformed `output[key]`. Use
336
- * sequential mode (the default) for chained-key sanitize-then-validate
337
- * patterns.
745
+ * **Trade-off — chained-key reads are not supported in parallel mode.**
746
+ * Sequential `run()` reads each mount's `value` from `output[key]` when
747
+ * an earlier sibling mount already wrote there (so a sanitizer at
748
+ * `email` followed by a validator at `email` sees the sanitized output).
749
+ * Parallel mode reads `value` from the input `data` for every mount
750
+ * because siblings may not have completed yet. If you rely on chained
751
+ * sanitize-then-validate patterns, stay on sequential mode (the
752
+ * default). The behavior is intentional and consistent between
753
+ * `run({parallel: true})` and `safeRun({parallel: true})` — there is
754
+ * no diagnostic when a chained pattern is used in parallel mode; the
755
+ * later mount silently observes the un-sanitized input.
338
756
  */
339
757
  parallel?: boolean;
758
+ /**
759
+ * Per-mount result cache. When supplied, validator mounts that have
760
+ * NOT declared `sideEffect: true` (via `defineValidator`) will be
761
+ * skipped whenever the cached snapshot `(ctx.value, ctx.context,
762
+ * ctx.group)` matches the current invocation — replaying the prior
763
+ * issues and output without re-running the validator.
764
+ *
765
+ * Forwarded unchanged into nested `run()` calls so the same cache
766
+ * threads through the whole container tree (a nested container's
767
+ * own pure validators participate too).
768
+ *
769
+ * Omitting `cache` disables the optimization entirely; every mount
770
+ * runs every time, regardless of any `sideEffect` declaration.
771
+ */
772
+ cache?: IResultCache;
340
773
  };
341
774
  type MountOptions = {
342
775
  /**
@@ -379,32 +812,63 @@ type ResultFailure = {
379
812
  error: ValidupError;
380
813
  };
381
814
  type Result<T extends ObjectLiteral = ObjectLiteral> = ResultSuccess<T> | ResultFailure;
815
+ /**
816
+ * Input shape accepted by `IContainer.run` (and siblings). Typed as
817
+ * `Partial<T>` so callers can hand in form objects that are narrower than the
818
+ * validator's full entity type (the typical "create/edit form for a server
819
+ * entity" case — fields like `id` / `createdAt` are server-set and not part
820
+ * of the form). The runtime treats unmounted keys as pass-through, so the
821
+ * type just reflects what the validator actually inspects.
822
+ *
823
+ * **Extra keys.** A variable-typed object with extra keys not in `T` is
824
+ * accepted via TS's structural object-type rules (no excess-property check
825
+ * outside of fresh literals). An object **literal** with extra keys does
826
+ * trigger TS's excess-property check against `Partial<T>` — pre-fix
827
+ * `Record<string, any>` accepted such literals silently; if a call site
828
+ * relies on that, cast the literal or assign it to a variable first.
829
+ */
830
+ type ContainerInput<T extends ObjectLiteral = ObjectLiteral> = Partial<T>;
382
831
  interface IContainer<T extends ObjectLiteral = ObjectLiteral, C = unknown> {
383
832
  /**
384
- * Run container with given input.
385
- *
386
- * @param input
387
- * @param options
833
+ * Run the container against `input`. Throws `ValidupError` on validation
834
+ * failure; rethrows `signal.reason` when the run is aborted via
835
+ * `options.signal`.
388
836
  */
389
- run(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Promise<T>;
837
+ run(input?: ContainerInput<T>, options?: ContainerRunOptions<T, C>): Promise<T>;
390
838
  /**
391
- * Safe run container with given input.
839
+ * Run the container against `input` and return a discriminated `Result`
840
+ * instead of throwing on validation failure.
392
841
  *
393
- * @param input
394
- * @param options
842
+ * **Contract — when `safeRun` can still throw:**
843
+ * - The run is aborted via `options.signal` — `signal.reason` is
844
+ * re-thrown verbatim so callers can distinguish "validation failed"
845
+ * from "operation cancelled."
846
+ * - This is the **only** sanctioned reason. Implementations that throw
847
+ * for any other reason violate the contract; consumers that wrap
848
+ * `safeRun` in a defensive `try/catch` (e.g. `@validup/vue`) treat
849
+ * such throws as a synthetic path-less failure.
395
850
  */
396
- safeRun(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Promise<Result<T>>;
851
+ safeRun(input?: ContainerInput<T>, options?: ContainerRunOptions<T, C>): Promise<Result<T>>;
397
852
  /**
398
853
  * Synchronous variant of `run()`. Optional — implementations can omit
399
854
  * this when their validators are inherently async. The default
400
855
  * `Container` provides it; nested containers without it cannot be
401
856
  * traversed by a parent's `runSync`.
857
+ *
858
+ * Throws `RunSyncViolationError` (structural — distinct from validation
859
+ * failures) when any validator returns a thenable or any nested
860
+ * container lacks `runSync`. Those throws bypass the issue-folding path
861
+ * and surface verbatim.
402
862
  */
403
- runSync?(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): T;
863
+ runSync?(input?: ContainerInput<T>, options?: ContainerRunOptions<T, C>): T;
404
864
  /**
405
865
  * Synchronous variant of `safeRun()`. Optional — same caveat as `runSync`.
866
+ *
867
+ * Same throw-contract as `safeRun`, plus: `RunSyncViolationError`s are
868
+ * re-thrown (not wrapped into `Result.failure`) because they signal a
869
+ * structural mismatch, not a validation outcome.
406
870
  */
407
- safeRunSync?(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Result<T>;
871
+ safeRunSync?(input?: ContainerInput<T>, options?: ContainerRunOptions<T, C>): Result<T>;
408
872
  }
409
873
  type BaseMount = {
410
874
  options: MountOptions;
@@ -425,9 +889,320 @@ type ContainerMount = BaseMount & {
425
889
  type ValidatorMount<C = unknown> = BaseMount & {
426
890
  type: 'validator';
427
891
  data: Validator<C>;
892
+ /**
893
+ * Resolved at mount time from a `ValidatorDescriptor.sideEffect`
894
+ * declaration. `true` means the framework will never cache this
895
+ * mount's result; `false` / `undefined` means the result is
896
+ * cache-eligible when the caller supplies
897
+ * `ContainerRunOptions.cache`.
898
+ *
899
+ * Bare-function mounts always land here as `undefined` — the
900
+ * bare-function shape has no place to declare side effects, so
901
+ * the framework defaults them to cache-eligible (the same
902
+ * default as a `defineValidator` call without `sideEffect`).
903
+ * Wrap with `defineValidator({ sideEffect: true, run: fn })` to
904
+ * opt out.
905
+ */
906
+ sideEffect?: boolean;
428
907
  };
429
908
  type Mount<C = unknown> = ContainerMount | ValidatorMount<C>;
430
909
  //#endregion
910
+ //#region src/helpers/compose.d.ts
911
+ /**
912
+ * A composable element — either a bare `Validator<C>` function or a
913
+ * fully-built `IContainer<T, C>` instance. Containers participate
914
+ * with the same contract as validators (transform-or-throw); the
915
+ * dispatcher (`invokeComposeElement`) hides the call-shape difference.
916
+ *
917
+ * `IContainer<any, any>` (rather than something tighter) keeps the
918
+ * compose array heterogeneous — a chain can mix schemas / containers
919
+ * with different output shapes without forcing the caller to widen
920
+ * generics at every call site. The cost is that the composed
921
+ * `Validator`'s `Out` defaults to `unknown` (same as before).
922
+ */
923
+ type ComposeElement<C = unknown> = Validator<C> | IContainer<any, any>;
924
+ /**
925
+ * Options for {@link compose}. Discriminated on `oneOf` so the type
926
+ * surface enforces the (`bail` × `oneOf`) combinations that actually
927
+ * make sense:
928
+ *
929
+ * - `{}` / `{ bail?: boolean }` / `{ oneOf: false }` — the **all**
930
+ * strategy: every validator must pass, stages thread their return
931
+ * value into the next, `bail` controls fail-fast vs. collect-all.
932
+ * - `{ oneOf: true }` — the **any-of** strategy: the first branch to
933
+ * succeed wins and the composed validator returns its value;
934
+ * `bail` is rejected at compile time because there's no chain to
935
+ * bail out of.
936
+ */
937
+ type ComposeOptions = {
938
+ /**
939
+ * Run every validator and require all to pass (default). Stages
940
+ * thread their return into the next; `bail` controls whether the
941
+ * first failure stops the chain (`true`, default) or every failure
942
+ * is collected into one aggregate `ValidupError` (`false`).
943
+ *
944
+ * **Threading rule.** A stage's return replaces the threaded
945
+ * `ctx.value` only when defined — `undefined` is treated as a
946
+ * pass-through so pure checks that don't re-emit `ctx.value`
947
+ * compose cleanly with transformers. Stages that DO want to
948
+ * explicitly clear the field must throw or return a sentinel.
949
+ */
950
+ oneOf?: false;
951
+ bail?: boolean;
952
+ } | {
953
+ /**
954
+ * Run branches as alternatives in registration order — the first
955
+ * one to succeed wins, subsequent branches are not invoked, and
956
+ * the composed validator returns the winning branch's value
957
+ * (falling back to `ctx.value` if the winning branch returned
958
+ * `undefined`). When *every* branch fails, the composed validator
959
+ * throws a `ValidupError` whose first issue is an `IssueGroup`
960
+ * with `code: IssueCode.ONE_OF_FAILED` carrying every branch's
961
+ * collected failures (per-branch index surfaced via
962
+ * `data: { branch }`). Symmetric with
963
+ * `Container.options.oneOf`, just at the validator level.
964
+ *
965
+ * Each branch sees the original `ctx.value` — no threading
966
+ * across alternatives, since branches aren't a pipeline.
967
+ * `bail` is intentionally rejected at the type level under this
968
+ * mode: there's no chain to fail-fast over.
969
+ */
970
+ oneOf: true;
971
+ };
972
+ /**
973
+ * Compose multiple validators into a single `Validator`.
974
+ *
975
+ * Default (`oneOf: false`) — validators run in order; each stage's
976
+ * return value feeds the next as `ctx.value`. A stage that returns
977
+ * `undefined` is treated as a pass-through (upstream value continues
978
+ * down the chain), so pure checks that don't re-emit `ctx.value`
979
+ * compose cleanly with transformers. `bail: true` (default) stops at
980
+ * the first failure; `bail: false` collects every failure into a
981
+ * single `ValidupError`.
982
+ *
983
+ * `oneOf: true` — branches run as alternatives in registration order;
984
+ * the first branch to succeed wins and subsequent branches are not
985
+ * invoked. When every branch fails, the composed validator throws a
986
+ * `ValidupError` whose first issue is an `IssueGroup` with
987
+ * `code: IssueCode.ONE_OF_FAILED` carrying every branch's failures.
988
+ *
989
+ * Elements can be bare `Validator<C>` functions OR fully-built
990
+ * `IContainer<T, C>` instances — the dispatcher detects which and
991
+ * either calls the function with the threaded `ctx` or invokes the
992
+ * container's `run(value, { group, context, signal, path })` with
993
+ * the threaded value as input. Containers participate with the same
994
+ * transform-or-throw contract; their output replaces the threaded
995
+ * value in the all-strategy chain, and a successful container wins
996
+ * the branch in `oneOf` mode.
997
+ *
998
+ * @example
999
+ * // Fail-fast (default) — sanitize then validate
1000
+ * container.mount('email', compose([
1001
+ * trim(),
1002
+ * isEmail(),
1003
+ * isLength({ max: 254 }),
1004
+ * ]));
1005
+ *
1006
+ * // Collect-all — surface every broken rule for a richer error UI
1007
+ * container.mount('password', compose([
1008
+ * isLength({ min: 8 }),
1009
+ * isAlphanumeric(),
1010
+ * matches(/[0-9]/),
1011
+ * ], { bail: false }));
1012
+ *
1013
+ * // Any-of — accept either an email or a phone number on the same field
1014
+ * container.mount('contact', compose([
1015
+ * isEmail(),
1016
+ * isMobilePhone(),
1017
+ * ], { oneOf: true }));
1018
+ *
1019
+ * // Any-of with a container branch — accept a contact string OR a
1020
+ * // nested address object validated by its own container.
1021
+ * container.mount('contact', composeOneOf([
1022
+ * isEmail(),
1023
+ * isMobilePhone(),
1024
+ * addressContainer,
1025
+ * ]));
1026
+ *
1027
+ * Throws that aren't `ValidupError` / `Error` (raw strings, plain
1028
+ * objects, null) are synthesized into a single `IssueItem` so the
1029
+ * aggregate is never silently missing a contributing failure — mirrors
1030
+ * `Container.recordMountError`'s defensive behavior.
1031
+ */
1032
+ declare function compose<C = unknown>(elements: ComposeElement<C>[], options?: ComposeOptions): Validator<C>;
1033
+ /**
1034
+ * Sugar for `compose(elements, { oneOf: true })`. Reads more
1035
+ * naturally at the call site when the alternative semantic is the
1036
+ * intent, mirrors `Container`'s own `oneOf` option.
1037
+ */
1038
+ declare function composeOneOf<C = unknown>(elements: ComposeElement<C>[]): Validator<C>;
1039
+ //#endregion
1040
+ //#region src/helpers/create-error.d.ts
1041
+ /**
1042
+ * Trailing-args shape selected by the resolved `code`:
1043
+ *
1044
+ * - Parameterized code → `data` is required and typed.
1045
+ * - Bare code → no trailing arg accepted.
1046
+ * - Ad-hoc string code → `data?: Record<string, unknown>` optional.
1047
+ */
1048
+ type CreateValidupErrorTail<C> = ResolveIssueCode<C> extends ParameterizedIssueCode ? [data: IssueDataByCode[ResolveIssueCode<C> & ParameterizedIssueCode]] : ResolveIssueCode<C> extends BareIssueCode ? [] : [data?: Record<string, unknown>];
1049
+ /**
1050
+ * Build a `ValidupError` carrying a single `IssueItem` with the supplied
1051
+ * code / message / data. Sugar for the common one-issue failure
1052
+ * construction used by adapters and hand-rolled validators.
1053
+ *
1054
+ * The caller throws — keeping the `throw` keyword at the call site
1055
+ * makes the failure path obvious in the validator function body:
1056
+ *
1057
+ * ```ts
1058
+ * if (!validator.isEmail(s)) {
1059
+ * throw createValidupError(ctx.value, IssueCode.EMAIL, 'Invalid email');
1060
+ * }
1061
+ *
1062
+ * if (!isInRange(s)) {
1063
+ * throw createValidupError(ctx.value, IssueCode.MIN_VALUE, msg, { min: 18 });
1064
+ * }
1065
+ * ```
1066
+ *
1067
+ * The `code` you pass selects the `data` requirement at compile time:
1068
+ * parameterized codes (`MIN_LENGTH`, `STRONG_PASSWORD`, …) require their
1069
+ * typed payload; bare codes (`EMAIL`, `REQUIRED`, …) take no data; any
1070
+ * other string falls through to an open `Record<string, unknown>` data
1071
+ * argument.
1072
+ *
1073
+ * For multi-issue failures (e.g. inside {@link compose} with `{ bail: false }`),
1074
+ * build a `ValidupError` directly with
1075
+ * `new ValidupError([defineIssueItem(...), …])`.
1076
+ */
1077
+ declare function createValidupError<C extends string = typeof IssueCode.VALUE_INVALID>(received: unknown, code: C, message: string, ...rest: CreateValidupErrorTail<C>): ValidupError;
1078
+ //#endregion
1079
+ //#region src/helpers/defaults.d.ts
1080
+ /**
1081
+ * Slice a parent `defaults` map down to entries that target paths inside a
1082
+ * single nested container mount, with the mount-key prefix stripped so the
1083
+ * child sees them as local keys. Exact-key matches (the default targets the
1084
+ * mount root itself) are skipped — the parent's post-loop fill handles those
1085
+ * once the child has returned, since the child is run with `flat: true` and
1086
+ * cannot address its own root.
1087
+ */
1088
+ declare function resolveDefaults(defaults: Record<string, any> | undefined, key: string): Record<string, any> | undefined;
1089
+ //#endregion
1090
+ //#region src/helpers/error.d.ts
1091
+ declare function buildErrorMessageForAttribute(key: PropertyKey): string;
1092
+ declare function buildErrorMessageForAttributes(input: PropertyKey[] | Record<string, any>): string;
1093
+ //#endregion
1094
+ //#region src/helpers/error-to-issues.d.ts
1095
+ /**
1096
+ * Options for {@link errorToIssues}. Defaults match what the
1097
+ * orchestrating helpers (compose's collect-all catch, composeAnyOf's
1098
+ * branch-failure path) want out of the box.
1099
+ */
1100
+ type ErrorToIssuesOptions = {
1101
+ /**
1102
+ * Code stamped on the synthetic `IssueItem` when the thrown value
1103
+ * is an `Error` or a non-`Error` throw. Defaults to
1104
+ * `IssueCode.VALUE_INVALID`. `ValidupError` issues are spread
1105
+ * verbatim and DO NOT get this code applied; their own codes are
1106
+ * preserved.
1107
+ */
1108
+ code?: IssueCode | (string & {});
1109
+ /**
1110
+ * Path on the synthetic `IssueItem`. Defaults to `[]`.
1111
+ * `ValidupError` issues are spread verbatim with their original
1112
+ * paths intact — callers that want to prefix or transform spread
1113
+ * paths should do so after this fold (the surrounding Container
1114
+ * run loop does this in `prefixIssuePath`, for example).
1115
+ */
1116
+ path?: PropertyKey[];
1117
+ };
1118
+ /**
1119
+ * The "given an unknown throw, produce `Issue[]`" cascade shared by
1120
+ * the validator-orchestrating helpers. The branching is identical
1121
+ * at each site — `ValidupError` fans out, `Error` becomes one item,
1122
+ * anything else gets a defensive stringify — so it lives here.
1123
+ *
1124
+ * - `ValidupError` → returns a fresh array containing each of its
1125
+ * `issues` verbatim (callers can map/prefix after).
1126
+ * - `Error` → returns one `IssueItem` carrying the message + supplied
1127
+ * code/path.
1128
+ * - Anything else (string, plain object, `null`, …) → returns one
1129
+ * defensively-stringified `IssueItem` so the aggregate is never
1130
+ * silently missing a contributing failure.
1131
+ *
1132
+ * Callers layer their own per-site concerns on top of the returned
1133
+ * issues: path prefixing, optional stamping, per-branch index
1134
+ * stamping, etc.
1135
+ */
1136
+ declare function errorToIssues(error: unknown, options?: ErrorToIssuesOptions): Issue[];
1137
+ //#endregion
1138
+ //#region src/helpers/one-of-failed.d.ts
1139
+ /**
1140
+ * Options for {@link buildOneOfFailedGroup}.
1141
+ */
1142
+ type BuildOneOfFailedGroupOptions = {
1143
+ /**
1144
+ * Path on the wrapping group. Defaults to `[]` — most callers
1145
+ * (compose's `composeAnyOf`, the run-loop entry to a oneOf
1146
+ * container) emit the group at the boundary they own and let the
1147
+ * surrounding context attach a path.
1148
+ */
1149
+ path?: PropertyKey[];
1150
+ /**
1151
+ * Override the default English message. The wrapping group
1152
+ * carries `code: IssueCode.ONE_OF_FAILED`, so i18n catalogs key
1153
+ * off the code rather than the message; the message is only the
1154
+ * fallback rendering.
1155
+ */
1156
+ message?: string;
1157
+ };
1158
+ /**
1159
+ * Build the `IssueGroup` that wraps an every-branch-failed aggregate
1160
+ * — used by `composeAnyOf` (validator-level oneOf) AND
1161
+ * `Container.finalizeOutput` (container-level `oneOf` option). Sharing
1162
+ * the shape keeps the `IssueCode.ONE_OF_FAILED` contract symmetric so
1163
+ * consumers / i18n catalogs only need one format for both modes.
1164
+ */
1165
+ declare function buildOneOfFailedGroup(branchIssues: Issue[], options?: BuildOneOfFailedGroupOptions): IssueGroup;
1166
+ //#endregion
1167
+ //#region src/helpers/optional-value.d.ts
1168
+ /**
1169
+ * Check if input value (type of) satisfies optional value type constraint.
1170
+ *
1171
+ * @param value
1172
+ * @param optionalValue
1173
+ */
1174
+ declare function isOptionalValue(value: unknown, optionalValue?: `${OptionalValue}`): boolean;
1175
+ //#endregion
1176
+ //#region src/helpers/path-filter.d.ts
1177
+ type PathFilterResolution = {
1178
+ skip: boolean;
1179
+ pathsToInclude: string[] | undefined;
1180
+ pathsToExclude: string[] | undefined;
1181
+ };
1182
+ /**
1183
+ * Resolve `pathsToInclude` / `pathsToExclude` against a single mounted item's
1184
+ * (already-expanded) local `key`. Returns whether to skip the item, plus the
1185
+ * filter sub-lists to forward into a child container — with the parent prefix
1186
+ * stripped so the child can match purely against its own local keys.
1187
+ *
1188
+ * Semantics:
1189
+ * - Un-keyed container mount (`key === ''`) shares the parent's namespace, so
1190
+ * filters are forwarded verbatim.
1191
+ * - Exact match in `pathsToInclude` / `pathsToExclude` matches the whole mount.
1192
+ * - Prefix match (`<key>.…`) only descends into container mounts; leaf
1193
+ * validators with deeper-target filters fall through (skipped for include,
1194
+ * kept for exclude).
1195
+ */
1196
+ declare function resolvePathFilter(pathsToInclude: string[] | undefined, pathsToExclude: string[] | undefined, key: string, isContainer: boolean): PathFilterResolution;
1197
+ //#endregion
1198
+ //#region src/helpers/path-stringify.d.ts
1199
+ /**
1200
+ * Stringify path array to string.
1201
+ *
1202
+ * @param input
1203
+ */
1204
+ declare function stringifyPath(input: PropertyKey[]): string;
1205
+ //#endregion
431
1206
  //#region src/container/check.d.ts
432
1207
  declare function isContainer(input: unknown): input is IContainer;
433
1208
  //#endregion
@@ -438,33 +1213,105 @@ declare class Container<T extends Record<string, any> = Record<string, any>, C =
438
1213
  constructor(options?: ContainerOptions<T>);
439
1214
  mount(container: IContainer<any, any>): void;
440
1215
  mount(options: MountOptions, container: IContainer<any, any>): void;
441
- mount(key: Path<T> | (string & {}), data: IContainer<any, any> | Validator<C>): void;
442
- mount(key: Path<T> | (string & {}), options: MountOptions, data: IContainer<any, any> | Validator<C>): void;
1216
+ mount(key: Path<T> | (string & {}), data: IContainer<any, any> | Validator<C> | ValidatorDescriptor<C>): void;
1217
+ mount(key: Path<T> | (string & {}), options: MountOptions, data: IContainer<any, any> | Validator<C> | ValidatorDescriptor<C>): void;
443
1218
  /**
444
- * @throws ValidupError
1219
+ * Run the container against `data`. Default execution mode — async,
1220
+ * sequential, throws `ValidupError` on validation failure.
1221
+ *
1222
+ * Variants for the other execution modes:
1223
+ * - `run(data, { parallel: true })` — async, sequential→concurrent. Each
1224
+ * mount captures `value` from `data` before any sibling runs, so chained
1225
+ * sanitize-then-validate patterns are not supported.
1226
+ * - {@link Container.safeRun} — same as `run` but returns a discriminated
1227
+ * `Result<T>` instead of throwing on validation failure (still rethrows
1228
+ * on abort).
1229
+ * - {@link Container.runSync} / {@link Container.safeRunSync} — synchronous
1230
+ * variants for graphs where every validator (and every nested container's
1231
+ * `runSync`) is synchronous.
1232
+ *
1233
+ * Aborts surface verbatim — the abort is detected via `signal.throwIfAborted()`
1234
+ * between mounts (which throws `signal.reason`), and any error raised by a
1235
+ * mid-flight validator during an aborted run is re-thrown as-is rather than
1236
+ * folded into the issue tree. Callers can therefore distinguish "validation
1237
+ * failed" from "operation cancelled," but should not assume the thrown value
1238
+ * is always `signal.reason` — a validator that throws its own error before
1239
+ * the next abort check produces that error instead.
445
1240
  *
446
- * @param data
447
- * @param options
1241
+ * @throws ValidupError on validation failure.
1242
+ * @throws signal.reason when the abort check fires between mounts.
1243
+ * @throws (mid-flight validator error) when a validator throws during an
1244
+ * already-aborted run — re-raised as-is rather than wrapped.
448
1245
  */
449
- run(data?: Record<string, any>, options?: ContainerRunOptions<T, C>): Promise<T>;
1246
+ run(data?: ContainerInput<T>, options?: ContainerRunOptions<T, C>): Promise<T>;
450
1247
  /**
451
1248
  * Parallel-execution variant of `run()`. All mounts kick off their
452
1249
  * promises eagerly and the results are merged after `Promise.allSettled`.
453
1250
  * See `ContainerRunOptions.parallel` for the trade-off note.
454
1251
  */
455
1252
  private runParallel;
456
- safeRun(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Promise<Result<T>>;
1253
+ safeRun(input?: ContainerInput<T>, options?: ContainerRunOptions<T, C>): Promise<Result<T>>;
1254
+ /**
1255
+ * Synchronous variant of {@link Container.run}. Use it for purely
1256
+ * synchronous validator graphs where the microtask overhead of `await`
1257
+ * per mount matters (e.g. driving a reactive UI without a `pending`
1258
+ * flicker on every keystroke).
1259
+ *
1260
+ * Each mounted validator's return value MUST NOT be a thenable, and every
1261
+ * nested container MUST implement `runSync`. Either violation throws
1262
+ * `RunSyncViolationError` (structural — distinct from validation
1263
+ * failures), so the diagnostic is surfaced verbatim rather than wrapped
1264
+ * into a `ValidupError`. The companion {@link Container.safeRunSync}
1265
+ * still rethrows these for the same reason.
1266
+ *
1267
+ * No `parallel` variant — synchronous graphs don't benefit from
1268
+ * concurrency, and `Promise.allSettled` is async by definition.
1269
+ *
1270
+ * Aborts surface the same way as {@link Container.run}: the
1271
+ * `signal.throwIfAborted()` check between mounts throws `signal.reason`,
1272
+ * and a mid-flight validator throw during an already-aborted run is
1273
+ * re-raised verbatim. Don't assume the thrown value is always
1274
+ * `signal.reason`.
1275
+ *
1276
+ * @throws ValidupError on validation failure.
1277
+ * @throws RunSyncViolationError when a validator returns a Promise or a
1278
+ * nested container does not implement `runSync`.
1279
+ * @throws signal.reason when the abort check fires between mounts.
1280
+ * @throws (mid-flight validator error) when a validator throws during an
1281
+ * already-aborted run.
1282
+ */
1283
+ runSync(data?: ContainerInput<T>, options?: ContainerRunOptions<T, C>): T;
1284
+ safeRunSync(input?: ContainerInput<T>, options?: ContainerRunOptions<T, C>): Result<T>;
457
1285
  /**
458
- * @throws ValidupError
1286
+ * Lookup helper for the per-mount result cache.
459
1287
  *
460
- * Synchronous variant of `run()`. Throws synchronously if any validator
461
- * returns a thenable, or if a nested container does not implement
462
- * `runSync`. Use it for purely synchronous validator graphs where the
463
- * microtask overhead of `await` per mount matters (e.g. driving a
464
- * reactive UI without a `pending` flicker).
1288
+ * Returns `undefined` (forcing a real run) for any of:
1289
+ * - No `cache` supplied — caller didn't opt in.
1290
+ * - Mount isn't a validator — container mounts run their own
1291
+ * inner loop, which consults the cache for their own mounts.
1292
+ * - Validator declared `sideEffect: true` — its result depends on
1293
+ * inputs the snapshot doesn't capture (sibling fields, network,
1294
+ * global state), so caching would be unsound.
1295
+ * - No prior entry stored for this `(mount, key)` pair.
1296
+ * - Stored snapshot's `value` / `context` / `group` don't all match
1297
+ * the current invocation by `Object.is`.
465
1298
  */
466
- runSync(data?: Record<string, any>, options?: ContainerRunOptions<T, C>): T;
467
- safeRunSync(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Result<T>;
1299
+ private resolveCachedOutcome;
1300
+ /**
1301
+ * Store the outcome of a fresh validator invocation. No-ops in the
1302
+ * same cases `resolveCachedOutcome` returns `undefined` for, plus:
1303
+ *
1304
+ * - `signal.aborted` — the throw was caused by cancellation, not by
1305
+ * a validation outcome we want to remember. Caching the abort
1306
+ * would mean future replays surface "AbortError" as a fake
1307
+ * validation issue every time the same snapshot is seen, even
1308
+ * in fully-completed runs.
1309
+ *
1310
+ * `RunSyncViolationError`s are filtered out at the call site
1311
+ * (`runSync` only) because they're structural — the validator
1312
+ * graph is wrong, not the input.
1313
+ */
1314
+ private writeCachedOutcome;
468
1315
  private resolveContainerFilters;
469
1316
  /**
470
1317
  * Prepend `keyParts` to a child issue's `path` and — when the child is
@@ -477,12 +1324,42 @@ declare class Container<T extends Record<string, any> = Record<string, any>, C =
477
1324
  */
478
1325
  private prefixIssuePath;
479
1326
  /**
480
- * Translate a per-mount throw into accumulated `issues`. Re-throws when
1327
+ * Translate a throw raised by one execution step (one validator or
1328
+ * nested-container invocation, from the surrounding `run` loop) into
1329
+ * accumulated issues and push them onto `context.issues`. Re-throws when
481
1330
  * the run was aborted (signal-aware validators) so abort errors are not
482
- * mangled into validation issues. `keyParts` is the current mount's
483
- * expanded path (used to prepend to nested `ValidupError` issues).
1331
+ * mangled into validation issues.
1332
+ *
1333
+ * "Mount" is the *setup-time* verb (`container.mount(...)`); what failed
1334
+ * here is the *execution* of an already-mounted unit — hence the name.
1335
+ *
1336
+ * The context object captures everything the error path needs to know
1337
+ * about the failing step: the thrown value (`error`), the mount
1338
+ * descriptor (`item`), the current input (`value` — kept around so we
1339
+ * can re-evaluate predicate-optional declarations at error time), the
1340
+ * expanded path (`keyParts` — used to prepend to nested `ValidupError`
1341
+ * issues) and the trailing segment (`pathRelative` — used when wrapping
1342
+ * multi-issue or container emissions into an `IssueGroup`). The
1343
+ * destination accumulator (`issues`) and the abort `signal` round out
1344
+ * what's needed to handle the failure.
1345
+ *
1346
+ * @modifies context.issues — appends one or more entries per call.
1347
+ */
1348
+ private collectExecutionFailure;
1349
+ /**
1350
+ * For `oneOf` containers, wrap the issues produced by a single branch
1351
+ * (slice from `branchStart` to the end of `issues`) into one sub-group
1352
+ * so per-branch identity is preserved in the final aggregate. Non-oneOf
1353
+ * containers leave the issue list untouched — they don't need branch
1354
+ * partitioning.
1355
+ *
1356
+ * The wrapping group's `path` is `[]` (the branch wraps everything
1357
+ * inside it; per-leaf paths are unchanged); `data.branch` is the
1358
+ * mount index; and `data.name` (when set) is the mount path so
1359
+ * consumers can label "branch X failed" without recomputing the
1360
+ * registration order.
484
1361
  */
485
- private recordMountError;
1362
+ private wrapBranchForOneOf;
486
1363
  /**
487
1364
  * Apply post-loop semantics: oneOf aggregation, error throw, defaults
488
1365
  * fill, and flat-vs-nested output expansion.
@@ -610,5 +1487,5 @@ declare function hasOwnProperty<X extends {}, Y extends PropertyKey>(obj: X, pro
610
1487
  //#region src/utils/object.d.ts
611
1488
  declare function isObject(input: unknown): input is Record<string, any>;
612
1489
  //#endregion
613
- export { BaseMount, Builder, Container, ContainerMount, ContainerOptions, ContainerRunOptions, GroupKey, IBuilder, IContainer, IsOptional, Issue, IssueBase, IssueCode, IssueCodeRegistry, IssueGroup, IssueItem, IssueMessageTemplates, Mount, MountOptions, MountTarget, Mounted, ObjectLiteral, OptionalValue, PathFilterResolution, Result, ResultFailure, ResultSuccess, Spread, Validator, ValidatorContext, ValidatorMount, ValidupError, buildErrorMessageForAttribute, buildErrorMessageForAttributes, defineIssueGroup, defineIssueItem, defineSchema, flattenIssueGroups, flattenIssueItems, formatIssue, hasOwnProperty, interpolate, isContainer, isError, isIssue, isIssueGroup, isIssueItem, isObject, isOptionalValue, isValidupError, resolveDefaults, resolvePathFilter, stringifyPath };
1490
+ export { BareIssueCode, BaseMount, BuildOneOfFailedGroupOptions, Builder, ComposeElement, ComposeOptions, Container, ContainerInput, ContainerMount, ContainerOptions, ContainerRunOptions, ErrorToIssuesOptions, GroupKey, IBuilder, IContainer, IResultCache, IsOptional, Issue, IssueBase, IssueCode, IssueDataByCode, IssueGroup, IssueItem, IssueItemBare, IssueItemRaw, IssueItemTyped, IssueMessageTemplates, Mount, MountOptions, MountTarget, Mounted, ObjectLiteral, OptionalValue, ParameterizedIssueCode, PathFilterResolution, ResolveIssueCode, Result, ResultCache, ResultCacheEntry, ResultCacheOutcome, ResultCacheSnapshot, ResultFailure, ResultSuccess, Spread, Validator, ValidatorContext, ValidatorDescriptor, ValidatorMount, ValidupError, buildErrorMessageForAttribute, buildErrorMessageForAttributes, buildOneOfFailedGroup, compose, composeOneOf, createValidupError, defineIssueGroup, defineIssueItem, defineSchema, defineValidator, errorToIssues, flattenIssueGroups, flattenIssueItems, formatIssue, hasOwnProperty, interpolate, isContainer, isError, isIssue, isIssueGroup, isIssueItem, isObject, isOptionalValue, isResultCache, isValidatorDescriptor, isValidupError, resolveDefaults, resolvePathFilter, stringifyPath };
614
1491
  //# sourceMappingURL=index.d.mts.map