validup 0.2.2 → 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/LICENSE +201 -21
- package/README.md +868 -115
- package/dist/index.d.mts +1473 -0
- package/dist/index.mjs +1561 -450
- package/dist/index.mjs.map +1 -1
- package/package.json +16 -18
- package/dist/constants.d.ts +0 -17
- package/dist/container/check.d.ts +0 -2
- package/dist/container/index.d.ts +0 -3
- package/dist/container/module.d.ts +0 -23
- package/dist/container/types.d.ts +0 -120
- package/dist/error/base.d.ts +0 -5
- package/dist/error/check.d.ts +0 -5
- package/dist/error/index.d.ts +0 -2
- package/dist/helpers/error.d.ts +0 -2
- package/dist/helpers/index.d.ts +0 -3
- package/dist/helpers/optional-value.d.ts +0 -8
- package/dist/helpers/path-stringify.d.ts +0 -6
- package/dist/index.cjs +0 -494
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.ts +0 -7
- package/dist/issue/check.d.ts +0 -4
- package/dist/issue/constants.d.ts +0 -4
- package/dist/issue/define.d.ts +0 -5
- package/dist/issue/index.d.ts +0 -4
- package/dist/issue/types.d.ts +0 -47
- package/dist/types.d.ts +0 -24
- package/dist/utils/has-own-property.d.ts +0 -1
- package/dist/utils/index.d.ts +0 -2
- package/dist/utils/object.d.ts +0 -1
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,1473 @@
|
|
|
1
|
+
import { BaseError, interpolate } from "@ebec/core";
|
|
2
|
+
import { Path } from "pathtrace";
|
|
3
|
+
|
|
4
|
+
//#region src/cache/types.d.ts
|
|
5
|
+
/**
|
|
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
|
+
*/
|
|
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
|
+
}
|
|
72
|
+
//#endregion
|
|
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
|
+
}
|
|
107
|
+
//#endregion
|
|
108
|
+
//#region src/constants.d.ts
|
|
109
|
+
declare enum GroupKey {
|
|
110
|
+
WILDCARD = "*"
|
|
111
|
+
}
|
|
112
|
+
declare enum OptionalValue {
|
|
113
|
+
/**
|
|
114
|
+
* Treats only `undefined` as optional. Default.
|
|
115
|
+
*/
|
|
116
|
+
UNDEFINED = "undefined",
|
|
117
|
+
/**
|
|
118
|
+
* Treats `null` and `undefined` as optional.
|
|
119
|
+
*/
|
|
120
|
+
NULL = "null",
|
|
121
|
+
/**
|
|
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`).
|
|
130
|
+
*/
|
|
131
|
+
FALSY = "falsy"
|
|
132
|
+
}
|
|
133
|
+
//#endregion
|
|
134
|
+
//#region src/issue/constants.d.ts
|
|
135
|
+
/**
|
|
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.
|
|
140
|
+
*
|
|
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.
|
|
148
|
+
*
|
|
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:
|
|
153
|
+
*
|
|
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.).
|
|
166
|
+
*/
|
|
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];
|
|
211
|
+
/**
|
|
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:
|
|
225
|
+
*
|
|
226
|
+
* ```ts
|
|
227
|
+
* // In a third-party package or app:
|
|
228
|
+
* declare module 'validup' {
|
|
229
|
+
* interface IssueDataByCode {
|
|
230
|
+
* email_taken: { existingUserId: string };
|
|
231
|
+
* }
|
|
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
|
+
* });
|
|
240
|
+
* ```
|
|
241
|
+
*
|
|
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.
|
|
245
|
+
*/
|
|
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
|
+
};
|
|
276
|
+
}
|
|
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>;
|
|
289
|
+
//#endregion
|
|
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;
|
|
302
|
+
interface IssueBase {
|
|
303
|
+
/**
|
|
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.
|
|
337
|
+
*/
|
|
338
|
+
meta?: Record<string, unknown>;
|
|
339
|
+
/**
|
|
340
|
+
* Issue path.
|
|
341
|
+
*/
|
|
342
|
+
path: PropertyKey[];
|
|
343
|
+
/**
|
|
344
|
+
* Default-rendered message (eager, English). Use `formatIssue` with a
|
|
345
|
+
* `code → template` map for localized re-rendering at the consumer side.
|
|
346
|
+
*/
|
|
347
|
+
message: string;
|
|
348
|
+
/**
|
|
349
|
+
* Structured parameters used by the default `message` rendering and
|
|
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.
|
|
353
|
+
*/
|
|
354
|
+
data?: Record<string, unknown>;
|
|
355
|
+
}
|
|
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 {
|
|
363
|
+
/**
|
|
364
|
+
* Issue Type
|
|
365
|
+
*/
|
|
366
|
+
type: 'item';
|
|
367
|
+
/**
|
|
368
|
+
* Received input value.
|
|
369
|
+
*/
|
|
370
|
+
received?: unknown;
|
|
371
|
+
/**
|
|
372
|
+
* Expected input value.
|
|
373
|
+
*/
|
|
374
|
+
expected?: unknown;
|
|
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;
|
|
433
|
+
interface IssueGroup extends IssueBase {
|
|
434
|
+
/**
|
|
435
|
+
* Code identifying the issue. See `IssueItem.code` for the
|
|
436
|
+
* vocabulary + ad-hoc widening conventions.
|
|
437
|
+
*/
|
|
438
|
+
code?: IssueCode | (string & {});
|
|
439
|
+
/**
|
|
440
|
+
* Issue Type
|
|
441
|
+
*/
|
|
442
|
+
type: 'group';
|
|
443
|
+
/**
|
|
444
|
+
* Child issues
|
|
445
|
+
*/
|
|
446
|
+
issues: Issue[];
|
|
447
|
+
}
|
|
448
|
+
type Issue = IssueGroup | IssueItem;
|
|
449
|
+
//#endregion
|
|
450
|
+
//#region src/issue/check.d.ts
|
|
451
|
+
declare function isIssueItem(input: unknown): input is IssueItem;
|
|
452
|
+
declare function isIssueGroup(input: unknown): input is IssueGroup;
|
|
453
|
+
declare function isIssue(input: unknown): input is Issue;
|
|
454
|
+
//#endregion
|
|
455
|
+
//#region src/issue/define.d.ts
|
|
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>;
|
|
497
|
+
declare function defineIssueGroup(data: Omit<IssueGroup, 'type'>): IssueGroup;
|
|
498
|
+
//#endregion
|
|
499
|
+
//#region src/issue/flatten.d.ts
|
|
500
|
+
declare function flattenIssueItems(issues: Issue[]): IssueItem[];
|
|
501
|
+
declare function flattenIssueGroups(issues: Issue[]): IssueGroup[];
|
|
502
|
+
//#endregion
|
|
503
|
+
//#region src/issue/format.d.ts
|
|
504
|
+
/**
|
|
505
|
+
* Map of issue `code` → message template. Templates use `{name}` placeholders
|
|
506
|
+
* — the same syntax `@ebec/core`'s `interpolate` understands — and are
|
|
507
|
+
* resolved against `Issue.data` at format time.
|
|
508
|
+
*
|
|
509
|
+
* ```ts
|
|
510
|
+
* const de: IssueMessageTemplates = {
|
|
511
|
+
* value_invalid: 'Wert ist ungültig',
|
|
512
|
+
* one_of_failed: 'Keine der Varianten war erfolgreich',
|
|
513
|
+
* };
|
|
514
|
+
* ```
|
|
515
|
+
*/
|
|
516
|
+
type IssueMessageTemplates = Partial<Record<IssueCode, string>> & Record<string, string>;
|
|
517
|
+
/**
|
|
518
|
+
* Render an issue's user-facing message.
|
|
519
|
+
*
|
|
520
|
+
* Resolution order:
|
|
521
|
+
* 1. If `templates[code]` exists, return `interpolate(template, issue.data)`.
|
|
522
|
+
* 2. Else return `issue.message` (the default English rendering set at
|
|
523
|
+
* construction time).
|
|
524
|
+
* 3. Else return `fallback`.
|
|
525
|
+
*/
|
|
526
|
+
declare function formatIssue(issue: Issue, templates?: IssueMessageTemplates, fallback?: string): string;
|
|
527
|
+
//#endregion
|
|
528
|
+
//#region src/error/base.d.ts
|
|
529
|
+
declare class ValidupError extends BaseError {
|
|
530
|
+
readonly issues: Issue[];
|
|
531
|
+
constructor(issues?: Issue[]);
|
|
532
|
+
toJSON(): ReturnType<BaseError['toJSON']> & {
|
|
533
|
+
issues: Issue[];
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
//#endregion
|
|
537
|
+
//#region src/error/check.d.ts
|
|
538
|
+
declare function isError(input: unknown): input is Error & {
|
|
539
|
+
[key: string]: any;
|
|
540
|
+
};
|
|
541
|
+
declare function isValidupError(error: unknown): error is ValidupError;
|
|
542
|
+
//#endregion
|
|
543
|
+
//#region src/types.d.ts
|
|
544
|
+
type ObjectLiteral = Record<string | number, any>;
|
|
545
|
+
//#endregion
|
|
546
|
+
//#region src/validator/types.d.ts
|
|
547
|
+
type ValidatorContext<C = unknown> = {
|
|
548
|
+
/**
|
|
549
|
+
* The expanded mount path in the current container.
|
|
550
|
+
*/
|
|
551
|
+
key: string;
|
|
552
|
+
/**
|
|
553
|
+
* The global mount path of the parent container.
|
|
554
|
+
*/
|
|
555
|
+
path: PropertyKey[];
|
|
556
|
+
/**
|
|
557
|
+
* The actual value, which should be validated.
|
|
558
|
+
*/
|
|
559
|
+
value: unknown;
|
|
560
|
+
/**
|
|
561
|
+
* The input data of the current container.
|
|
562
|
+
*/
|
|
563
|
+
data: Record<string, any>;
|
|
564
|
+
/**
|
|
565
|
+
* The group name for which the validator is executed.
|
|
566
|
+
*/
|
|
567
|
+
group?: string;
|
|
568
|
+
/**
|
|
569
|
+
* Caller-supplied context, forwarded unchanged through nested containers.
|
|
570
|
+
* Useful for request-scoped data (current user, locale, DB connection,
|
|
571
|
+
* request id) that validators need but isn't part of the validated value.
|
|
572
|
+
*/
|
|
573
|
+
context: C;
|
|
574
|
+
/**
|
|
575
|
+
* Cancellation signal forwarded from `ContainerRunOptions.signal`.
|
|
576
|
+
* Async validators (DB lookups, HTTP fetches) should pass it through to
|
|
577
|
+
* cancel I/O when the run is aborted. The container itself checks
|
|
578
|
+
* `signal.aborted` between mounts and rethrows the signal's `reason`.
|
|
579
|
+
*/
|
|
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;
|
|
595
|
+
};
|
|
596
|
+
/**
|
|
597
|
+
* A `Validator` either returns the (optionally transformed) value or throws.
|
|
598
|
+
*
|
|
599
|
+
* @typeParam C - Caller-supplied context type, propagated from the parent
|
|
600
|
+
* `Container<T, C>` and surfaced on `ValidatorContext.context`.
|
|
601
|
+
* @typeParam Out - The validator's resolved output type. Defaults to `unknown`,
|
|
602
|
+
* so call sites that don't care about typed output compile
|
|
603
|
+
* unchanged. The builder API (`defineSchema`) uses this
|
|
604
|
+
* second generic to accumulate per-field types.
|
|
605
|
+
*/
|
|
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>;
|
|
675
|
+
//#endregion
|
|
676
|
+
//#region src/container/types.d.ts
|
|
677
|
+
type ContainerOptions<T> = {
|
|
678
|
+
/**
|
|
679
|
+
* Only one of the mounted container/validators must succeed.
|
|
680
|
+
*/
|
|
681
|
+
oneOf?: boolean;
|
|
682
|
+
/**
|
|
683
|
+
* Limit mounted paths on execution.
|
|
684
|
+
* By default, all mounted containers/validators will
|
|
685
|
+
* be considered for execution.
|
|
686
|
+
*/
|
|
687
|
+
pathsToInclude?: Path<T>[];
|
|
688
|
+
/**
|
|
689
|
+
* Exclude mounted paths on execution.
|
|
690
|
+
* By default, all mounted containers/validators will
|
|
691
|
+
* be considered for execution.
|
|
692
|
+
*/
|
|
693
|
+
pathsToExclude?: Path<T>[];
|
|
694
|
+
};
|
|
695
|
+
type ContainerRunOptions<T extends Record<string, any> = Record<string, any>, C = unknown> = {
|
|
696
|
+
/**
|
|
697
|
+
* Default values for the container output.
|
|
698
|
+
*/
|
|
699
|
+
defaults?: { [Key in Path<T>]: any };
|
|
700
|
+
/**
|
|
701
|
+
* Group to execute.
|
|
702
|
+
*/
|
|
703
|
+
group?: string;
|
|
704
|
+
/**
|
|
705
|
+
* Output flat object?
|
|
706
|
+
*/
|
|
707
|
+
flat?: boolean;
|
|
708
|
+
/**
|
|
709
|
+
* Passed path from the parent container.
|
|
710
|
+
*/
|
|
711
|
+
path?: PropertyKey[];
|
|
712
|
+
/**
|
|
713
|
+
* Limit mounted paths on execution.
|
|
714
|
+
* By default, all mounted containers/validators will
|
|
715
|
+
* be considered for execution.
|
|
716
|
+
*/
|
|
717
|
+
pathsToInclude?: Path<T>[];
|
|
718
|
+
/**
|
|
719
|
+
* Exclude mounted paths on execution.
|
|
720
|
+
* By default, all mounted containers/validators will
|
|
721
|
+
* be considered for execution.
|
|
722
|
+
*/
|
|
723
|
+
pathsToExclude?: Path<T>[];
|
|
724
|
+
/**
|
|
725
|
+
* Caller-supplied context surfaced on `ValidatorContext.context`. Forwarded
|
|
726
|
+
* unchanged into nested container `run()` calls so the entire tree shares
|
|
727
|
+
* the same value.
|
|
728
|
+
*/
|
|
729
|
+
context?: C;
|
|
730
|
+
/**
|
|
731
|
+
* Cancellation signal. The container checks `signal.aborted` between
|
|
732
|
+
* mounts and rethrows `signal.reason` when set. Forwarded unchanged into
|
|
733
|
+
* nested `run()` calls and surfaced on `ValidatorContext.signal` so async
|
|
734
|
+
* validators can pass it into `fetch`, DB drivers, etc.
|
|
735
|
+
*/
|
|
736
|
+
signal?: AbortSignal;
|
|
737
|
+
/**
|
|
738
|
+
* Run mounted validators / nested containers concurrently rather than
|
|
739
|
+
* sequentially. Useful when several independent fields hit slow async
|
|
740
|
+
* resources (DB lookups, HTTP calls). Forwarded unchanged into nested
|
|
741
|
+
* `run()` calls.
|
|
742
|
+
*
|
|
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.
|
|
754
|
+
*/
|
|
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;
|
|
771
|
+
};
|
|
772
|
+
type MountOptions = {
|
|
773
|
+
/**
|
|
774
|
+
* Group(s) to execute.
|
|
775
|
+
*/
|
|
776
|
+
group?: string | string[];
|
|
777
|
+
/**
|
|
778
|
+
* Specify if an optional value is also acceptable for the mount key.
|
|
779
|
+
* An optional value won't be passed to the underlying container/validator.
|
|
780
|
+
*
|
|
781
|
+
* Pass a predicate `(value) => boolean` for fine-grained control beyond
|
|
782
|
+
* what `optionalValue` covers (e.g. "treat empty string as missing but
|
|
783
|
+
* keep `0`"). When a predicate is provided, `optionalValue` is ignored.
|
|
784
|
+
*
|
|
785
|
+
* default: false
|
|
786
|
+
*/
|
|
787
|
+
optional?: boolean | ((value: unknown) => boolean);
|
|
788
|
+
/**
|
|
789
|
+
* Which values are considered optional.
|
|
790
|
+
* An optional value won't be passed to the underlying container/validator.
|
|
791
|
+
*
|
|
792
|
+
* default: 'undefined'
|
|
793
|
+
*/
|
|
794
|
+
optionalValue?: `${OptionalValue}`;
|
|
795
|
+
/**
|
|
796
|
+
* Include optional value as property in output.
|
|
797
|
+
*
|
|
798
|
+
* default: false
|
|
799
|
+
*/
|
|
800
|
+
optionalInclude?: boolean;
|
|
801
|
+
};
|
|
802
|
+
type ResultSuccess<T> = {
|
|
803
|
+
success: true;
|
|
804
|
+
data: T;
|
|
805
|
+
error?: never;
|
|
806
|
+
};
|
|
807
|
+
type ResultFailure = {
|
|
808
|
+
success: false;
|
|
809
|
+
data?: never;
|
|
810
|
+
error: ValidupError;
|
|
811
|
+
};
|
|
812
|
+
type Result<T extends ObjectLiteral = ObjectLiteral> = ResultSuccess<T> | ResultFailure;
|
|
813
|
+
interface IContainer<T extends ObjectLiteral = ObjectLiteral, C = unknown> {
|
|
814
|
+
/**
|
|
815
|
+
* Run the container against `input`. Throws `ValidupError` on validation
|
|
816
|
+
* failure; rethrows `signal.reason` when the run is aborted via
|
|
817
|
+
* `options.signal`.
|
|
818
|
+
*/
|
|
819
|
+
run(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Promise<T>;
|
|
820
|
+
/**
|
|
821
|
+
* Run the container against `input` and return a discriminated `Result`
|
|
822
|
+
* instead of throwing on validation failure.
|
|
823
|
+
*
|
|
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.
|
|
832
|
+
*/
|
|
833
|
+
safeRun(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Promise<Result<T>>;
|
|
834
|
+
/**
|
|
835
|
+
* Synchronous variant of `run()`. Optional — implementations can omit
|
|
836
|
+
* this when their validators are inherently async. The default
|
|
837
|
+
* `Container` provides it; nested containers without it cannot be
|
|
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.
|
|
844
|
+
*/
|
|
845
|
+
runSync?(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): T;
|
|
846
|
+
/**
|
|
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.
|
|
852
|
+
*/
|
|
853
|
+
safeRunSync?(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Result<T>;
|
|
854
|
+
}
|
|
855
|
+
type BaseMount = {
|
|
856
|
+
options: MountOptions;
|
|
857
|
+
/**
|
|
858
|
+
* Mount path expressed in dot/bracket notation (e.g. `foo.bar`,
|
|
859
|
+
* `items[0].name`). Path segments are joined and split on `.` throughout
|
|
860
|
+
* the runtime, so keys that contain a *literal* dot (e.g. an object keyed
|
|
861
|
+
* `data['user.email']`) are not addressable as a single mount segment and
|
|
862
|
+
* will produce ambiguous flat output when merged. Use bracketed/array
|
|
863
|
+
* shapes instead for inputs that contain literal-dot keys.
|
|
864
|
+
*/
|
|
865
|
+
path?: string;
|
|
866
|
+
};
|
|
867
|
+
type ContainerMount = BaseMount & {
|
|
868
|
+
type: 'container';
|
|
869
|
+
data: IContainer<any, any>;
|
|
870
|
+
};
|
|
871
|
+
type ValidatorMount<C = unknown> = BaseMount & {
|
|
872
|
+
type: 'validator';
|
|
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;
|
|
889
|
+
};
|
|
890
|
+
type Mount<C = unknown> = ContainerMount | ValidatorMount<C>;
|
|
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
|
|
1188
|
+
//#region src/container/check.d.ts
|
|
1189
|
+
declare function isContainer(input: unknown): input is IContainer;
|
|
1190
|
+
//#endregion
|
|
1191
|
+
//#region src/container/module.d.ts
|
|
1192
|
+
declare class Container<T extends Record<string, any> = Record<string, any>, C = unknown> implements IContainer<T, C> {
|
|
1193
|
+
protected options: ContainerOptions<T>;
|
|
1194
|
+
protected items: Mount<C>[];
|
|
1195
|
+
constructor(options?: ContainerOptions<T>);
|
|
1196
|
+
mount(container: IContainer<any, any>): void;
|
|
1197
|
+
mount(options: MountOptions, container: IContainer<any, any>): 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;
|
|
1200
|
+
/**
|
|
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.
|
|
1222
|
+
*
|
|
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.
|
|
1227
|
+
*/
|
|
1228
|
+
run(data?: Record<string, any>, options?: ContainerRunOptions<T, C>): Promise<T>;
|
|
1229
|
+
/**
|
|
1230
|
+
* Parallel-execution variant of `run()`. All mounts kick off their
|
|
1231
|
+
* promises eagerly and the results are merged after `Promise.allSettled`.
|
|
1232
|
+
* See `ContainerRunOptions.parallel` for the trade-off note.
|
|
1233
|
+
*/
|
|
1234
|
+
private runParallel;
|
|
1235
|
+
safeRun(input?: Record<string, any>, options?: ContainerRunOptions<T, C>): Promise<Result<T>>;
|
|
1236
|
+
/**
|
|
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.
|
|
1251
|
+
*
|
|
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.
|
|
1264
|
+
*/
|
|
1265
|
+
runSync(data?: Record<string, any>, options?: ContainerRunOptions<T, C>): T;
|
|
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;
|
|
1297
|
+
private resolveContainerFilters;
|
|
1298
|
+
/**
|
|
1299
|
+
* Prepend `keyParts` to a child issue's `path` and — when the child is
|
|
1300
|
+
* an `IssueGroup` — recurse into its nested issues so every leaf carries
|
|
1301
|
+
* the parent prefix. Without recursion, a child container that already
|
|
1302
|
+
* wrapped its own multi-issue mount in a group (or a `oneOf` child) would
|
|
1303
|
+
* surface inner items with paths missing the parent segment, breaking
|
|
1304
|
+
* downstream consumers that rely on `flattenIssueItems` for per-field
|
|
1305
|
+
* lookup (e.g. `@validup/vue`).
|
|
1306
|
+
*/
|
|
1307
|
+
private prefixIssuePath;
|
|
1308
|
+
/**
|
|
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
|
|
1312
|
+
* the run was aborted (signal-aware validators) so abort errors are not
|
|
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.
|
|
1343
|
+
*/
|
|
1344
|
+
private wrapBranchForOneOf;
|
|
1345
|
+
/**
|
|
1346
|
+
* Apply post-loop semantics: oneOf aggregation, error throw, defaults
|
|
1347
|
+
* fill, and flat-vs-nested output expansion.
|
|
1348
|
+
*/
|
|
1349
|
+
private finalizeOutput;
|
|
1350
|
+
private wrapSafeRunError;
|
|
1351
|
+
private isItemGroupIncluded;
|
|
1352
|
+
/**
|
|
1353
|
+
* Join flat-output keys with `.` separators, preserving any pre-existing
|
|
1354
|
+
* leading dot on the right-hand side. Note: keys containing a *literal*
|
|
1355
|
+
* dot collide with the dotted-path syntax used for nested-output
|
|
1356
|
+
* expansion (see `setPathValue` in `pathtrace`) and will produce
|
|
1357
|
+
* ambiguous output when re-expanded — avoid mounting/returning such keys.
|
|
1358
|
+
*/
|
|
1359
|
+
private mergePaths;
|
|
1360
|
+
protected initialize(): void;
|
|
1361
|
+
}
|
|
1362
|
+
//#endregion
|
|
1363
|
+
//#region src/builder/types.d.ts
|
|
1364
|
+
/**
|
|
1365
|
+
* Cosmetic helper — flattens an intersection so editors render
|
|
1366
|
+
* `{ foo: string; bar: number }` instead of `{ foo: string } & { bar: number }`.
|
|
1367
|
+
*/
|
|
1368
|
+
type Spread<T> = { [K in keyof T]: T[K] };
|
|
1369
|
+
/**
|
|
1370
|
+
* Anything that can be mounted under a key on a `Builder`: a leaf validator,
|
|
1371
|
+
* a nested builder (auto-`.build()`-ed), or an existing `Container`.
|
|
1372
|
+
*/
|
|
1373
|
+
type MountTarget<C> = Validator<C, any> | IBuilder<any, C> | IContainer<any, C>;
|
|
1374
|
+
/**
|
|
1375
|
+
* `true` when `O` declares `optional: true` or `optional: (value) => …`. The
|
|
1376
|
+
* builder's `mount(key, options, target)` overload uses this to widen the
|
|
1377
|
+
* accumulated key to `{ K?: V }`. Plain `boolean`-typed options stay required —
|
|
1378
|
+
* the `const` modifier on the `mount` generic preserves literal `true` from
|
|
1379
|
+
* inline option objects, which is the common case.
|
|
1380
|
+
*/
|
|
1381
|
+
type IsOptional<O> = O extends {
|
|
1382
|
+
optional: true;
|
|
1383
|
+
} ? true : O extends {
|
|
1384
|
+
optional: (value: any) => any;
|
|
1385
|
+
} ? true : false;
|
|
1386
|
+
/**
|
|
1387
|
+
* Resolved field shape produced by `mount(key, target, …)`.
|
|
1388
|
+
*
|
|
1389
|
+
* Builder / Container targets → `{ [K]: U }` where `U` is the child's shape.
|
|
1390
|
+
* Validator targets → `{ [K]: Awaited<Out> }` based on the validator's return
|
|
1391
|
+
* type. In all three cases, `IsOptional<O>` widens the property to
|
|
1392
|
+
* `{ [K]?: … }` when `options.optional` is the literal `true` or a predicate —
|
|
1393
|
+
* matching the runtime behavior that an optional mount may be skipped, leaving
|
|
1394
|
+
* the key absent from the output.
|
|
1395
|
+
*/
|
|
1396
|
+
type Mounted<K extends string, V, O> = V extends IBuilder<infer U, any> ? IsOptional<O> extends true ? { [P in K]?: U } : { [P in K]: U } : V extends IContainer<infer U, any> ? IsOptional<O> extends true ? { [P in K]?: U } : { [P in K]: U } : V extends Validator<any, infer Out> ? IsOptional<O> extends true ? { [P in K]?: Awaited<Out> } : { [P in K]: Awaited<Out> } : never;
|
|
1397
|
+
/**
|
|
1398
|
+
* Compile-time-typed schema builder. `mount(...)` accumulates the resolved
|
|
1399
|
+
* field type into `T`, so `build()` returns a `Container<T, C>` whose static
|
|
1400
|
+
* return type from `run()` reflects exactly what was registered.
|
|
1401
|
+
*
|
|
1402
|
+
* Builders are immutable: every method returns a new `Builder` so chains
|
|
1403
|
+
* may fork without leaking state. The shape of `mount` mirrors
|
|
1404
|
+
* `Container.mount`'s keyed forms — `(key, target)` and
|
|
1405
|
+
* `(key, options, target)` — so transferring patterns between the imperative
|
|
1406
|
+
* and builder APIs is straightforward.
|
|
1407
|
+
*/
|
|
1408
|
+
interface IBuilder<T extends Record<string, any>, C = unknown> {
|
|
1409
|
+
/**
|
|
1410
|
+
* Mount a leaf validator, nested builder, or existing container at `key`.
|
|
1411
|
+
* The accumulated shape gains the resolved type of `target`. Re-mounting
|
|
1412
|
+
* the same key overrides the previous registration's type (matching the
|
|
1413
|
+
* runtime "last write wins" behavior of `Container.mount`).
|
|
1414
|
+
*/
|
|
1415
|
+
mount<K extends string, V extends MountTarget<C>>(key: K, target: V): IBuilder<Spread<Omit<T, K> & Mounted<K, V, undefined>>, C>;
|
|
1416
|
+
/**
|
|
1417
|
+
* Mount with `MountOptions`. When `options.optional` is `true` (or a
|
|
1418
|
+
* predicate function) the accumulated key widens to `{ K?: V }`.
|
|
1419
|
+
*/
|
|
1420
|
+
mount<K extends string, const O extends MountOptions, V extends MountTarget<C>>(key: K, options: O, target: V): IBuilder<Spread<Omit<T, K> & Mounted<K, V, O>>, C>;
|
|
1421
|
+
/** Mark the resulting container as `oneOf` (only one branch must succeed). */
|
|
1422
|
+
oneOf(): IBuilder<T, C>;
|
|
1423
|
+
/** Restrict the resulting container's `pathsToInclude`. */
|
|
1424
|
+
pathsToInclude(...paths: (keyof T & string)[]): IBuilder<T, C>;
|
|
1425
|
+
/** Restrict the resulting container's `pathsToExclude`. */
|
|
1426
|
+
pathsToExclude(...paths: (keyof T & string)[]): IBuilder<T, C>;
|
|
1427
|
+
/** Materialize a `Container<T, C>` and replay every accumulated mount. */
|
|
1428
|
+
build(): Container<T, C>;
|
|
1429
|
+
}
|
|
1430
|
+
//#endregion
|
|
1431
|
+
//#region src/builder/module.d.ts
|
|
1432
|
+
type ValidatorStep<C> = {
|
|
1433
|
+
kind: 'validator';
|
|
1434
|
+
key: string;
|
|
1435
|
+
validator: Validator<C>;
|
|
1436
|
+
options: MountOptions;
|
|
1437
|
+
};
|
|
1438
|
+
type NestStep<C> = {
|
|
1439
|
+
kind: 'nest';
|
|
1440
|
+
key: string;
|
|
1441
|
+
child: IContainer<any, C>;
|
|
1442
|
+
options: MountOptions;
|
|
1443
|
+
};
|
|
1444
|
+
type Step<C> = ValidatorStep<C> | NestStep<C>;
|
|
1445
|
+
declare class Builder<T extends Record<string, any>, C> implements IBuilder<T, C> {
|
|
1446
|
+
private readonly options;
|
|
1447
|
+
private readonly steps;
|
|
1448
|
+
constructor(options: ContainerOptions<any>, steps: ReadonlyArray<Step<C>>);
|
|
1449
|
+
mount(key: string, ...rest: unknown[]): IBuilder<any, C>;
|
|
1450
|
+
oneOf(): IBuilder<T, C>;
|
|
1451
|
+
pathsToInclude(...paths: (keyof T & string)[]): IBuilder<T, C>;
|
|
1452
|
+
pathsToExclude(...paths: (keyof T & string)[]): IBuilder<T, C>;
|
|
1453
|
+
build(): Container<T, C>;
|
|
1454
|
+
}
|
|
1455
|
+
/**
|
|
1456
|
+
* Entry point for the compile-time-typed schema builder. The accumulator
|
|
1457
|
+
* starts at `{}` and grows as `.mount(...)` calls are chained;
|
|
1458
|
+
* `.build()` returns a `Container<T, C>` whose `run()` reflects the
|
|
1459
|
+
* accumulated shape.
|
|
1460
|
+
*
|
|
1461
|
+
* Pass the context type as the generic parameter to flow it through nested
|
|
1462
|
+
* builders and validator factories: `defineSchema<MyContext>()`.
|
|
1463
|
+
*/
|
|
1464
|
+
declare function defineSchema<C = unknown>(): IBuilder<{}, C>;
|
|
1465
|
+
//#endregion
|
|
1466
|
+
//#region src/utils/has-own-property.d.ts
|
|
1467
|
+
declare function hasOwnProperty<X extends {}, Y extends PropertyKey>(obj: X, prop: Y): obj is X & Record<Y, unknown>;
|
|
1468
|
+
//#endregion
|
|
1469
|
+
//#region src/utils/object.d.ts
|
|
1470
|
+
declare function isObject(input: unknown): input is Record<string, any>;
|
|
1471
|
+
//#endregion
|
|
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 };
|
|
1473
|
+
//# sourceMappingURL=index.d.mts.map
|