validup 0.3.0 → 0.4.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/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> = {
@@ -330,13 +740,34 @@ type ContainerRunOptions<T extends Record<string, any> = Record<string, any>, C
330
740
  * resources (DB lookups, HTTP calls). Forwarded unchanged into nested
331
741
  * `run()` calls.
332
742
  *
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.
743
+ * **Trade-off — chained-key reads are not supported in parallel mode.**
744
+ * Sequential `run()` reads each mount's `value` from `output[key]` when
745
+ * an earlier sibling mount already wrote there (so a sanitizer at
746
+ * `email` followed by a validator at `email` sees the sanitized output).
747
+ * Parallel mode reads `value` from the input `data` for every mount
748
+ * because siblings may not have completed yet. If you rely on chained
749
+ * sanitize-then-validate patterns, stay on sequential mode (the
750
+ * default). The behavior is intentional and consistent between
751
+ * `run({parallel: true})` and `safeRun({parallel: true})` — there is
752
+ * no diagnostic when a chained pattern is used in parallel mode; the
753
+ * later mount silently observes the un-sanitized input.
338
754
  */
339
755
  parallel?: boolean;
756
+ /**
757
+ * Per-mount result cache. When supplied, validator mounts that have
758
+ * NOT declared `sideEffect: true` (via `defineValidator`) will be
759
+ * skipped whenever the cached snapshot `(ctx.value, ctx.context,
760
+ * ctx.group)` matches the current invocation — replaying the prior
761
+ * issues and output without re-running the validator.
762
+ *
763
+ * Forwarded unchanged into nested `run()` calls so the same cache
764
+ * threads through the whole container tree (a nested container's
765
+ * own pure validators participate too).
766
+ *
767
+ * Omitting `cache` disables the optimization entirely; every mount
768
+ * runs every time, regardless of any `sideEffect` declaration.
769
+ */
770
+ cache?: IResultCache;
340
771
  };
341
772
  type MountOptions = {
342
773
  /**
@@ -381,17 +812,23 @@ type ResultFailure = {
381
812
  type Result<T extends ObjectLiteral = ObjectLiteral> = ResultSuccess<T> | ResultFailure;
382
813
  interface IContainer<T extends ObjectLiteral = ObjectLiteral, C = unknown> {
383
814
  /**
384
- * Run container with given input.
385
- *
386
- * @param input
387
- * @param options
815
+ * Run the container against `input`. Throws `ValidupError` on validation
816
+ * failure; rethrows `signal.reason` when the run is aborted via
817
+ * `options.signal`.
388
818
  */
389
819
  run(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Promise<T>;
390
820
  /**
391
- * Safe run container with given input.
821
+ * Run the container against `input` and return a discriminated `Result`
822
+ * instead of throwing on validation failure.
392
823
  *
393
- * @param input
394
- * @param options
824
+ * **Contract — when `safeRun` can still throw:**
825
+ * - The run is aborted via `options.signal` — `signal.reason` is
826
+ * re-thrown verbatim so callers can distinguish "validation failed"
827
+ * from "operation cancelled."
828
+ * - This is the **only** sanctioned reason. Implementations that throw
829
+ * for any other reason violate the contract; consumers that wrap
830
+ * `safeRun` in a defensive `try/catch` (e.g. `@validup/vue`) treat
831
+ * such throws as a synthetic path-less failure.
395
832
  */
396
833
  safeRun(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Promise<Result<T>>;
397
834
  /**
@@ -399,10 +836,19 @@ interface IContainer<T extends ObjectLiteral = ObjectLiteral, C = unknown> {
399
836
  * this when their validators are inherently async. The default
400
837
  * `Container` provides it; nested containers without it cannot be
401
838
  * traversed by a parent's `runSync`.
839
+ *
840
+ * Throws `RunSyncViolationError` (structural — distinct from validation
841
+ * failures) when any validator returns a thenable or any nested
842
+ * container lacks `runSync`. Those throws bypass the issue-folding path
843
+ * and surface verbatim.
402
844
  */
403
845
  runSync?(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): T;
404
846
  /**
405
847
  * Synchronous variant of `safeRun()`. Optional — same caveat as `runSync`.
848
+ *
849
+ * Same throw-contract as `safeRun`, plus: `RunSyncViolationError`s are
850
+ * re-thrown (not wrapped into `Result.failure`) because they signal a
851
+ * structural mismatch, not a validation outcome.
406
852
  */
407
853
  safeRunSync?(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Result<T>;
408
854
  }
@@ -425,9 +871,320 @@ type ContainerMount = BaseMount & {
425
871
  type ValidatorMount<C = unknown> = BaseMount & {
426
872
  type: 'validator';
427
873
  data: Validator<C>;
874
+ /**
875
+ * Resolved at mount time from a `ValidatorDescriptor.sideEffect`
876
+ * declaration. `true` means the framework will never cache this
877
+ * mount's result; `false` / `undefined` means the result is
878
+ * cache-eligible when the caller supplies
879
+ * `ContainerRunOptions.cache`.
880
+ *
881
+ * Bare-function mounts always land here as `undefined` — the
882
+ * bare-function shape has no place to declare side effects, so
883
+ * the framework defaults them to cache-eligible (the same
884
+ * default as a `defineValidator` call without `sideEffect`).
885
+ * Wrap with `defineValidator({ sideEffect: true, run: fn })` to
886
+ * opt out.
887
+ */
888
+ sideEffect?: boolean;
428
889
  };
429
890
  type Mount<C = unknown> = ContainerMount | ValidatorMount<C>;
430
891
  //#endregion
892
+ //#region src/helpers/compose.d.ts
893
+ /**
894
+ * A composable element — either a bare `Validator<C>` function or a
895
+ * fully-built `IContainer<T, C>` instance. Containers participate
896
+ * with the same contract as validators (transform-or-throw); the
897
+ * dispatcher (`invokeComposeElement`) hides the call-shape difference.
898
+ *
899
+ * `IContainer<any, any>` (rather than something tighter) keeps the
900
+ * compose array heterogeneous — a chain can mix schemas / containers
901
+ * with different output shapes without forcing the caller to widen
902
+ * generics at every call site. The cost is that the composed
903
+ * `Validator`'s `Out` defaults to `unknown` (same as before).
904
+ */
905
+ type ComposeElement<C = unknown> = Validator<C> | IContainer<any, any>;
906
+ /**
907
+ * Options for {@link compose}. Discriminated on `oneOf` so the type
908
+ * surface enforces the (`bail` × `oneOf`) combinations that actually
909
+ * make sense:
910
+ *
911
+ * - `{}` / `{ bail?: boolean }` / `{ oneOf: false }` — the **all**
912
+ * strategy: every validator must pass, stages thread their return
913
+ * value into the next, `bail` controls fail-fast vs. collect-all.
914
+ * - `{ oneOf: true }` — the **any-of** strategy: the first branch to
915
+ * succeed wins and the composed validator returns its value;
916
+ * `bail` is rejected at compile time because there's no chain to
917
+ * bail out of.
918
+ */
919
+ type ComposeOptions = {
920
+ /**
921
+ * Run every validator and require all to pass (default). Stages
922
+ * thread their return into the next; `bail` controls whether the
923
+ * first failure stops the chain (`true`, default) or every failure
924
+ * is collected into one aggregate `ValidupError` (`false`).
925
+ *
926
+ * **Threading rule.** A stage's return replaces the threaded
927
+ * `ctx.value` only when defined — `undefined` is treated as a
928
+ * pass-through so pure checks that don't re-emit `ctx.value`
929
+ * compose cleanly with transformers. Stages that DO want to
930
+ * explicitly clear the field must throw or return a sentinel.
931
+ */
932
+ oneOf?: false;
933
+ bail?: boolean;
934
+ } | {
935
+ /**
936
+ * Run branches as alternatives in registration order — the first
937
+ * one to succeed wins, subsequent branches are not invoked, and
938
+ * the composed validator returns the winning branch's value
939
+ * (falling back to `ctx.value` if the winning branch returned
940
+ * `undefined`). When *every* branch fails, the composed validator
941
+ * throws a `ValidupError` whose first issue is an `IssueGroup`
942
+ * with `code: IssueCode.ONE_OF_FAILED` carrying every branch's
943
+ * collected failures (per-branch index surfaced via
944
+ * `data: { branch }`). Symmetric with
945
+ * `Container.options.oneOf`, just at the validator level.
946
+ *
947
+ * Each branch sees the original `ctx.value` — no threading
948
+ * across alternatives, since branches aren't a pipeline.
949
+ * `bail` is intentionally rejected at the type level under this
950
+ * mode: there's no chain to fail-fast over.
951
+ */
952
+ oneOf: true;
953
+ };
954
+ /**
955
+ * Compose multiple validators into a single `Validator`.
956
+ *
957
+ * Default (`oneOf: false`) — validators run in order; each stage's
958
+ * return value feeds the next as `ctx.value`. A stage that returns
959
+ * `undefined` is treated as a pass-through (upstream value continues
960
+ * down the chain), so pure checks that don't re-emit `ctx.value`
961
+ * compose cleanly with transformers. `bail: true` (default) stops at
962
+ * the first failure; `bail: false` collects every failure into a
963
+ * single `ValidupError`.
964
+ *
965
+ * `oneOf: true` — branches run as alternatives in registration order;
966
+ * the first branch to succeed wins and subsequent branches are not
967
+ * invoked. When every branch fails, the composed validator throws a
968
+ * `ValidupError` whose first issue is an `IssueGroup` with
969
+ * `code: IssueCode.ONE_OF_FAILED` carrying every branch's failures.
970
+ *
971
+ * Elements can be bare `Validator<C>` functions OR fully-built
972
+ * `IContainer<T, C>` instances — the dispatcher detects which and
973
+ * either calls the function with the threaded `ctx` or invokes the
974
+ * container's `run(value, { group, context, signal, path })` with
975
+ * the threaded value as input. Containers participate with the same
976
+ * transform-or-throw contract; their output replaces the threaded
977
+ * value in the all-strategy chain, and a successful container wins
978
+ * the branch in `oneOf` mode.
979
+ *
980
+ * @example
981
+ * // Fail-fast (default) — sanitize then validate
982
+ * container.mount('email', compose([
983
+ * trim(),
984
+ * isEmail(),
985
+ * isLength({ max: 254 }),
986
+ * ]));
987
+ *
988
+ * // Collect-all — surface every broken rule for a richer error UI
989
+ * container.mount('password', compose([
990
+ * isLength({ min: 8 }),
991
+ * isAlphanumeric(),
992
+ * matches(/[0-9]/),
993
+ * ], { bail: false }));
994
+ *
995
+ * // Any-of — accept either an email or a phone number on the same field
996
+ * container.mount('contact', compose([
997
+ * isEmail(),
998
+ * isMobilePhone(),
999
+ * ], { oneOf: true }));
1000
+ *
1001
+ * // Any-of with a container branch — accept a contact string OR a
1002
+ * // nested address object validated by its own container.
1003
+ * container.mount('contact', composeOneOf([
1004
+ * isEmail(),
1005
+ * isMobilePhone(),
1006
+ * addressContainer,
1007
+ * ]));
1008
+ *
1009
+ * Throws that aren't `ValidupError` / `Error` (raw strings, plain
1010
+ * objects, null) are synthesized into a single `IssueItem` so the
1011
+ * aggregate is never silently missing a contributing failure — mirrors
1012
+ * `Container.recordMountError`'s defensive behavior.
1013
+ */
1014
+ declare function compose<C = unknown>(elements: ComposeElement<C>[], options?: ComposeOptions): Validator<C>;
1015
+ /**
1016
+ * Sugar for `compose(elements, { oneOf: true })`. Reads more
1017
+ * naturally at the call site when the alternative semantic is the
1018
+ * intent, mirrors `Container`'s own `oneOf` option.
1019
+ */
1020
+ declare function composeOneOf<C = unknown>(elements: ComposeElement<C>[]): Validator<C>;
1021
+ //#endregion
1022
+ //#region src/helpers/create-error.d.ts
1023
+ /**
1024
+ * Trailing-args shape selected by the resolved `code`:
1025
+ *
1026
+ * - Parameterized code → `data` is required and typed.
1027
+ * - Bare code → no trailing arg accepted.
1028
+ * - Ad-hoc string code → `data?: Record<string, unknown>` optional.
1029
+ */
1030
+ type CreateValidupErrorTail<C> = ResolveIssueCode<C> extends ParameterizedIssueCode ? [data: IssueDataByCode[ResolveIssueCode<C> & ParameterizedIssueCode]] : ResolveIssueCode<C> extends BareIssueCode ? [] : [data?: Record<string, unknown>];
1031
+ /**
1032
+ * Build a `ValidupError` carrying a single `IssueItem` with the supplied
1033
+ * code / message / data. Sugar for the common one-issue failure
1034
+ * construction used by adapters and hand-rolled validators.
1035
+ *
1036
+ * The caller throws — keeping the `throw` keyword at the call site
1037
+ * makes the failure path obvious in the validator function body:
1038
+ *
1039
+ * ```ts
1040
+ * if (!validator.isEmail(s)) {
1041
+ * throw createValidupError(ctx.value, IssueCode.EMAIL, 'Invalid email');
1042
+ * }
1043
+ *
1044
+ * if (!isInRange(s)) {
1045
+ * throw createValidupError(ctx.value, IssueCode.MIN_VALUE, msg, { min: 18 });
1046
+ * }
1047
+ * ```
1048
+ *
1049
+ * The `code` you pass selects the `data` requirement at compile time:
1050
+ * parameterized codes (`MIN_LENGTH`, `STRONG_PASSWORD`, …) require their
1051
+ * typed payload; bare codes (`EMAIL`, `REQUIRED`, …) take no data; any
1052
+ * other string falls through to an open `Record<string, unknown>` data
1053
+ * argument.
1054
+ *
1055
+ * For multi-issue failures (e.g. inside {@link compose} with `{ bail: false }`),
1056
+ * build a `ValidupError` directly with
1057
+ * `new ValidupError([defineIssueItem(...), …])`.
1058
+ */
1059
+ declare function createValidupError<C extends string = typeof IssueCode.VALUE_INVALID>(received: unknown, code: C, message: string, ...rest: CreateValidupErrorTail<C>): ValidupError;
1060
+ //#endregion
1061
+ //#region src/helpers/defaults.d.ts
1062
+ /**
1063
+ * Slice a parent `defaults` map down to entries that target paths inside a
1064
+ * single nested container mount, with the mount-key prefix stripped so the
1065
+ * child sees them as local keys. Exact-key matches (the default targets the
1066
+ * mount root itself) are skipped — the parent's post-loop fill handles those
1067
+ * once the child has returned, since the child is run with `flat: true` and
1068
+ * cannot address its own root.
1069
+ */
1070
+ declare function resolveDefaults(defaults: Record<string, any> | undefined, key: string): Record<string, any> | undefined;
1071
+ //#endregion
1072
+ //#region src/helpers/error.d.ts
1073
+ declare function buildErrorMessageForAttribute(key: PropertyKey): string;
1074
+ declare function buildErrorMessageForAttributes(input: PropertyKey[] | Record<string, any>): string;
1075
+ //#endregion
1076
+ //#region src/helpers/error-to-issues.d.ts
1077
+ /**
1078
+ * Options for {@link errorToIssues}. Defaults match what the
1079
+ * orchestrating helpers (compose's collect-all catch, composeAnyOf's
1080
+ * branch-failure path) want out of the box.
1081
+ */
1082
+ type ErrorToIssuesOptions = {
1083
+ /**
1084
+ * Code stamped on the synthetic `IssueItem` when the thrown value
1085
+ * is an `Error` or a non-`Error` throw. Defaults to
1086
+ * `IssueCode.VALUE_INVALID`. `ValidupError` issues are spread
1087
+ * verbatim and DO NOT get this code applied; their own codes are
1088
+ * preserved.
1089
+ */
1090
+ code?: IssueCode | (string & {});
1091
+ /**
1092
+ * Path on the synthetic `IssueItem`. Defaults to `[]`.
1093
+ * `ValidupError` issues are spread verbatim with their original
1094
+ * paths intact — callers that want to prefix or transform spread
1095
+ * paths should do so after this fold (the surrounding Container
1096
+ * run loop does this in `prefixIssuePath`, for example).
1097
+ */
1098
+ path?: PropertyKey[];
1099
+ };
1100
+ /**
1101
+ * The "given an unknown throw, produce `Issue[]`" cascade shared by
1102
+ * the validator-orchestrating helpers. The branching is identical
1103
+ * at each site — `ValidupError` fans out, `Error` becomes one item,
1104
+ * anything else gets a defensive stringify — so it lives here.
1105
+ *
1106
+ * - `ValidupError` → returns a fresh array containing each of its
1107
+ * `issues` verbatim (callers can map/prefix after).
1108
+ * - `Error` → returns one `IssueItem` carrying the message + supplied
1109
+ * code/path.
1110
+ * - Anything else (string, plain object, `null`, …) → returns one
1111
+ * defensively-stringified `IssueItem` so the aggregate is never
1112
+ * silently missing a contributing failure.
1113
+ *
1114
+ * Callers layer their own per-site concerns on top of the returned
1115
+ * issues: path prefixing, optional stamping, per-branch index
1116
+ * stamping, etc.
1117
+ */
1118
+ declare function errorToIssues(error: unknown, options?: ErrorToIssuesOptions): Issue[];
1119
+ //#endregion
1120
+ //#region src/helpers/one-of-failed.d.ts
1121
+ /**
1122
+ * Options for {@link buildOneOfFailedGroup}.
1123
+ */
1124
+ type BuildOneOfFailedGroupOptions = {
1125
+ /**
1126
+ * Path on the wrapping group. Defaults to `[]` — most callers
1127
+ * (compose's `composeAnyOf`, the run-loop entry to a oneOf
1128
+ * container) emit the group at the boundary they own and let the
1129
+ * surrounding context attach a path.
1130
+ */
1131
+ path?: PropertyKey[];
1132
+ /**
1133
+ * Override the default English message. The wrapping group
1134
+ * carries `code: IssueCode.ONE_OF_FAILED`, so i18n catalogs key
1135
+ * off the code rather than the message; the message is only the
1136
+ * fallback rendering.
1137
+ */
1138
+ message?: string;
1139
+ };
1140
+ /**
1141
+ * Build the `IssueGroup` that wraps an every-branch-failed aggregate
1142
+ * — used by `composeAnyOf` (validator-level oneOf) AND
1143
+ * `Container.finalizeOutput` (container-level `oneOf` option). Sharing
1144
+ * the shape keeps the `IssueCode.ONE_OF_FAILED` contract symmetric so
1145
+ * consumers / i18n catalogs only need one format for both modes.
1146
+ */
1147
+ declare function buildOneOfFailedGroup(branchIssues: Issue[], options?: BuildOneOfFailedGroupOptions): IssueGroup;
1148
+ //#endregion
1149
+ //#region src/helpers/optional-value.d.ts
1150
+ /**
1151
+ * Check if input value (type of) satisfies optional value type constraint.
1152
+ *
1153
+ * @param value
1154
+ * @param optionalValue
1155
+ */
1156
+ declare function isOptionalValue(value: unknown, optionalValue?: `${OptionalValue}`): boolean;
1157
+ //#endregion
1158
+ //#region src/helpers/path-filter.d.ts
1159
+ type PathFilterResolution = {
1160
+ skip: boolean;
1161
+ pathsToInclude: string[] | undefined;
1162
+ pathsToExclude: string[] | undefined;
1163
+ };
1164
+ /**
1165
+ * Resolve `pathsToInclude` / `pathsToExclude` against a single mounted item's
1166
+ * (already-expanded) local `key`. Returns whether to skip the item, plus the
1167
+ * filter sub-lists to forward into a child container — with the parent prefix
1168
+ * stripped so the child can match purely against its own local keys.
1169
+ *
1170
+ * Semantics:
1171
+ * - Un-keyed container mount (`key === ''`) shares the parent's namespace, so
1172
+ * filters are forwarded verbatim.
1173
+ * - Exact match in `pathsToInclude` / `pathsToExclude` matches the whole mount.
1174
+ * - Prefix match (`<key>.…`) only descends into container mounts; leaf
1175
+ * validators with deeper-target filters fall through (skipped for include,
1176
+ * kept for exclude).
1177
+ */
1178
+ declare function resolvePathFilter(pathsToInclude: string[] | undefined, pathsToExclude: string[] | undefined, key: string, isContainer: boolean): PathFilterResolution;
1179
+ //#endregion
1180
+ //#region src/helpers/path-stringify.d.ts
1181
+ /**
1182
+ * Stringify path array to string.
1183
+ *
1184
+ * @param input
1185
+ */
1186
+ declare function stringifyPath(input: PropertyKey[]): string;
1187
+ //#endregion
431
1188
  //#region src/container/check.d.ts
432
1189
  declare function isContainer(input: unknown): input is IContainer;
433
1190
  //#endregion
@@ -438,13 +1195,35 @@ declare class Container<T extends Record<string, any> = Record<string, any>, C =
438
1195
  constructor(options?: ContainerOptions<T>);
439
1196
  mount(container: IContainer<any, any>): void;
440
1197
  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;
1198
+ mount(key: Path<T> | (string & {}), data: IContainer<any, any> | Validator<C> | ValidatorDescriptor<C>): void;
1199
+ mount(key: Path<T> | (string & {}), options: MountOptions, data: IContainer<any, any> | Validator<C> | ValidatorDescriptor<C>): void;
443
1200
  /**
444
- * @throws ValidupError
1201
+ * Run the container against `data`. Default execution mode — async,
1202
+ * sequential, throws `ValidupError` on validation failure.
1203
+ *
1204
+ * Variants for the other execution modes:
1205
+ * - `run(data, { parallel: true })` — async, sequential→concurrent. Each
1206
+ * mount captures `value` from `data` before any sibling runs, so chained
1207
+ * sanitize-then-validate patterns are not supported.
1208
+ * - {@link Container.safeRun} — same as `run` but returns a discriminated
1209
+ * `Result<T>` instead of throwing on validation failure (still rethrows
1210
+ * on abort).
1211
+ * - {@link Container.runSync} / {@link Container.safeRunSync} — synchronous
1212
+ * variants for graphs where every validator (and every nested container's
1213
+ * `runSync`) is synchronous.
1214
+ *
1215
+ * Aborts surface verbatim — the abort is detected via `signal.throwIfAborted()`
1216
+ * between mounts (which throws `signal.reason`), and any error raised by a
1217
+ * mid-flight validator during an aborted run is re-thrown as-is rather than
1218
+ * folded into the issue tree. Callers can therefore distinguish "validation
1219
+ * failed" from "operation cancelled," but should not assume the thrown value
1220
+ * is always `signal.reason` — a validator that throws its own error before
1221
+ * the next abort check produces that error instead.
445
1222
  *
446
- * @param data
447
- * @param options
1223
+ * @throws ValidupError on validation failure.
1224
+ * @throws signal.reason when the abort check fires between mounts.
1225
+ * @throws (mid-flight validator error) when a validator throws during an
1226
+ * already-aborted run — re-raised as-is rather than wrapped.
448
1227
  */
449
1228
  run(data?: Record<string, any>, options?: ContainerRunOptions<T, C>): Promise<T>;
450
1229
  /**
@@ -455,16 +1234,66 @@ declare class Container<T extends Record<string, any> = Record<string, any>, C =
455
1234
  private runParallel;
456
1235
  safeRun(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Promise<Result<T>>;
457
1236
  /**
458
- * @throws ValidupError
1237
+ * Synchronous variant of {@link Container.run}. Use it for purely
1238
+ * synchronous validator graphs where the microtask overhead of `await`
1239
+ * per mount matters (e.g. driving a reactive UI without a `pending`
1240
+ * flicker on every keystroke).
1241
+ *
1242
+ * Each mounted validator's return value MUST NOT be a thenable, and every
1243
+ * nested container MUST implement `runSync`. Either violation throws
1244
+ * `RunSyncViolationError` (structural — distinct from validation
1245
+ * failures), so the diagnostic is surfaced verbatim rather than wrapped
1246
+ * into a `ValidupError`. The companion {@link Container.safeRunSync}
1247
+ * still rethrows these for the same reason.
1248
+ *
1249
+ * No `parallel` variant — synchronous graphs don't benefit from
1250
+ * concurrency, and `Promise.allSettled` is async by definition.
459
1251
  *
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).
1252
+ * Aborts surface the same way as {@link Container.run}: the
1253
+ * `signal.throwIfAborted()` check between mounts throws `signal.reason`,
1254
+ * and a mid-flight validator throw during an already-aborted run is
1255
+ * re-raised verbatim. Don't assume the thrown value is always
1256
+ * `signal.reason`.
1257
+ *
1258
+ * @throws ValidupError on validation failure.
1259
+ * @throws RunSyncViolationError when a validator returns a Promise or a
1260
+ * nested container does not implement `runSync`.
1261
+ * @throws signal.reason when the abort check fires between mounts.
1262
+ * @throws (mid-flight validator error) when a validator throws during an
1263
+ * already-aborted run.
465
1264
  */
466
1265
  runSync(data?: Record<string, any>, options?: ContainerRunOptions<T, C>): T;
467
1266
  safeRunSync(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Result<T>;
1267
+ /**
1268
+ * Lookup helper for the per-mount result cache.
1269
+ *
1270
+ * Returns `undefined` (forcing a real run) for any of:
1271
+ * - No `cache` supplied — caller didn't opt in.
1272
+ * - Mount isn't a validator — container mounts run their own
1273
+ * inner loop, which consults the cache for their own mounts.
1274
+ * - Validator declared `sideEffect: true` — its result depends on
1275
+ * inputs the snapshot doesn't capture (sibling fields, network,
1276
+ * global state), so caching would be unsound.
1277
+ * - No prior entry stored for this `(mount, key)` pair.
1278
+ * - Stored snapshot's `value` / `context` / `group` don't all match
1279
+ * the current invocation by `Object.is`.
1280
+ */
1281
+ private resolveCachedOutcome;
1282
+ /**
1283
+ * Store the outcome of a fresh validator invocation. No-ops in the
1284
+ * same cases `resolveCachedOutcome` returns `undefined` for, plus:
1285
+ *
1286
+ * - `signal.aborted` — the throw was caused by cancellation, not by
1287
+ * a validation outcome we want to remember. Caching the abort
1288
+ * would mean future replays surface "AbortError" as a fake
1289
+ * validation issue every time the same snapshot is seen, even
1290
+ * in fully-completed runs.
1291
+ *
1292
+ * `RunSyncViolationError`s are filtered out at the call site
1293
+ * (`runSync` only) because they're structural — the validator
1294
+ * graph is wrong, not the input.
1295
+ */
1296
+ private writeCachedOutcome;
468
1297
  private resolveContainerFilters;
469
1298
  /**
470
1299
  * Prepend `keyParts` to a child issue's `path` and — when the child is
@@ -477,12 +1306,42 @@ declare class Container<T extends Record<string, any> = Record<string, any>, C =
477
1306
  */
478
1307
  private prefixIssuePath;
479
1308
  /**
480
- * Translate a per-mount throw into accumulated `issues`. Re-throws when
1309
+ * Translate a throw raised by one execution step (one validator or
1310
+ * nested-container invocation, from the surrounding `run` loop) into
1311
+ * accumulated issues and push them onto `context.issues`. Re-throws when
481
1312
  * 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).
1313
+ * mangled into validation issues.
1314
+ *
1315
+ * "Mount" is the *setup-time* verb (`container.mount(...)`); what failed
1316
+ * here is the *execution* of an already-mounted unit — hence the name.
1317
+ *
1318
+ * The context object captures everything the error path needs to know
1319
+ * about the failing step: the thrown value (`error`), the mount
1320
+ * descriptor (`item`), the current input (`value` — kept around so we
1321
+ * can re-evaluate predicate-optional declarations at error time), the
1322
+ * expanded path (`keyParts` — used to prepend to nested `ValidupError`
1323
+ * issues) and the trailing segment (`pathRelative` — used when wrapping
1324
+ * multi-issue or container emissions into an `IssueGroup`). The
1325
+ * destination accumulator (`issues`) and the abort `signal` round out
1326
+ * what's needed to handle the failure.
1327
+ *
1328
+ * @modifies context.issues — appends one or more entries per call.
1329
+ */
1330
+ private collectExecutionFailure;
1331
+ /**
1332
+ * For `oneOf` containers, wrap the issues produced by a single branch
1333
+ * (slice from `branchStart` to the end of `issues`) into one sub-group
1334
+ * so per-branch identity is preserved in the final aggregate. Non-oneOf
1335
+ * containers leave the issue list untouched — they don't need branch
1336
+ * partitioning.
1337
+ *
1338
+ * The wrapping group's `path` is `[]` (the branch wraps everything
1339
+ * inside it; per-leaf paths are unchanged); `data.branch` is the
1340
+ * mount index; and `data.name` (when set) is the mount path so
1341
+ * consumers can label "branch X failed" without recomputing the
1342
+ * registration order.
484
1343
  */
485
- private recordMountError;
1344
+ private wrapBranchForOneOf;
486
1345
  /**
487
1346
  * Apply post-loop semantics: oneOf aggregation, error throw, defaults
488
1347
  * fill, and flat-vs-nested output expansion.
@@ -610,5 +1469,5 @@ declare function hasOwnProperty<X extends {}, Y extends PropertyKey>(obj: X, pro
610
1469
  //#region src/utils/object.d.ts
611
1470
  declare function isObject(input: unknown): input is Record<string, any>;
612
1471
  //#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 };
1472
+ export { BareIssueCode, BaseMount, BuildOneOfFailedGroupOptions, Builder, ComposeElement, ComposeOptions, Container, 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
1473
  //# sourceMappingURL=index.d.mts.map