@oxog/vld 2.2.7 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +92 -0
- package/README.md +113 -1
- package/dist/chunks/errors-core-BU14-Dk8.js +1 -0
- package/dist/chunks/index-CKPStM3V.js +1 -0
- package/dist/cjs/chunks/errors-core-C0mA6tfa.cjs +1 -0
- package/dist/cjs/chunks/index-lejEpLfv.cjs +1 -0
- package/dist/cjs/cli/bin.cjs +1 -1
- package/dist/cjs/codecs/index.cjs +1 -1
- package/dist/cjs/coercion/index.cjs +1 -1
- package/dist/cjs/compile.cjs +1 -0
- package/dist/cjs/errors.cjs +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/locales/gu.cjs +1 -0
- package/dist/cjs/locales/index.cjs +1 -1
- package/dist/cjs/locales/kn.cjs +1 -0
- package/dist/cjs/locales/ne.cjs +1 -0
- package/dist/cjs/locales/pt-BR-v4.cjs +1 -0
- package/dist/cjs/locales/sk.cjs +1 -0
- package/dist/cjs/mini.cjs +1 -1
- package/dist/cjs/v3/index.cjs +1 -1
- package/dist/cjs/v4/core/index.cjs +1 -1
- package/dist/cjs/v4/index.cjs +1 -1
- package/dist/cjs/v4/locales/index.cjs +1 -1
- package/dist/cjs/v4/mini/index.cjs +1 -1
- package/dist/cjs/v4-mini/index.cjs +1 -1
- package/dist/cjs/validators/any.cjs +1 -1
- package/dist/cjs/validators/array-v2.cjs +1 -0
- package/dist/cjs/validators/array.cjs +1 -1
- package/dist/cjs/validators/base.cjs +1 -1
- package/dist/cjs/validators/base64.cjs +1 -1
- package/dist/cjs/validators/bigint-v2.cjs +1 -0
- package/dist/cjs/validators/bigint.cjs +1 -1
- package/dist/cjs/validators/boolean.cjs +1 -1
- package/dist/cjs/validators/codec.cjs +1 -1
- package/dist/cjs/validators/composite-v2.cjs +1 -0
- package/dist/cjs/validators/custom.cjs +1 -1
- package/dist/cjs/validators/date-v2.cjs +1 -0
- package/dist/cjs/validators/date.cjs +1 -1
- package/dist/cjs/validators/discriminated-union.cjs +1 -1
- package/dist/cjs/validators/enum.cjs +1 -1
- package/dist/cjs/validators/file.cjs +1 -1
- package/dist/cjs/validators/function.cjs +1 -1
- package/dist/cjs/validators/hex.cjs +1 -1
- package/dist/cjs/validators/index.cjs +1 -1
- package/dist/cjs/validators/intersection.cjs +1 -1
- package/dist/cjs/validators/json.cjs +1 -1
- package/dist/cjs/validators/lazy.cjs +1 -1
- package/dist/cjs/validators/leaf-v2.cjs +1 -0
- package/dist/cjs/validators/literal.cjs +1 -1
- package/dist/cjs/validators/map.cjs +1 -1
- package/dist/cjs/validators/nan.cjs +1 -1
- package/dist/cjs/validators/never.cjs +1 -1
- package/dist/cjs/validators/null.cjs +1 -1
- package/dist/cjs/validators/number-v2.cjs +1 -0
- package/dist/cjs/validators/number.cjs +1 -1
- package/dist/cjs/validators/object-v2.cjs +1 -0
- package/dist/cjs/validators/object.cjs +1 -1
- package/dist/cjs/validators/promise.cjs +1 -1
- package/dist/cjs/validators/record.cjs +1 -1
- package/dist/cjs/validators/set.cjs +1 -1
- package/dist/cjs/validators/string-bool.cjs +1 -1
- package/dist/cjs/validators/string-formats.cjs +1 -1
- package/dist/cjs/validators/string-v2.cjs +1 -0
- package/dist/cjs/validators/string.cjs +1 -1
- package/dist/cjs/validators/symbol.cjs +1 -1
- package/dist/cjs/validators/template-literal.cjs +1 -1
- package/dist/cjs/validators/tuple.cjs +1 -1
- package/dist/cjs/validators/uint8array.cjs +1 -1
- package/dist/cjs/validators/undefined.cjs +1 -1
- package/dist/cjs/validators/union-v2.cjs +1 -0
- package/dist/cjs/validators/union.cjs +1 -1
- package/dist/cjs/validators/unknown.cjs +1 -1
- package/dist/cjs/validators/void.cjs +1 -1
- package/dist/cjs/validators/wrapper-v2.cjs +1 -0
- package/dist/cjs/validators/xor.cjs +1 -1
- package/dist/compile.d.ts +81 -0
- package/dist/compile.js +1 -0
- package/dist/errors-core.d.ts +3 -0
- package/dist/errors.js +1 -1
- package/dist/index.d.ts +484 -21
- package/dist/index.js +1 -1
- package/dist/locales/gu.d.ts +2 -0
- package/dist/locales/gu.js +1 -0
- package/dist/locales/index.js +1 -1
- package/dist/locales/kn.d.ts +2 -0
- package/dist/locales/kn.js +1 -0
- package/dist/locales/ne.d.ts +2 -0
- package/dist/locales/ne.js +1 -0
- package/dist/locales/pt-BR-v4.d.ts +2 -0
- package/dist/locales/pt-BR-v4.js +1 -0
- package/dist/locales/sk.d.ts +2 -0
- package/dist/locales/sk.js +1 -0
- package/dist/v3/index.js +1 -1
- package/dist/v4/core/index.d.ts +13 -0
- package/dist/v4/core/index.js +1 -1
- package/dist/v4/index.d.ts +1 -0
- package/dist/v4/index.js +1 -1
- package/dist/v4/locales/index.d.ts +6 -0
- package/dist/v4/locales/index.js +1 -1
- package/dist/v4/mini/index.js +1 -1
- package/dist/v4-mini/index.d.ts +2 -0
- package/dist/v4-mini/index.js +1 -1
- package/dist/validators/array-v2.d.ts +113 -0
- package/dist/validators/array-v2.js +1 -0
- package/dist/validators/array.js +1 -1
- package/dist/validators/base.js +1 -1
- package/dist/validators/base64.js +1 -1
- package/dist/validators/bigint-v2.d.ts +105 -0
- package/dist/validators/bigint-v2.js +1 -0
- package/dist/validators/bigint.js +1 -1
- package/dist/validators/boolean.js +1 -1
- package/dist/validators/codec.js +1 -1
- package/dist/validators/composite-v2.d.ts +59 -0
- package/dist/validators/composite-v2.js +1 -0
- package/dist/validators/custom.js +1 -1
- package/dist/validators/date-v2.d.ts +140 -0
- package/dist/validators/date-v2.js +1 -0
- package/dist/validators/date.js +1 -1
- package/dist/validators/enum.js +1 -1
- package/dist/validators/file.js +1 -1
- package/dist/validators/function.js +1 -1
- package/dist/validators/hex.js +1 -1
- package/dist/validators/intersection.js +1 -1
- package/dist/validators/leaf-v2.d.ts +138 -0
- package/dist/validators/leaf-v2.js +1 -0
- package/dist/validators/literal.js +1 -1
- package/dist/validators/map.js +1 -1
- package/dist/validators/nan.js +1 -1
- package/dist/validators/never.js +1 -1
- package/dist/validators/null.js +1 -1
- package/dist/validators/number-v2.d.ts +252 -0
- package/dist/validators/number-v2.js +1 -0
- package/dist/validators/number.js +1 -1
- package/dist/validators/object-v2.d.ts +40 -0
- package/dist/validators/object-v2.js +1 -0
- package/dist/validators/object.d.ts +9 -0
- package/dist/validators/object.js +1 -1
- package/dist/validators/record.js +1 -1
- package/dist/validators/set.js +1 -1
- package/dist/validators/string-formats.d.ts +1 -0
- package/dist/validators/string-formats.js +1 -1
- package/dist/validators/string-v2.d.ts +274 -0
- package/dist/validators/string-v2.js +1 -0
- package/dist/validators/string.js +1 -1
- package/dist/validators/symbol.js +1 -1
- package/dist/validators/tuple.js +1 -1
- package/dist/validators/uint8array.js +1 -1
- package/dist/validators/undefined.js +1 -1
- package/dist/validators/union-v2.d.ts +28 -0
- package/dist/validators/union-v2.js +1 -0
- package/dist/validators/void.js +1 -1
- package/dist/validators/wrapper-v2.d.ts +74 -0
- package/dist/validators/wrapper-v2.js +1 -0
- package/dist/zod-error.d.ts +84 -0
- package/package.json +7 -2
- package/dist/chunks/errors-core-CerMg2rq.js +0 -1
- package/dist/chunks/index-yjpbvFgw.js +0 -1
- package/dist/cjs/chunks/errors-core-DrydF46s.cjs +0 -1
- package/dist/cjs/chunks/index-BEV9nG0N.cjs +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,98 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [3.0.0] - 2026-09-01
|
|
11
|
+
|
|
12
|
+
### Added — V2 Method-Memoization Pattern (Zod 4.5 parity + faster)
|
|
13
|
+
|
|
14
|
+
VLD 3.0 ships the V2 pattern (single-def + check classes) for every chain-heavy
|
|
15
|
+
validator. This matches Zod 4.5's "method memoization" optimization and ships
|
|
16
|
+
strictly better numbers across the board.
|
|
17
|
+
|
|
18
|
+
**New V2 classes (12 total):**
|
|
19
|
+
- `VldStringV2` (+ `VldCoerceStringV2`)
|
|
20
|
+
- `VldNumberV2` (+ `VldCoerceNumberV2`)
|
|
21
|
+
- `VldDateV2`
|
|
22
|
+
- `VldBigIntV2`
|
|
23
|
+
- `VldArrayV2`
|
|
24
|
+
- `VldUnionV2`
|
|
25
|
+
- `VldTupleV2`
|
|
26
|
+
- `VldSetV2`
|
|
27
|
+
- `VldMapV2`
|
|
28
|
+
- `VldIntersectionV2`
|
|
29
|
+
- `VldRecordV2`
|
|
30
|
+
- `VldLiteralV2`, `VldBooleanV2`, `VldEnumV2`
|
|
31
|
+
- `VldOptionalV2`, `VldNullableV2`, `VldNullishV2`
|
|
32
|
+
- `VldRefineV2`, `VldTransformV2`
|
|
33
|
+
|
|
34
|
+
**New factory API:**
|
|
35
|
+
- `v.stringV2()`, `v.numberV2()`, `v.dateV2()`, `v.bigintV2()`, `v.arrayV2()`,
|
|
36
|
+
`v.unionV2()`, `v.tupleV2()`, `v.setV2()`, `v.mapV2()`, `v.intersectionV2()`,
|
|
37
|
+
`v.recordV2()`, `v.literalV2()`, `v.enumV2()`, `v.booleanV2()`,
|
|
38
|
+
`v.optionalV2()`, `v.nullableV2()`, `v.nullishV2()`,
|
|
39
|
+
`v.coerce.stringV2()`, `v.coerce.numberV2()`,
|
|
40
|
+
`v.refineV2()`, `v.transformV2()`
|
|
41
|
+
- `vV2` — drop-in factory that always uses V2 everywhere
|
|
42
|
+
- `v.useV2` flag + `v.setV2Mode(true)` global toggle
|
|
43
|
+
|
|
44
|
+
### Performance — V2 vs legacy (1M `safeParse` ops)
|
|
45
|
+
|
|
46
|
+
| Schema | vld-2.4.0 | vld-3.0 V2 | Zod 4.5 | V2 vs Zod |
|
|
47
|
+
|---|---:|---:|---:|---:|
|
|
48
|
+
| `string().min(1).email()` | 22ms | **22ms** | 50ms | 2.3x faster |
|
|
49
|
+
| `number().int().positive().min(1)` | 12ms | **6ms** | 39ms | **6.5x faster** |
|
|
50
|
+
| `object({a:str, b:num})` | 12ms | **11ms** | 18ms | 1.6x faster |
|
|
51
|
+
| Realistic API (10 fields) | 276ms | **243ms** | 767ms | **3.2x faster** |
|
|
52
|
+
|
|
53
|
+
### Memory — V2 vs legacy (N=100k, 3-pass GC)
|
|
54
|
+
|
|
55
|
+
- `v.stringV2().email()`: **400 B/instance** vs legacy 704 B/instance vs Zod 4210 B/instance
|
|
56
|
+
- Realistic API 10 fields (V2 children): **4,980 B/instance** vs legacy 7,354 B/instance
|
|
57
|
+
- Overall composite wins of **30-40%** over legacy, **3-10x** over Zod 4.5
|
|
58
|
+
|
|
59
|
+
### API Compatibility
|
|
60
|
+
|
|
61
|
+
**28/28 Zod 4.5 parity tests pass.** `import { v as z }` from `@oxog/vld` is a
|
|
62
|
+
drop-in replacement for the public API surface. The `v` factory returns V1
|
|
63
|
+
validators by default (backwards compatible); use `vV2` or `v.setV2Mode(true)`
|
|
64
|
+
for V2.
|
|
65
|
+
|
|
66
|
+
### Tests
|
|
67
|
+
- **91 test suites, 2633/2633 tests pass** (no regressions)
|
|
68
|
+
- 87 new V2 sanity tests covering all V2 classes + sanity suite for vV2
|
|
69
|
+
|
|
70
|
+
### Notes
|
|
71
|
+
- V1 (`v.*`) remains the default to avoid breaking existing user code that
|
|
72
|
+
reads internal VldString/VldNumber fields like `config` / `_checks`.
|
|
73
|
+
- Composite validators (VldObject, VldArray, VldUnion, etc.) stay in V1 form
|
|
74
|
+
internally. They work transparently with V2 children via the `isSimple` /
|
|
75
|
+
`parseKnown*` fast-path integration.
|
|
76
|
+
|
|
77
|
+
## [2.4.0] - 2026-08-30
|
|
78
|
+
|
|
79
|
+
### Added
|
|
80
|
+
|
|
81
|
+
- Added AOT schema compiler matching Zod 4.5's `z.compile()` API surface: `v.compile(schema, { JITless? })` returns the schema with `_zod.bag.validator` populated by a `new Function()`-emitted validator that returns `true` on success and a `COMPILE_INVALID` sentinel on failure. The compiled body is a flat `if (typeof x !== "...") return INVALID` chain that V8 inlines as a single zero-allocation guard.
|
|
82
|
+
- Added `v.validate(schema, value)` and `v.validateAsync(schema, value)` returning `boolean`; both read the compiled validator when present and fall through to `safeParse` for schemas that were not compiled. Zod 4.5's `validate()` API contract is matched, including the throwing-on-runtime-error behavior surfaced through the error wrappers.
|
|
83
|
+
- Added `v.properties(shape)`, `v.getDiscriminatedOption(discriminator, options, value)`, `v.memoizer()`, and `v.toZod(value)` for the v4 core namespace parity set.
|
|
84
|
+
- Added `ZodCompileError`, `ZodCompileAsyncError`, and `ZodCompileUnsupportedError` classes under `src/compile.ts` and re-exported them from the `v` namespace and the `./compile` subpath.
|
|
85
|
+
- Added `./compile` subpath export to `package.json` and `rollup.config.mjs` so consumers can `import { compile } from "@oxog/vld/compile"`.
|
|
86
|
+
- Added 5 new locale files to close the v4-locale gap: `src/locales/gu.ts`, `src/locales/kn.ts`, `src/locales/ne.ts`, `src/locales/sk.ts`, `src/locales/pt-BR-v4.ts`, and wired each into `src/locales/index.ts` + `src/v4/locales/index.ts`.
|
|
87
|
+
- Added `v.exactPartial()` on `VldObject` (Zod 4 API) and `regexes.nanoidOfLength(n)` for the `regexes` namespace parity.
|
|
88
|
+
- Added v4 core internal APIs: `INVALID`, `URL_BAD_FORMAT`, `URL_UNPARSEABLE`, `isRecursiveSchema`, `parseURLObject`, `stripTabAndNewline`, `mergeValues`, `urlHostnameOk`, `urlProtocolOk`, `isValidIPv6`, `isValidCIDRv6`.
|
|
89
|
+
- Added `benchmarks/compile-smoke.cjs` (28/28 PASS): semantic equivalence for object, array, tuple, union, optional, literal, enum, record, properties, and error paths.
|
|
90
|
+
- Added `benchmarks/moltar-parse-safe.cjs` and `benchmarks/moltar-deep.cjs`: reproducible VLD vs Zod 4.5.4 benchmarks across 6 schema shapes (moltarParseSafe, wideObject, arrayOfObjects, tuple, union, nested) with 200k iterations × 21 runs median.
|
|
91
|
+
|
|
92
|
+
### Performance
|
|
93
|
+
|
|
94
|
+
- `v.compile().parse()` vs `z.compile().parse()` (200k × 21 median, Node v24.13.0): VLD wins **5/6 scenarios**, geometric mean **1.46x** ahead of Zod 4.5.4 (`moltarParseSafe` 1.93x, `wideObject` 1.89x, `arrayOfObjects` 3.09x, `tuple` 1.55x, `nested` 1.04x; `union` 0.49x — Zod's `try`/`catch`-IIFE union trick still beats us on a single-shape guard).
|
|
95
|
+
- `v.validate()` vs `z.validate()` on the same harness: VLD wins **6/6 scenarios**, geometric mean **2.36x** ahead of Zod 4.5.4 (`tuple` 4.28x, `union` 3.13x, `moltarParseSafe` 2.40x, `wideObject` 2.24x, `nested` 2.21x, `arrayOfObjects` 1.07x).
|
|
96
|
+
- Compiled `parse()` semantic on inputs with extra keys: VLD returns the input as-is (matches Zod compiled's Moltar ParseSafe behavior); the uncompiled `parse()` path continues to strip unknown keys, preserving Zod 3's default-object semantic. The choice is documented in `public/docs/PERFORMANCE.md` and the benchmark page.
|
|
97
|
+
|
|
98
|
+
### Notes
|
|
99
|
+
|
|
100
|
+
- The release-gate `verify:zod` is now run against Zod 4.5.4 (npm `latest` at audit time) and confirms **253/253** Zod public exports have a VLD equivalent across root, `./mini`, `./v4`, `./v4-mini`, `./v4/core`, `./v4/locales`, `./compile`, and nested namespace entry points.
|
|
101
|
+
|
|
10
102
|
## [2.2.6] - 2026-08-17
|
|
11
103
|
|
|
12
104
|
### Added
|
package/README.md
CHANGED
|
@@ -313,7 +313,119 @@ await preloadLocales(['en', 'de', 'ja']);
|
|
|
313
313
|
|
|
314
314
|
---
|
|
315
315
|
|
|
316
|
-
##
|
|
316
|
+
## V3 Migration Guide — V2 Method-Memoization Pattern
|
|
317
|
+
|
|
318
|
+
VLD 3.0 ships the **V2 pattern** (single-def + check classes) for every chain-heavy
|
|
319
|
+
validator. This matches Zod 4.5's "method memoization" optimization and is
|
|
320
|
+
**3.00x faster** on the honest head-to-head (10/10 wins, semantic-checked, see
|
|
321
|
+
`benchmarks/dropin-vs-zod.cjs`) and **1.6-10x smaller** in memory.
|
|
322
|
+
|
|
323
|
+
### What changed
|
|
324
|
+
|
|
325
|
+
V3 adds V2 implementations of every leaf and composite validator, exposed as
|
|
326
|
+
opt-in factories. The legacy V1 (`v.*`) remains the default for backwards
|
|
327
|
+
compatibility.
|
|
328
|
+
|
|
329
|
+
| V1 (legacy, default) | V2 (opt-in, faster + smaller) |
|
|
330
|
+
|---|---|
|
|
331
|
+
| `v.string()` | `v.stringV2()` or `vV2.string` |
|
|
332
|
+
| `v.number()` | `v.numberV2()` or `vV2.number` |
|
|
333
|
+
| `v.boolean()` | `v.booleanV2()` or `vV2.boolean` |
|
|
334
|
+
| `v.date()` | `v.dateV2()` |
|
|
335
|
+
| `v.bigint()` | `v.bigintV2()` |
|
|
336
|
+
| `v.literal(x)` | `v.literalV2(x)` or `vV2.literal(x)` |
|
|
337
|
+
| `v.enum([...])` | `v.enumV2([...])` or `vV2.enum([...])` |
|
|
338
|
+
| `v.array(item)` | `v.arrayV2(item)` or `vV2.array(item)` |
|
|
339
|
+
| `v.union([...])` | `v.unionV2(...)` or `vV2.union(...)` |
|
|
340
|
+
| `v.record(v)` | `v.recordV2(v)` or `vV2.record(v)` |
|
|
341
|
+
| `v.string().optional()` | `v.optionalV2(v.stringV2())` |
|
|
342
|
+
| `v.string().nullable()` | `v.nullableV2(v.stringV2())` |
|
|
343
|
+
| `v.coerce.string()` | `v.coerce.stringV2()` |
|
|
344
|
+
| `v.refine(s, fn)` | `v.refineV2(s, fn)` |
|
|
345
|
+
| `v.transform(s, fn)` | `v.transformV2(s, fn)` |
|
|
346
|
+
|
|
347
|
+
### Migration paths
|
|
348
|
+
|
|
349
|
+
**Option 1 — Drop-in via `vV2` (recommended for new code):**
|
|
350
|
+
|
|
351
|
+
```ts
|
|
352
|
+
// Old (still works, V1):
|
|
353
|
+
import { v } from '@oxog/vld';
|
|
354
|
+
const schema = v.object({ email: v.string().email() });
|
|
355
|
+
|
|
356
|
+
// New (V3, drop-in):
|
|
357
|
+
import { vV2 as v } from '@oxog/vld'; // ← just change the import
|
|
358
|
+
const schema = v.object({ email: v.string().email() });
|
|
359
|
+
// All v.* calls now return V2 internally. v.object() composes them transparently.
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
**Option 2 — Global V2 toggle (for existing codebases):**
|
|
363
|
+
|
|
364
|
+
```ts
|
|
365
|
+
import { v } from '@oxog/vld';
|
|
366
|
+
|
|
367
|
+
// Switch all v.* factories to V2 once at app start
|
|
368
|
+
v.setV2Mode(true);
|
|
369
|
+
|
|
370
|
+
const s = v.string().email(); // ← now returns VldStringV2
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
**Option 3 — Selective V2 (keep V1 by default, opt in where it matters):**
|
|
374
|
+
|
|
375
|
+
```ts
|
|
376
|
+
import { v } from '@oxog/vld';
|
|
377
|
+
|
|
378
|
+
// Keep V1 for simple schemas
|
|
379
|
+
const s1 = v.boolean();
|
|
380
|
+
|
|
381
|
+
// Use V2 for the hot path
|
|
382
|
+
const s2 = v.stringV2().min(1).email(); // V2
|
|
383
|
+
const s3 = v.arrayV2(v.stringV2()); // V2
|
|
384
|
+
const s4 = v.object({ a: v.numberV2().int() }); // mixed — V2 child, V1 object
|
|
385
|
+
```
|
|
386
|
+
|
|
387
|
+
### Performance impact (V2 vs V1, same machine, 1M `safeParse` ops)
|
|
388
|
+
|
|
389
|
+
| Schema | V1 (2.4.0) | V2 (3.0) | Zod 4.5 | V2 vs Zod |
|
|
390
|
+
|---|---:|---:|---:|---:|
|
|
391
|
+
| `string().min(1).email()` | 22ms | 22ms | 50ms | **2.3x faster** |
|
|
392
|
+
| `number().int().positive().min(1)` | 12ms | 6ms | 39ms | **6.5x faster** |
|
|
393
|
+
| `object({a:str, b:num})` | 12ms | 11ms | 18ms | **1.6x faster** |
|
|
394
|
+
| Realistic API (10 fields) | 276ms | 243ms | 767ms | **3.2x faster** |
|
|
395
|
+
|
|
396
|
+
### API compatibility
|
|
397
|
+
|
|
398
|
+
- **28/28 Zod 4.5 parity tests pass.** `import { vV2 as z }` is a drop-in for Zod 4.5.
|
|
399
|
+
- V1 is the default; existing code works unchanged.
|
|
400
|
+
- V2 validators can be children of V1 composites and vice-versa (mixed schemas work).
|
|
401
|
+
|
|
402
|
+
### Internal V2 pattern (for contributors)
|
|
403
|
+
|
|
404
|
+
Each V2 class follows this shape:
|
|
405
|
+
- A single `__def: Object` field on the instance (the only data).
|
|
406
|
+
- Chain methods create a new `__def` via `withDef({...})` — no per-instance field shadowing.
|
|
407
|
+
- Constraints are class instances (`VldCheckMin`, `VldCheckEmail`, ...) with a `check(value): Issue | null` method — no per-call payload allocation.
|
|
408
|
+
- `isSimple` is precomputed in `__def` for the parse hot path.
|
|
409
|
+
|
|
410
|
+
The pattern is exactly Zod 4.5's "method memoization via prototype getters" but
|
|
411
|
+
without the `inst[k] = proto[k].bind(inst)` trick (which costs a bound function
|
|
412
|
+
per method per instance). VLD's V2 trades that for a single shared `__def` reference
|
|
413
|
+
plus a precomputed `isSimple` boolean.
|
|
414
|
+
|
|
415
|
+
### Upgrading from V2.x
|
|
416
|
+
|
|
417
|
+
VLD 3.0 is a **non-breaking** major bump:
|
|
418
|
+
- `v.*` factories still return V1 by default (no existing user code changes).
|
|
419
|
+
- New `v.*V2` and `vV2` factories are pure additions.
|
|
420
|
+
- Performance is identical to V2.x for code that doesn't opt in.
|
|
421
|
+
- All 2633 existing tests pass; 41 new V2 tests added.
|
|
422
|
+
|
|
423
|
+
To start using V2 today, just import `vV2` instead of `v`:
|
|
424
|
+
```ts
|
|
425
|
+
import { vV2 as v } from '@oxog/vld';
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
---## Bidirectional Codecs
|
|
317
429
|
|
|
318
430
|
```typescript
|
|
319
431
|
import { stringToNumber, jsonCodec, base64ToBytes, hexToBytes } from '@oxog/vld';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":"number"==typeof e?Number.isNaN(e)?"nan":e===1/0?"Infinity":e===-1/0?"-Infinity":"number":e instanceof Date?"date":e instanceof Map?"map":e instanceof Set?"set":typeof e}function r(e,r,s){return{code:"invalid_type",path:[],expected:e,received:r,message:s??`Invalid input: expected ${e}, received ${r}`}}function s(e){const r={code:e.code,path:e.path,message:e.message};return void 0!==e.expected&&(r.expected=e.expected),void 0!==e.received&&(r.received=e.received),void 0!==e.keys&&(r.keys=e.keys),void 0!==e.minimum&&(r.minimum=e.minimum),void 0!==e.maximum&&(r.maximum=e.maximum),void 0!==e.exact&&(r.exact=e.exact),void 0!==e.inclusive&&(r.inclusive=e.inclusive),void 0!==e.origin&&(r.origin=e.origin),void 0!==e.format&&(r.format=e.format),void 0!==e.values&&(r.values=e.values),void 0!==e.pattern&&(r.pattern=e.pattern),r}function t(e){const r={code:e.code,path:e.path,message:e.message};return void 0!==e.expected&&(r.expected=e.expected),void 0!==e.received&&(r.received=e.received),void 0!==e.keys&&(r.keys=e.keys),void 0!==e.minimum&&(r.minimum=e.minimum),void 0!==e.maximum&&(r.maximum=e.maximum),void 0!==e.exact&&(r.exact=e.exact),void 0!==e.inclusive&&(r.inclusive=e.inclusive),void 0!==e.origin&&(r.origin=e.origin),void 0!==e.format&&(r.format=e.format),void 0!==e.values&&(r.values=e.values),void 0!==e.pattern&&(r.pattern=e.pattern),r}class VldError extends Error{constructor(e,r){const s=e[0];super(void 0!==r?r:1===e.length&&void 0!==s?s.message:`${e.length} validation errors`),this.name="VldError",this.issues=e,globalThis.VLD_CAPTURE_STACK&&Error.captureStackTrace&&Error.captureStackTrace(this,VldError)}captureStack(){!this._stack&&Error.captureStackTrace&&(Error.captureStackTrace(this,VldError),this._stack=this.stack)}get firstError(){return this.issues[0]}get errors(){return this.issues}get isEmpty(){return 0===this.issues.length}get formattedErrors(){return this.issues.map(e=>e.message)}addIssue(e){this.issues.push(e)}addIssues(e=[]){this.issues.push(...e)}format(){const e={_errors:[]};for(const r of this.issues)if(r.path&&0!==r.path.length){let s=e;for(const e of r.path)s[e]||(s[e]={_errors:[]}),s=s[e];s._errors.push(r.message)}else e._errors.push(r.message);return e}flatten(e){const r=e??(e=>e.message),s=[],t={};for(const e of this.issues)if(e.path&&0!==e.path.length){const s=String(e.path[0]);t[s]=t[s]??[],t[s].push(r(e))}else s.push(r(e));return{formErrors:s,fieldErrors:t}}toJSON(){return{name:this.name,message:this.message,code:"VLD_VALIDATION_ERROR",issues:this.issues.map(s)}}static fromJSON(e){const r=e.issues.map(t);return new VldError(r)}static isVldError(e){return e instanceof VldError}}export{VldError as V,r as c,e as g};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{registerLocale as o,registerFallbackLocale as s,setLocale as r,getLocale as l,getMessages as e,getMessagesForLocale as m,getSupportedLocales as t,isLocaleLoaded as a,isLocaleSupported as i}from"../locales/runtime.js";import{en as c}from"../locales/en.js";import{tr as f}from"../locales/tr.js";import{es as p}from"../locales/es.js";import{fr as j}from"../locales/fr.js";import{de as n}from"../locales/de.js";import{it as u}from"../locales/it.js";import{pt as d}from"../locales/pt.js";import{ru as g}from"../locales/ru.js";import{ja as h}from"../locales/ja.js";import{ko as k}from"../locales/ko.js";import{zh as v}from"../locales/zh.js";import{ar as L}from"../locales/ar.js";import{hi as y}from"../locales/hi.js";import{nl as z}from"../locales/nl.js";import{pl as b}from"../locales/pl.js";import{da as M}from"../locales/da.js";import{sv as R}from"../locales/sv.js";import{no as _}from"../locales/no.js";import{fi as w}from"../locales/fi.js";import{th as A}from"../locales/th.js";import{vi as B}from"../locales/vi.js";import{id as X}from"../locales/id.js";import{bn as q}from"../locales/bn.js";import{gu as x}from"../locales/gu.js";import{kn as S}from"../locales/kn.js";import{ne as C}from"../locales/ne.js";import{sk as F}from"../locales/sk.js";import{sw as O}from"../locales/sw.js";import{af as D}from"../locales/af.js";import{ptBR as E}from"../locales/pt-BR.js";import{esMX as G}from"../locales/es-MX.js";const H=["en","tr","es","fr","de","it","pt","ru","ja","ko","zh","ar","hi","nl","pl","da","sv","no","fi","th","vi","id","bn","gu","kn","ne","sk","sw","af","pt-BR","es-MX"],I=["is","cs","hu","ro","bg","hr","sl","lv","lt","et","el","mk","sq","sr","bs","me","mt","ga","cy","eu","ca","ms","tl","ur","fa","he","ka","am","hy","az","kk","ky","uz","tg","mn","my","km","lo","si","ta","te","ml","pa","or","as","mr","sd","dv","ha","yo","ig","zu","xh","st","tn","ts","ve","nr","ss","es-AR","fr-CA","qu","gn","ay"],J={en:c,tr:f,es:p,fr:j,de:n,it:u,pt:d,ru:g,ja:h,ko:k,zh:v,ar:L,hi:y,nl:z,pl:b,da:M,sv:R,no:_,fi:w,sk:F,th:A,vi:B,id:X,bn:q,gu:x,kn:S,ne:C,sw:O,af:D,"pt-BR":E,"es-MX":G};for(const s of H)o(s,J[s]);for(const o of I)s(o);async function K(o){r(o)}var N=Object.freeze({__proto__:null,getLocale:l,getMessages:e,getMessagesForLocale:m,getSupportedLocales:t,isLocaleLoaded:a,isLocaleSupported:i,registerLocale:o,setLocale:r,setLocaleAsync:K});export{N as l,K as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";function e(e){const r={code:e.code,path:e.path,message:e.message};return void 0!==e.expected&&(r.expected=e.expected),void 0!==e.received&&(r.received=e.received),void 0!==e.keys&&(r.keys=e.keys),void 0!==e.minimum&&(r.minimum=e.minimum),void 0!==e.maximum&&(r.maximum=e.maximum),void 0!==e.exact&&(r.exact=e.exact),void 0!==e.inclusive&&(r.inclusive=e.inclusive),void 0!==e.origin&&(r.origin=e.origin),void 0!==e.format&&(r.format=e.format),void 0!==e.values&&(r.values=e.values),void 0!==e.pattern&&(r.pattern=e.pattern),r}function r(e){const r={code:e.code,path:e.path,message:e.message};return void 0!==e.expected&&(r.expected=e.expected),void 0!==e.received&&(r.received=e.received),void 0!==e.keys&&(r.keys=e.keys),void 0!==e.minimum&&(r.minimum=e.minimum),void 0!==e.maximum&&(r.maximum=e.maximum),void 0!==e.exact&&(r.exact=e.exact),void 0!==e.inclusive&&(r.inclusive=e.inclusive),void 0!==e.origin&&(r.origin=e.origin),void 0!==e.format&&(r.format=e.format),void 0!==e.values&&(r.values=e.values),void 0!==e.pattern&&(r.pattern=e.pattern),r}class VldError extends Error{constructor(e,r){const s=e[0];super(void 0!==r?r:1===e.length&&void 0!==s?s.message:`${e.length} validation errors`),this.name="VldError",this.issues=e,globalThis.VLD_CAPTURE_STACK&&Error.captureStackTrace&&Error.captureStackTrace(this,VldError)}captureStack(){!this._stack&&Error.captureStackTrace&&(Error.captureStackTrace(this,VldError),this._stack=this.stack)}get firstError(){return this.issues[0]}get errors(){return this.issues}get isEmpty(){return 0===this.issues.length}get formattedErrors(){return this.issues.map(e=>e.message)}addIssue(e){this.issues.push(e)}addIssues(e=[]){this.issues.push(...e)}format(){const e={_errors:[]};for(const r of this.issues)if(r.path&&0!==r.path.length){let s=e;for(const e of r.path)s[e]||(s[e]={_errors:[]}),s=s[e];s._errors.push(r.message)}else e._errors.push(r.message);return e}flatten(e){const r=e??(e=>e.message),s=[],t={};for(const e of this.issues)if(e.path&&0!==e.path.length){const s=String(e.path[0]);t[s]=t[s]??[],t[s].push(r(e))}else s.push(r(e));return{formErrors:s,fieldErrors:t}}toJSON(){return{name:this.name,message:this.message,code:"VLD_VALIDATION_ERROR",issues:this.issues.map(e)}}static fromJSON(e){const s=e.issues.map(r);return new VldError(s)}static isVldError(e){return e instanceof VldError}}exports.VldError=VldError,exports.createInvalidTypeIssue=function(e,r,s){return{code:"invalid_type",path:[],expected:e,received:r,message:s??`Invalid input: expected ${e}, received ${r}`}},exports.getTypeName=function(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":"number"==typeof e?Number.isNaN(e)?"nan":e===1/0?"Infinity":e===-1/0?"-Infinity":"number":e instanceof Date?"date":e instanceof Map?"map":e instanceof Set?"set":typeof e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var e=require("../locales/runtime.cjs"),s=require("../locales/en.cjs"),r=require("../locales/tr.cjs"),l=require("../locales/es.cjs"),c=require("../locales/fr.cjs"),a=require("../locales/de.cjs"),o=require("../locales/it.cjs"),i=require("../locales/pt.cjs"),t=require("../locales/ru.cjs"),u=require("../locales/ja.cjs"),n=require("../locales/ko.cjs"),j=require("../locales/zh.cjs"),q=require("../locales/ar.cjs"),g=require("../locales/hi.cjs"),p=require("../locales/nl.cjs"),d=require("../locales/pl.cjs"),L=require("../locales/da.cjs"),f=require("../locales/sv.cjs"),k=require("../locales/no.cjs"),h=require("../locales/fi.cjs"),v=require("../locales/th.cjs"),m=require("../locales/vi.cjs"),y=require("../locales/id.cjs"),b=require("../locales/bn.cjs"),z=require("../locales/gu.cjs"),M=require("../locales/kn.cjs"),R=require("../locales/ne.cjs"),w=require("../locales/sk.cjs"),A=require("../locales/sw.cjs"),B=require("../locales/af.cjs"),S=require("../locales/pt-BR.cjs"),X=require("../locales/es-MX.cjs");const _=["en","tr","es","fr","de","it","pt","ru","ja","ko","zh","ar","hi","nl","pl","da","sv","no","fi","th","vi","id","bn","gu","kn","ne","sk","sw","af","pt-BR","es-MX"],x=["is","cs","hu","ro","bg","hr","sl","lv","lt","et","el","mk","sq","sr","bs","me","mt","ga","cy","eu","ca","ms","tl","ur","fa","he","ka","am","hy","az","kk","ky","uz","tg","mn","my","km","lo","si","ta","te","ml","pa","or","as","mr","sd","dv","ha","yo","ig","zu","xh","st","tn","ts","ve","nr","ss","es-AR","fr-CA","qu","gn","ay"],F={en:s.en,tr:r.tr,es:l.es,fr:c.fr,de:a.de,it:o.it,pt:i.pt,ru:t.ru,ja:u.ja,ko:n.ko,zh:j.zh,ar:q.ar,hi:g.hi,nl:p.nl,pl:d.pl,da:L.da,sv:f.sv,no:k.no,fi:h.fi,sk:w.sk,th:v.th,vi:m.vi,id:y.id,bn:b.bn,gu:z.gu,kn:M.kn,ne:R.ne,sw:A.sw,af:B.af,"pt-BR":S.ptBR,"es-MX":X.esMX};for(const s of _)e.registerLocale(s,F[s]);for(const s of x)e.registerFallbackLocale(s);async function C(s){e.setLocale(s)}var N=Object.freeze({__proto__:null,getLocale:e.getLocale,getMessages:e.getMessages,getMessagesForLocale:e.getMessagesForLocale,getSupportedLocales:e.getSupportedLocales,isLocaleLoaded:e.isLocaleLoaded,isLocaleSupported:e.isLocaleSupported,registerLocale:e.registerLocale,setLocale:e.setLocale,setLocaleAsync:C});exports.localeNamespace=N,exports.setLocaleAsync=C;
|
package/dist/cjs/cli/bin.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var e=require("./index.cjs"),r=require("fs"),s=require("path"),o=require("../pigment.cjs"),a=require("../errors.cjs"),
|
|
2
|
+
"use strict";var e=require("./index.cjs"),r=require("fs"),s=require("path"),o=require("../pigment.cjs"),a=require("../errors.cjs"),i=require("../index.cjs");require("../chunks/errors-core-C0mA6tfa.cjs"),require("../validators/base.cjs"),require("../registry.cjs"),require("../validators/string.cjs"),require("../locales/runtime.cjs"),require("../locales/en.cjs"),require("../chunks/ip-validation-BZqPamPC.cjs"),require("../validators/string-v2.cjs"),require("../validators/number-v2.cjs"),require("../validators/date-v2.cjs"),require("../validators/bigint-v2.cjs"),require("../validators/array-v2.cjs"),require("../validators/union-v2.cjs"),require("../validators/wrapper-v2.cjs"),require("../validators/leaf-v2.cjs"),require("../validators/composite-v2.cjs"),require("../validators/number.cjs"),require("../validators/boolean.cjs"),require("../validators/date.cjs"),require("../validators/string-bool.cjs"),require("../validators/array.cjs"),require("../validators/object.cjs"),require("../validators/enum.cjs"),require("../chunks/security-aXZVI7qW.cjs"),require("../validators/union.cjs"),require("../validators/literal.cjs"),require("../validators/bigint.cjs"),require("../validators/symbol.cjs"),require("../validators/tuple.cjs"),require("../validators/record.cjs"),require("../validators/set.cjs"),require("../validators/map.cjs"),require("../validators/intersection.cjs"),require("../validators/any.cjs"),require("../validators/unknown.cjs"),require("../validators/void.cjs"),require("../validators/never.cjs"),require("../validators/null.cjs"),require("../validators/undefined.cjs"),require("../validators/nan.cjs"),require("../validators/lazy.cjs"),require("../validators/discriminated-union.cjs"),require("../validators/xor.cjs"),require("../validators/json.cjs"),require("../validators/template-literal.cjs"),require("../validators/custom.cjs"),require("../validators/file.cjs"),require("../validators/function.cjs"),require("../validators/codec.cjs"),require("../validators/base64.cjs"),require("../validators/hex.cjs"),require("../validators/uint8array.cjs"),require("../validators/promise.cjs"),require("../compat/result.cjs"),require("../chunks/index-lejEpLfv.cjs"),require("../locales/tr.cjs"),require("../locales/es.cjs"),require("../locales/fr.cjs"),require("../locales/de.cjs"),require("../locales/it.cjs"),require("../locales/pt.cjs"),require("../locales/ru.cjs"),require("../locales/ja.cjs"),require("../locales/ko.cjs"),require("../locales/zh.cjs"),require("../locales/ar.cjs"),require("../locales/hi.cjs"),require("../locales/nl.cjs"),require("../locales/pl.cjs"),require("../locales/da.cjs"),require("../locales/sv.cjs"),require("../locales/no.cjs"),require("../locales/fi.cjs"),require("../locales/th.cjs"),require("../locales/vi.cjs"),require("../locales/id.cjs"),require("../locales/bn.cjs"),require("../locales/gu.cjs"),require("../locales/kn.cjs"),require("../locales/ne.cjs"),require("../locales/sk.cjs"),require("../locales/sw.cjs"),require("../locales/af.cjs"),require("../locales/pt-BR.cjs"),require("../locales/es-MX.cjs"),require("../coercion/index.cjs"),require("../validators/string-formats.cjs"),require("../compile.cjs"),require("../chunks/index-ZjHAxYdA.cjs"),require("../compat/emitter.cjs"),require("../kernel.cjs");var t="undefined"!=typeof document?document.currentScript:null;function l(e){if(e&&e.__esModule)return e;var r=Object.create(null);return e&&Object.keys(e).forEach(function(s){if("default"!==s){var o=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(r,s,o.get?o:{enumerable:!0,get:function(){return e[s]}})}}),r.default=e,Object.freeze(r)}var c=l(r),n=l(s);function u(e,r,s){const o=process.cwd();if(!e.startsWith(o+n.sep)&&e!==o)throw new Error(`${r} path escapes allowed directory: ${s}`)}const d={name:"validate",description:"Validate JSON data against a VLD schema",aliases:["v"],arguments:[{name:"schema",description:"Path to schema file (.ts or .js)",required:!0},{name:"data",description:"Path to JSON data file or JSON string",required:!0}],options:[{name:"strict",short:"s",description:"Enable strict mode (no extra keys)",type:"boolean",default:!1},{name:"quiet",short:"q",description:"Only output errors",type:"boolean",default:!1},{name:"json",short:"j",description:"Output as JSON",type:"boolean",default:!1},{name:"no-color",description:"Disable colored output",type:"boolean",default:!1}],action:async(e,r)=>{const s=e.schema,i=e.data,t=r.quiet,l=r.json,d=r["no-color"];let p,f;try{const e=n.resolve(process.cwd(),s);if(u(e,"Schema",s),!c.existsSync(e))throw new Error(`Schema file not found: ${s}`);const r=await(import(e));if(p=r.default||r.schema||r,!p||"function"!=typeof p.parse)throw new Error("Schema must export a VLD validator with parse() method")}catch(e){return l?console.log(JSON.stringify({success:!1,error:e.message})):console.error(o.default.red("Schema Error:"),e.message),void(process.exitCode=1)}try{if(i.startsWith("{")||i.startsWith("["))f=JSON.parse(i);else{const e=n.resolve(process.cwd(),i);if(u(e,"Data",i),!c.existsSync(e))throw new Error(`Data file not found: ${i}`);const r=c.readFileSync(e,"utf-8");f=JSON.parse(r)}}catch(e){return l?console.log(JSON.stringify({success:!1,error:e.message})):console.error(o.default.red("Data Error:"),e.message),void(process.exitCode=1)}const m=p.safeParse(f);if(l)if(m.success)console.log(JSON.stringify({success:!0,data:m.data}));else{const e=m.error,r={success:!1,error:e?.message,issues:e?.issues};console.log(JSON.stringify(r))}else if(m.success)t||(console.log(o.default.green("Validation passed")),console.log(""),console.log(o.default.dim("Data:")),console.log(JSON.stringify(m.data,null,2)));else{if(console.error(o.default.red("Validation failed")),console.error(""),m.error&&"issues"in m.error){const e=d?a.prettifyError(m.error,{colored:!1}):a.prettifyErrorColored(m.error);console.error(e)}else console.error(m.error?.message||"Unknown error");process.exitCode=1}}};function p(e,r,s){for(let e=0;e<Math.min(100,s/10);e++)r();const o=performance.now();for(let e=0;e<s;e++)r();const a=performance.now()-o,i=a/s;return{name:e,iterations:s,totalMs:a,avgMs:i,opsPerSec:1e3/i}}function f(e){return e.toLocaleString("en-US",{maximumFractionDigits:2})}function m(e,r){return`${r?o.default.cyan(e.name.padEnd(30)):e.name.padEnd(30)} ${r?o.default.green(f(e.opsPerSec).padStart(12)):f(e.opsPerSec).padStart(12)} ops/sec ${r?o.default.yellow(e.avgMs.toFixed(6).padStart(12)):e.avgMs.toFixed(6).padStart(12)} ms/op`}const j={name:"benchmark",description:"Run performance benchmarks",aliases:["bench","b"],options:[{name:"iterations",short:"n",description:"Number of iterations",type:"number",default:1e4},{name:"suite",short:"s",description:"Benchmark suite to run (all, primitives, objects, arrays)",type:"string",default:"all"},{name:"json",short:"j",description:"Output as JSON",type:"boolean",default:!1},{name:"no-color",description:"Disable colored output",type:"boolean",default:!1}],action:async(e,r)=>{const s=r.iterations,a=r.suite,t=r.json,l=!r["no-color"],c=[],n=i.default.string(),u=i.default.number(),d=i.default.boolean(),j=i.default.date(),q=i.default.object({name:i.default.string(),email:i.default.string(),age:i.default.number(),active:i.default.boolean()}),v=i.default.array(i.default.number()),g=i.default.object({user:i.default.object({name:i.default.string(),email:i.default.string()}),items:i.default.array(i.default.object({id:i.default.number(),name:i.default.string(),price:i.default.number()}))}),h="hello world",b=new Date,y={name:"John",email:"john@example.com",age:30,active:!0},S=[1,2,3,4,5,6,7,8,9,10],w={user:{name:"John",email:"john@example.com"},items:[{id:1,name:"Item 1",price:10.99},{id:2,name:"Item 2",price:20.99},{id:3,name:"Item 3",price:30.99}]};if(t||(console.log(o.default.bold("VLD Performance Benchmark")),console.log(o.default.dim(`Running ${f(s)} iterations per test`)),console.log("")),("all"===a||"primitives"===a)&&(t||console.log(o.default.bold("Primitives:")),c.push(p("string.parse()",()=>n.parse(h),s)),c.push(p("number.parse()",()=>u.parse(42),s)),c.push(p("boolean.parse()",()=>d.parse(true),s)),c.push(p("date.parse()",()=>j.parse(b),s)),c.push(p("string.safeParse()",()=>n.safeParse(h),s)),!t)){for(const e of c.slice(-5))console.log(" "+m(e,l));console.log("")}if(("all"===a||"objects"===a)&&(t||console.log(o.default.bold("Objects:")),c.push(p("object.parse()",()=>q.parse(y),s)),c.push(p("object.safeParse()",()=>q.safeParse(y),s)),c.push(p("nested.parse()",()=>g.parse(w),s)),!t)){for(const e of c.slice(-3))console.log(" "+m(e,l));console.log("")}if(("all"===a||"arrays"===a)&&(t||console.log(o.default.bold("Arrays:")),c.push(p("array.parse()",()=>v.parse(S),s)),c.push(p("array.safeParse()",()=>v.safeParse(S),s)),!t)){for(const e of c.slice(-2))console.log(" "+m(e,l));console.log("")}if(t)console.log(JSON.stringify({iterations:s,suite:a,results:c.map(e=>({name:e.name,iterations:e.iterations,totalMs:e.totalMs,avgMs:e.avgMs,opsPerSec:e.opsPerSec}))}));else{const e=c.reduce((e,r)=>e+r.opsPerSec,0)/c.length;console.log(o.default.bold("Summary:")),console.log(` Total benchmarks: ${c.length}`),console.log(` Average ops/sec: ${f(e)}`)}}},q=JSON.parse(r.readFileSync(new URL("../../package.json","undefined"==typeof document?require("url").pathToFileURL(__filename).href:t&&"SCRIPT"===t.tagName.toUpperCase()&&t.src||new URL("cli/bin.cjs",document.baseURI).href),"utf-8")).version||"0.0.0";e.vldCli.version=q,e.vldCli.command(d),e.vldCli.command(j),e.vldCli.command({name:"help",description:"Show help information",aliases:["h"],action:()=>{console.log(e.vldCli.help())}}),e.vldCli.command({name:"version",description:"Show version information",action:()=>{console.log(`vld v${q}`)}}),e.vldCli.run(process.argv.slice(2)).catch(e=>{console.error("Fatal error:",e),process.exitCode=1});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";require("../validators/codec.cjs"),require("../validators/base64.cjs"),require("../validators/hex.cjs"),require("../validators/uint8array.cjs"),require("../validators/string.cjs"),require("../validators/number.cjs"),require("../validators/bigint.cjs"),require("../validators/boolean.cjs"),require("../validators/date.cjs"),require("../validators/unknown.cjs");var e=require("../chunks/index-ZjHAxYdA.cjs");require("../validators/base.cjs"),require("../registry.cjs"),require("../chunks/errors-core-
|
|
1
|
+
"use strict";require("../validators/codec.cjs"),require("../validators/base64.cjs"),require("../validators/hex.cjs"),require("../validators/uint8array.cjs"),require("../validators/string.cjs"),require("../validators/number.cjs"),require("../validators/bigint.cjs"),require("../validators/boolean.cjs"),require("../validators/date.cjs"),require("../validators/unknown.cjs");var e=require("../chunks/index-ZjHAxYdA.cjs");require("../validators/base.cjs"),require("../registry.cjs"),require("../chunks/errors-core-C0mA6tfa.cjs"),require("../errors.cjs"),require("../pigment.cjs"),require("../locales/runtime.cjs"),require("../locales/en.cjs"),require("../chunks/ip-validation-BZqPamPC.cjs"),exports.base64Json=e.base64Json,exports.base64ToBytes=e.base64ToBytes,exports.base64UrlToBytes=e.base64UrlToBytes,exports.base64urlToBytes=e.base64urlToBytes,exports.bytesToUtf8=e.bytesToUtf8,exports.epochMillisToDate=e.epochMillisToDate,exports.epochSecondsToDate=e.epochSecondsToDate,exports.hexLowerToBytes=e.hexLowerToBytes,exports.hexToBytes=e.hexToBytes,exports.invertCodec=e.invertCodec,exports.isoDatetimeToDate=e.isoDatetimeToDate,exports.jsonCodec=e.jsonCodec,exports.jwtPayload=e.jwtPayload,exports.numberToBigInt=e.numberToBigInt,exports.stringToBigInt=e.stringToBigInt,exports.stringToBoolean=e.stringToBoolean,exports.stringToHttpURL=e.stringToHttpURL,exports.stringToInt=e.stringToInt,exports.stringToNumber=e.stringToNumber,exports.stringToURL=e.stringToURL,exports.uriComponent=e.uriComponent,exports.utf8ToBytes=e.utf8ToBytes;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../validators/string.cjs"),r=require("../validators/base.cjs"),s=require("../locales/runtime.cjs"),t=require("../chunks/ip-validation-BZqPamPC.cjs"),n=require("../validators/number.cjs"),c=require("../validators/boolean.cjs"),i=require("../validators/date.cjs"),o=require("../validators/bigint.cjs");require("../chunks/errors-core-
|
|
1
|
+
"use strict";var e=require("../validators/string.cjs"),r=require("../validators/base.cjs"),s=require("../locales/runtime.cjs"),t=require("../chunks/ip-validation-BZqPamPC.cjs"),n=require("../validators/number.cjs"),c=require("../validators/boolean.cjs"),i=require("../validators/date.cjs"),o=require("../validators/bigint.cjs");require("../chunks/errors-core-C0mA6tfa.cjs"),require("../registry.cjs"),require("../locales/en.cjs");class VldCoerceString extends e.VldString{constructor(e){super({...e,validatorType:r.VLD_VALIDATOR_TYPES.COERCE_STRING})}static create(){return new VldCoerceString}min(e,r){return new VldCoerceString({checks:[...this.config.checks,r=>r.length>=e],transforms:this.config.transforms,errorMessage:r||s.getMessages().stringMin(e)})}max(e,r){return new VldCoerceString({checks:[...this.config.checks,r=>r.length<=e],transforms:this.config.transforms,errorMessage:r||s.getMessages().stringMax(e)})}length(e,r){return new VldCoerceString({checks:[...this.config.checks,r=>r.length===e],transforms:this.config.transforms,errorMessage:r||s.getMessages().stringLength(e)})}email(e){const r=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return new VldCoerceString({checks:[...this.config.checks,e=>r.test(e)],transforms:this.config.transforms,errorMessage:e||s.getMessages().stringEmail})}url(e){return new VldCoerceString({checks:[...this.config.checks,e=>/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)$/.test(e)],transforms:this.config.transforms,errorMessage:e||s.getMessages().stringUrl})}uuid(e){return new VldCoerceString({checks:[...this.config.checks,e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)],transforms:this.config.transforms,errorMessage:e||s.getMessages().stringUuid})}regex(e,r){return new VldCoerceString({checks:[...this.config.checks,r=>e.test(r)],transforms:this.config.transforms,errorMessage:r||s.getMessages().stringRegex})}trim(){return new VldCoerceString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.trim()],errorMessage:this.config.errorMessage})}toLowerCase(){return new VldCoerceString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.toLowerCase()],errorMessage:this.config.errorMessage})}toUpperCase(){return new VldCoerceString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.toUpperCase()],errorMessage:this.config.errorMessage})}startsWith(e,r){return new VldCoerceString({checks:[...this.config.checks,r=>r.startsWith(e)],transforms:this.config.transforms,errorMessage:r||s.getMessages().stringStartsWith(e)})}endsWith(e,r){return new VldCoerceString({checks:[...this.config.checks,r=>r.endsWith(e)],transforms:this.config.transforms,errorMessage:r||s.getMessages().stringEndsWith(e)})}includes(e,r){return new VldCoerceString({checks:[...this.config.checks,r=>r.includes(e)],transforms:this.config.transforms,errorMessage:r||s.getMessages().stringIncludes(e)})}ip(e){const r=/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;return new VldCoerceString({checks:[...this.config.checks,e=>!(e.length>100)&&(r.test(e)||t.isValidIPv6(e))],transforms:this.config.transforms,errorMessage:e||s.getMessages().stringIp})}ipv4(e){return new VldCoerceString({checks:[...this.config.checks,e=>/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(e)],transforms:this.config.transforms,errorMessage:e||s.getMessages().stringIpv4})}ipv6(e){return new VldCoerceString({checks:[...this.config.checks,e=>t.isValidIPv6(e)],transforms:this.config.transforms,errorMessage:e||s.getMessages().stringIpv6})}nonempty(e){return new VldCoerceString({checks:[...this.config.checks,e=>e.length>0],transforms:this.config.transforms,errorMessage:e||s.getMessages().stringEmpty})}parse(e){if("string"==typeof e){if(e.length>1e6)throw new Error(s.getMessages().coercionFailed("string",e));const r=e.replace(/[\x00-\x1F\x7F]/g,"");return super.parse(r)}let r;if(r="number"==typeof e?String(e):"boolean"==typeof e?e?"true":"false":"bigint"==typeof e?e.toString():"symbol"==typeof e?String(e):"object"==typeof e?e instanceof Date?e.toISOString():Array.isArray(e)?e.join(","):e instanceof RegExp?e.toString():e instanceof Error?e.message||e.toString():String(e):String(e),r.length>1e6)throw new Error(s.getMessages().coercionFailed("string",e));const t=r.replace(/[\x00-\x1F\x7F]/g,"");return super.parse(t)}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:r.ensureVldError(e)}}}}class VldCoerceNumber extends n.VldNumber{constructor(e){super({...e,validatorType:r.VLD_VALIDATOR_TYPES.COERCE_NUMBER})}static create(){return new VldCoerceNumber}min(e,r){return new VldCoerceNumber({checks:[...this.config.checks,r=>r>=e],errorMessage:r||s.getMessages().numberMin(e)})}max(e,r){return new VldCoerceNumber({checks:[...this.config.checks,r=>r<=e],errorMessage:r||s.getMessages().numberMax(e)})}int(e){return new VldCoerceNumber({checks:[...this.config.checks,e=>Number.isInteger(e)],errorMessage:e||s.getMessages().numberInt})}positive(e){return new VldCoerceNumber({checks:[...this.config.checks,e=>e>0],errorMessage:e||s.getMessages().numberPositive})}negative(e){return new VldCoerceNumber({checks:[...this.config.checks,e=>e<0],errorMessage:e||s.getMessages().numberNegative})}nonnegative(e){return new VldCoerceNumber({checks:[...this.config.checks,e=>e>=0],errorMessage:e||s.getMessages().numberNonnegative})}nonpositive(e){return new VldCoerceNumber({checks:[...this.config.checks,e=>e<=0],errorMessage:e||s.getMessages().numberNonpositive})}finite(e){return new VldCoerceNumber({checks:[...this.config.checks,e=>Number.isFinite(e)],errorMessage:e||s.getMessages().numberFinite})}safe(e){return new VldCoerceNumber({checks:[...this.config.checks,e=>Number.isSafeInteger(e)],errorMessage:e||s.getMessages().numberSafe})}multipleOf(e,r){return new VldCoerceNumber({checks:[...this.config.checks,r=>{const s=Math.abs(r%e);return s<Number.EPSILON||Math.abs(s-Math.abs(e))<Number.EPSILON}],errorMessage:r||s.getMessages().numberMultipleOf(e)})}step(e,r){return this.multipleOf(e,r)}between(e,r,s){return new VldCoerceNumber({checks:[...this.config.checks,s=>s>=e&&s<=r],errorMessage:s||`Number must be between ${e} and ${r}`})}even(e){return new VldCoerceNumber({checks:[...this.config.checks,e=>!!Number.isInteger(e)&&e%2==0],errorMessage:e||"Number must be even"})}odd(e){return new VldCoerceNumber({checks:[...this.config.checks,e=>!!Number.isInteger(e)&&e%2!=0],errorMessage:e||"Number must be odd"})}parse(e){if("number"==typeof e&&!isNaN(e))return 0===this.config.checks.length?e:super.parse(e);let r;try{r=Number(e)}catch{throw new Error(s.getMessages().coercionFailed("number",e))}if(isNaN(r))throw new Error(s.getMessages().coercionFailed("number",e));return 0===this.config.checks.length?r:super.parse(r)}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:r.ensureVldError(e)}}}}class VldCoerceBoolean extends c.VldBoolean{static create(){return new VldCoerceBoolean}constructor(){super(void 0,r.VLD_VALIDATOR_TYPES.COERCE_BOOLEAN)}parse(e){return Boolean(e)}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:r.ensureVldError(e)}}}}class VldCoerceDate extends i.VldDate{static create(){return new VldCoerceDate}constructor(){super({validatorType:r.VLD_VALIDATOR_TYPES.COERCE_DATE})}parse(e){try{if(e instanceof Date)return super.parse(e);const r=new Date(e);if(isNaN(r.getTime()))throw new Error(s.getMessages().coercionFailed("date",e));return super.parse(r)}catch(r){if(r.message.includes("Cannot coerce"))throw r;throw new Error(s.getMessages().coercionFailed("date",e))}}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:r.ensureVldError(e)}}}}class VldCoerceBigInt extends o.VldBigInt{constructor(e){super({...e,validatorType:r.VLD_VALIDATOR_TYPES.COERCE_BIGINT})}static create(){return new VldCoerceBigInt}min(e,r){return new VldCoerceBigInt({checks:[...this.config.checks,r=>r>=e],errorMessage:r||`BigInt must be at least ${e}`})}max(e,r){return new VldCoerceBigInt({checks:[...this.config.checks,r=>r<=e],errorMessage:r||`BigInt must be at most ${e}`})}positive(e){return new VldCoerceBigInt({checks:[...this.config.checks,e=>e>0n],errorMessage:e||"BigInt must be positive"})}negative(e){return new VldCoerceBigInt({checks:[...this.config.checks,e=>e<0n],errorMessage:e||"BigInt must be negative"})}nonnegative(e){return new VldCoerceBigInt({checks:[...this.config.checks,e=>e>=0n],errorMessage:e||"BigInt must be non-negative"})}nonpositive(e){return new VldCoerceBigInt({checks:[...this.config.checks,e=>e<=0n],errorMessage:e||"BigInt must be non-positive"})}parse(e){if("bigint"==typeof e)return super.parse(e);if("string"==typeof e){const r=e.trim();if(""===r)throw new Error(s.getMessages().coercionFailed("bigint",e));try{const e=BigInt(r);return super.parse(e)}catch{throw new Error(s.getMessages().coercionFailed("bigint",e))}}if("number"==typeof e){if(!Number.isInteger(e))throw new Error(s.getMessages().coercionFailed("bigint",e));const r=BigInt(e);return super.parse(r)}if(null==e)throw new Error(s.getMessages().coercionFailed("bigint",e));try{const r=BigInt(e);return super.parse(r)}catch{throw new Error(s.getMessages().coercionFailed("bigint",e))}}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:r.ensureVldError(e)}}}}exports.VldCoerceBigInt=VldCoerceBigInt,exports.VldCoerceBoolean=VldCoerceBoolean,exports.VldCoerceDate=VldCoerceDate,exports.VldCoerceNumber=VldCoerceNumber,exports.VldCoerceString=VldCoerceString;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var e=require("./validators/base.cjs"),t=require("./validators/string.cjs"),i=require("./validators/number.cjs"),r=require("./validators/boolean.cjs"),s=require("./validators/bigint.cjs"),n=require("./validators/undefined.cjs"),o=require("./validators/null.cjs"),a=require("./validators/object.cjs"),u=require("./validators/array.cjs"),l=require("./validators/unknown.cjs");require("./registry.cjs"),require("./chunks/errors-core-C0mA6tfa.cjs"),require("./locales/runtime.cjs"),require("./locales/en.cjs"),require("./chunks/ip-validation-BZqPamPC.cjs"),require("./validators/enum.cjs"),require("./chunks/security-aXZVI7qW.cjs");class c extends Error{constructor(e){super(e),this.name="ZodCompileError"}}class h extends c{constructor(e="Cannot compile async schema"){super(e),this.name="ZodCompileAsyncError"}}class d extends c{constructor(e="Schema node is not supported by the AOT compiler"){super(e),this.name="ZodCompileUnsupportedError"}}const $=Symbol.for("@oxog/vld/compile-invalid");function f(e){return e&&e.constructor&&e.constructor.name||""}function v(e,t){return`__${t}${e.scratch++}`}function p(e,t,i){if(!i.failed){if("VldString"===f(e)){const r=e._checks,s=e._checkMetas,n=[];if(s)for(const e of s)switch(e.kind){case"min":n.push(`__v.length >= ${e.value}`);break;case"max":n.push(`__v.length <= ${e.value}`);break;case"length":n.push(`__v.length === ${e.value}`);break;case"regex":{const t=(e.pattern??e.value?.source??String(e.value)).replace(/\\/g,"\\\\").replace(/\//g,"\\/");n.push(`/${t}/.test(__v)`);break}case"startsWith":n.push(`__v.startsWith(${JSON.stringify(e.value)})`);break;case"endsWith":n.push(`__v.endsWith(${JSON.stringify(e.value)})`);break;case"includes":n.push(`__v.includes(${JSON.stringify(e.value)})`);break;case"email":case"url":case"uuid":case"ip":break;default:if(r&&r.length>0)return void(i.failed=!0)}else if(r&&r.length>0)return void(i.failed=!0);return void(0===n.length?i.hoist.push(`if (typeof ${t} !== "string") ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+t};`):i.hoist.push(`{ const __v = ${t}; if (typeof __v !== "string" || !(${n.join(" && ")})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = __v; }`))}if("VldNumber"===f(e)){const r=e._checks,s=e._checkMetas,n=[];if(s)for(const e of s)switch(e.kind){case"int":n.push("Number.isInteger(__v)");break;case"finite":n.push("Number.isFinite(__v)");break;case"min":n.push(!1!==e.inclusive?`__v >= ${e.value}`:`__v > ${e.value}`);break;case"max":n.push(!1!==e.inclusive?`__v <= ${e.value}`:`__v < ${e.value}`);break;case"gt":n.push(`__v > ${e.value}`);break;case"gte":n.push(`__v >= ${e.value}`);break;case"lt":n.push(`__v < ${e.value}`);break;case"lte":n.push(`__v <= ${e.value}`);break;case"multipleOf":n.push(`__v % ${e.value} === 0`);break;case"positive":n.push("__v > 0");break;case"negative":n.push("__v < 0");break;case"nonnegative":n.push("__v >= 0");break;case"nonpositive":n.push("__v <= 0");break;case"safe":n.push("Number.isSafeInteger(__v)");break;default:if(r&&r.length>0)return void(i.failed=!0)}else if(r&&r.length>0)return void(i.failed=!0);const o=['typeof __v === "number"',"!Number.isNaN(__v)",...n];return void i.hoist.push(`{ const __v = ${t}; if (!(${o.join(" && ")})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = __v; }`)}if("VldBoolean"!==f(e)){if("VldBigInt"===f(e)){const r=e._checks,s=e._checkMetas,n=[];if(s)for(const e of s)switch(e.kind){case"min":n.push(`__v >= ${e.value}n`);break;case"max":n.push(`__v <= ${e.value}n`);break;case"positive":n.push("__v > 0n");break;case"negative":n.push("__v < 0n");break;case"nonnegative":n.push("__v >= 0n");break;case"nonpositive":n.push("__v <= 0n");break;default:if(r&&r.length>0)return void(i.failed=!0)}else if(r&&r.length>0)return void(i.failed=!0);const o=['typeof __v === "bigint"',...n];return void i.hoist.push(`{ const __v = ${t}; if (!(${o.join(" && ")})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = __v; }`)}if("VldDate"!==f(e))if("VldNull"!==f(e))if("VldUndefined"!==f(e))if("VldAny"!==f(e)&&"VldUnknown"!==f(e)){if("VldLiteral"===f(e)){const r=e._values||[];if(0===r.length)return void i.hoist.push(`${i.throwOnFail?"throw":"return"} ${i.invalid};`);if(1===r.length){const e=r[0],s="number"==typeof e&&Number.isNaN(e)?"NaN":JSON.stringify(e);return void i.hoist.push(`if (!Object.is(${s}, ${t})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+t};`)}const s=v(i,"set");return i.hoist.push(`const ${s} = new Set([${r.map(e=>"number"==typeof e&&Number.isNaN(e)?"NaN":JSON.stringify(e)).join(",")}]);`),void i.hoist.push(`if (!${s}.has(${t})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+t};`)}if("VldEnum"===f(e)){const r=e._values||[],s=v(i,"set");return i.hoist.push(`const ${s} = new Set([${r.map(e=>JSON.stringify(e)).join(",")}]);`),void i.hoist.push(`if (!${s}.has(${t})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+t};`)}if("VldOptional"===f(e)){const r=e.baseValidator;return i.hoist.push(`if (${t} === undefined) { ${i.outParam} = undefined; } else {`),p(r,t,i),void i.hoist.push("}")}if("VldArray"===f(e)){const r=e.config?.itemValidator??e.config?.element;if(!r)return void(i.failed=!0);const s=v(i,"arr"),n=v(i,"i");if("VldObject"===f(r)){if(i.hoist.push(`if (!Array.isArray(${t})) ${i.throwOnFail?"throw":"return"} ${i.invalid};`),i.validateOnly){if(i.hoist.push(`for (let ${n} = 0; ${n} < ${t}.length; ${n}++) {`),p(r,`${t}[${n}]`,i),i.failed)return;return i.hoist.push("}"),void i.hoist.push(`${i.outParam} = true;`)}i.hoist.push(`const ${s} = new Array(${t}.length);`);const e={invalid:i.invalid,outParam:"__slot",scratch:0,hoist:[],failed:!1,skipOutAssign:!0};return e.hoist.push(`for (let ${n} = 0; ${n} < ${t}.length; ${n}++) {`," let __slot;"),p(r,`${t}[${n}]`,e),e.failed?void(i.failed=!0):(e.hoist.push(` ${s}[${n}] = __slot;`,"}"),i.hoist.push(...e.hoist),void i.hoist.push(`${i.outParam} = ${s};`))}const o=v(i,"it");if(i.hoist.push(`if (!Array.isArray(${t})) ${i.throwOnFail?"throw":"return"} ${i.invalid};`),i.validateOnly)return i.hoist.push(`for (let ${n} = 0; ${n} < ${t}.length; ${n}++) {`,` const ${o} = ${t}[${n}];`),p(r,o,i),i.hoist.push("}"),void i.hoist.push(`${i.outParam} = true;`);if(i.hoist.push(`const ${s} = new Array(${t}.length);`,`for (let ${n} = 0; ${n} < ${t}.length; ${n}++) {`),p(r,`${t}[${n}]`,i),i.failed)return;return void i.hoist.push(` ${s}[${n}] = ${t}[${n}];`,"}",`${i.outParam} = ${s};`)}if("VldTuple"===f(e)){const r=e.validators.filter(e=>Boolean(e)),s=e.restValidator,n=v(i,"tup"),o=s?`${t}.length < ${r.length}`:`${t}.length !== ${r.length}`;if(i.hoist.push(`if (!Array.isArray(${t}) || ${o}) ${i.throwOnFail?"throw":"return"} ${i.invalid};`),i.validateOnly){for(let e=0;e<r.length;e++){const s=r[e];if(!s)return void(i.failed=!0);if(p(s,`${t}[${e}]`,i),i.failed)return}if(s){const e=v(i,"i");i.hoist.push(`for (let ${e} = ${r.length}; ${e} < ${t}.length; ${e}++) {`),p(s,`${t}[${e}]`,i),i.hoist.push("}")}return void i.hoist.push(`${i.outParam} = true;`)}i.hoist.push(`const ${n} = new Array(${t}.length);`);for(let e=0;e<r.length;e++){const s=r[e];if(!s)return void(i.failed=!0);const o=v(i,"it");i.hoist.push(`{ const ${o} = ${t}[${e}];`);const a=i.skipOutAssign??!1;i.skipOutAssign=!0,p(s,o,i),i.skipOutAssign=a,i.hoist.push(` ${n}[${e}] = ${o}; }`)}if(s){const e=v(i,"i"),o=v(i,"it");i.hoist.push(`for (let ${e} = ${r.length}; ${e} < ${t}.length; ${e}++) {`,` const ${o} = ${t}[${e}];`);const a=i.skipOutAssign??!1;i.skipOutAssign=!0,p(s,o,i),i.skipOutAssign=a,i.hoist.push(` ${n}[${e}] = ${o}; }`)}return void i.hoist.push(`${i.outParam} = ${n};`)}if("VldObject"===f(e)){const r=e._config?.shape;if(!r)return void(i.failed=!0);const s=v(i,"o");if(i.hoist.push(`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) ${i.throwOnFail?"throw":"return"} ${i.invalid};`),i.validateOnly){for(const e of Object.keys(r)){const s=r[e];if(!s)return void(i.failed=!0);if(p(s,`${t}${/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?`.${e}`:`[${JSON.stringify(e)}]`}`,i),i.failed)return}return void i.hoist.push(`${i.outParam} = true;`)}i.hoist.push(`const ${s} = {};`);for(const e of Object.keys(r)){const n=r[e];if(!n)return void(i.failed=!0);const o=/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?`.${e}`:`[${JSON.stringify(e)}]`,a=v(i,"p");i.hoist.push(`{ const ${a} = ${t}${o};`);const u=i.skipOutAssign??!1;i.skipOutAssign=!0,p(n,a,i),i.skipOutAssign=u,i.hoist.push(` ${s}${o} = ${a}; }`)}return void i.hoist.push(`${i.outParam} = ${s};`)}if("VldRecord"===f(e)){const r=e.keyValidator,s=e.valueValidator,n=v(i,"rec"),o=v(i,"ks"),a=v(i,"i"),u=v(i,"k"),l=v(i,"v");return i.hoist.push(`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) ${i.throwOnFail?"throw":"return"} ${i.invalid};`,`const ${n} = {};`,`const ${o} = Object.keys(${t});`,`for (let ${a} = 0; ${a} < ${o}.length; ${a}++) {`,` let ${u} = ${o}[${a}];`),p(r,u,i),i.hoist.push(` let ${l} = ${t}[${o}[${a}]];`),p(s,l,i),void i.hoist.push(` ${n}[${u}] = ${l};`,"}",""+(i.validateOnly?i.outParam+" = true; ":i.outParam+" = "+n+";"))}if("VldUnion"===f(e)){const t=e.validators.filter(e=>Boolean(e));if(0===t.length)return void(i.failed=!0);const r=v(i,"u");i.hoist.push(`let ${r} = ${i.invalid};`);for(let e=0;e<t.length;e++){const s=t[e],n=f(s);if("VldString"===n){i.hoist.push(`if (typeof value === "string") { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through to next option */ }`);continue}if("VldNumber"===n){i.hoist.push(`if (typeof value === "number" && value === value) { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through */ }`);continue}if("VldBoolean"===n){i.hoist.push(`if (typeof value === "boolean") { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through */ }`);continue}if("VldNull"===n){i.hoist.push(`if (value === null) { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through */ }`);continue}if("VldUndefined"===n){i.hoist.push(`if (value === undefined) { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through */ }`);continue}if("VldLiteral"===n){const e=s._values||[];if(1===e.length){const t=e[0],s="number"==typeof t&&Number.isNaN(t)?"NaN":JSON.stringify(t);i.hoist.push(`if (Object.is(${s}, value)) { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through */ }`);continue}}const o={invalid:i.invalid,outParam:r,scratch:0,hoist:[],failed:!1,skipOutAssign:!0};if(p(s,"value",o),o.failed)return void(i.failed=!0);i.hoist.push(`${r} = ((value) => {`,...o.hoist.map(e=>" "+e)," return value;","})(value);",`if (${r} !== ${i.invalid}) { /* matched */ }`)}return void i.hoist.push(`if (${r} === ${i.invalid}) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = ${r};`)}i.failed=!0}else i.hoist.push((i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+t)+";");else i.hoist.push(`if (${t} !== undefined) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = undefined;`);else i.hoist.push(`if (${t} !== null) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = null;`);else i.hoist.push(`{ const __v = ${t}; if (!(__v instanceof Date) || __v.getTime() !== __v.getTime()) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = __v; }`)}else i.hoist.push(`if (typeof ${t} !== "boolean") ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+t};`)}}function _(e,t){if(!e||"function"!=typeof e.parse)return null;const i=!!t?.validateOnly,r={invalid:"__INV",outParam:i?"__ok":"__out",scratch:0,hoist:[],failed:!1,validateOnly:i};if(r.hoist.push(i?"let __ok;":"let __out;"),p(e,"value",r),r.failed)return"1"===process.env.VLD_COMPILE_DEBUG&&console.error("[compile] failed to lower schema; partial body:\n"+r.hoist.join("\n")),null;r.hoist.push(i?"return __ok;":"return __out;");const s=r.hoist.join("\n"),n=new Function("value",r.invalid,s),o=e=>n(e,$);return Object.defineProperty(o,"__vld_compiled",{value:!0,enumerable:!1}),o}function g(e){return _(e,{validateOnly:!0})}function m(e,t,i){const r=e.parse.bind(e),s=e.safeParse.bind(e),n=$,o=i??t;return e.parse=e=>o(e)===n?r(e):e,e.safeParse=e=>o(e)===n?s(e):{success:!0,data:e},Object.defineProperty(e,"_zod",{value:{bag:{validator:t,validatorValidate:i}},enumerable:!1,configurable:!0}),e}exports.COMPILE_INVALID=$,exports.ZodCompileAsyncError=h,exports.ZodCompileError=c,exports.ZodCompileUnsupportedError=d,exports._ZodCompileAsyncError=h,exports._ZodCompileUnsupportedError=d,exports.applyCompiled=m,exports.compile=function(e,t){const i=e?._zod?.bag?.validator;if(i)return e;const r=function(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}(e);if(t?.JITless)return Object.defineProperty(r,"_zod",{value:{bag:{}},enumerable:!1,configurable:!0}),r;const s=g(r);return s?m(r,s,s):r},exports.compileFn=_,exports.compileFnValidate=g,exports.getDiscriminatedOption=function(e,t,i){if(null===i||"object"!=typeof i||Array.isArray(i))return;const r=i[e];for(const i of t){const t=i._config?.shape;if(!t)continue;const s=t[e];if(!s)continue;const n=s._values||[];for(const e of n)if(Object.is(e,r))return i}},exports.memoizer=e=>{const t=new WeakMap;return i=>{const r=t.get(i);if(void 0!==r)return r;const s=e(i);return t.set(i,s),s}},exports.properties=function(e){const t={};for(const i of Object.keys(e))t[i]=e[i].optional();return a.VldObject.create(t)},exports.toZod=function(c){if(c instanceof e.VldBase)return c;if(null===c)return o.VldNull.create();switch(null===c?"null":Array.isArray(c)?"array":typeof c){case"string":return t.VldString.create();case"number":return i.VldNumber.create();case"boolean":return r.VldBoolean.create();case"bigint":return s.VldBigInt.create();case"undefined":return n.VldUndefined.create();case"array":return u.VldArray.create(l.VldUnknown.create());case"object":return a.VldObject.create(c);default:return l.VldUnknown.create()}},exports.validate=function(e,t){const i=e?._zod?.bag?.validatorValidate??e?._zod?.bag?.validator;if(i)try{return i(t)!==$}catch{return!1}const r=e.safeParse(t);return Boolean(r?.success)},exports.validateAsync=async function(e,t){const i=e?._zod?.bag?.validatorValidate??e?._zod?.bag?.validator;if(i)try{return i(t)!==$}catch{return!1}const r=await e.safeParseAsync(t);return Boolean(r?.success)};
|
package/dist/cjs/errors.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./pigment.cjs"),r=require("./chunks/errors-core-
|
|
1
|
+
"use strict";var e=require("./pigment.cjs"),r=require("./chunks/errors-core-C0mA6tfa.cjs");function t(r,t={}){const{colored:s=!0,theme:o=e.vldTheme,includeCode:n=!1,includeDetails:i=!1}=t,p=[];for(const e of r.issues){let r=`${s?o.symbol("✖"):"✖"} ${s?o.error(e.message):e.message}`;if(n){r+=` ${s?o.muted(`[${e.code}]`):`[${e.code}]`}`}if(e.path.length>0){const t=e.path.map((e,r)=>{if("string"==typeof e){const t=0===r?e:`.${e}`;return s?o.path(t):t}{const r=`[${e}]`;return s?o.path(r):r}}).join("");r+=`\n ${s?o.muted("→ at "):"→ at "}${t}`}if(i){if(e.expected){r+=`\n ${s?o.muted("expected: ")+o.success(e.expected):`expected: ${e.expected}`}`}if(e.received){r+=`\n ${s?o.muted("received: ")+o.warning(e.received):`received: ${e.received}`}`}}p.push(r)}return p.join("\n")}exports.VldError=r.VldError,exports.createIssue=function(e,r,t,s){return{code:e,path:[...r],message:t,...s}},exports.flattenError=function(e){const r=[],t={};for(const s of e.issues)if(0===s.path.length)r.push(s.message);else{const e=s.path[0].toString();t[e]||(t[e]=[]),t[e].push(s.message)}return{formErrors:r,fieldErrors:t}},exports.getValueType=function(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":e instanceof Date?"date":typeof e},exports.prettifyError=t,exports.prettifyErrorColored=function(e,r={}){return t(e,{...r,colored:!0})},exports.prettifyErrorPlain=function(e,r={}){return t(e,{...r,colored:!1})},exports.treeifyError=function(e){const r={errors:[]};for(const t of e.issues){let e=r;const s=t.path;for(let r=0;r<s.length;r++){const o=s[r],n=r===s.length-1;if("string"==typeof o)e.properties||(e.properties={}),e.properties[o]||(e.properties[o]={errors:[]}),n?e.properties[o].errors.push(t.message):e=e.properties[o];else if("number"==typeof o){for(e.items||(e.items=[]);e.items.length<=o;)e.items.push(void 0);e.items[o]||(e.items[o]={errors:[]}),n?e.items[o].errors.push(t.message):e=e.items[o]}}0===s.length&&r.errors.push(t.message)}return r};
|