zod-compiler 1.28.0 → 2.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/README.md +176 -148
- package/dist/core/codegen/build-path.d.ts +12 -1
- package/dist/core/codegen/build-path.d.ts.map +1 -1
- package/dist/core/codegen/build-path.js +102 -21
- package/dist/core/codegen/build-path.js.map +1 -1
- package/dist/core/codegen/context.d.ts +31 -16
- package/dist/core/codegen/context.d.ts.map +1 -1
- package/dist/core/codegen/context.js +43 -18
- package/dist/core/codegen/context.js.map +1 -1
- package/dist/core/codegen/emit-issue.d.ts +17 -20
- package/dist/core/codegen/emit-issue.d.ts.map +1 -1
- package/dist/core/codegen/emit-issue.js +13 -13
- package/dist/core/codegen/emit-issue.js.map +1 -1
- package/dist/core/codegen/index.d.ts.map +1 -1
- package/dist/core/codegen/index.js +9 -7
- package/dist/core/codegen/index.js.map +1 -1
- package/dist/core/codegen/issue-decls.d.ts +83 -7
- package/dist/core/codegen/issue-decls.d.ts.map +1 -1
- package/dist/core/codegen/issue-decls.js +93 -10
- package/dist/core/codegen/issue-decls.js.map +1 -1
- package/dist/core/codegen/schemas/array.js +1 -1
- package/dist/core/codegen/schemas/array.js.map +1 -1
- package/dist/core/codegen/schemas/bigint.d.ts.map +1 -1
- package/dist/core/codegen/schemas/bigint.js +15 -4
- package/dist/core/codegen/schemas/bigint.js.map +1 -1
- package/dist/core/codegen/schemas/catch.d.ts.map +1 -1
- package/dist/core/codegen/schemas/catch.js +3 -2
- package/dist/core/codegen/schemas/catch.js.map +1 -1
- package/dist/core/codegen/schemas/discriminated-union.d.ts +6 -2
- package/dist/core/codegen/schemas/discriminated-union.d.ts.map +1 -1
- package/dist/core/codegen/schemas/discriminated-union.js +16 -56
- package/dist/core/codegen/schemas/discriminated-union.js.map +1 -1
- package/dist/core/codegen/schemas/effect.d.ts.map +1 -1
- package/dist/core/codegen/schemas/effect.js +4 -2
- package/dist/core/codegen/schemas/effect.js.map +1 -1
- package/dist/core/codegen/schemas/file.js +2 -8
- package/dist/core/codegen/schemas/file.js.map +1 -1
- package/dist/core/codegen/schemas/number.js +4 -3
- package/dist/core/codegen/schemas/number.js.map +1 -1
- package/dist/core/codegen/schemas/object.d.ts +11 -1
- package/dist/core/codegen/schemas/object.d.ts.map +1 -1
- package/dist/core/codegen/schemas/object.js +58 -14
- package/dist/core/codegen/schemas/object.js.map +1 -1
- package/dist/core/codegen/schemas/readonly.d.ts.map +1 -1
- package/dist/core/codegen/schemas/readonly.js.map +1 -1
- package/dist/core/codegen/schemas/record.d.ts.map +1 -1
- package/dist/core/codegen/schemas/record.js +8 -3
- package/dist/core/codegen/schemas/record.js.map +1 -1
- package/dist/core/codegen/schemas/sizeable.d.ts +49 -3
- package/dist/core/codegen/schemas/sizeable.d.ts.map +1 -1
- package/dist/core/codegen/schemas/sizeable.js +101 -8
- package/dist/core/codegen/schemas/sizeable.js.map +1 -1
- package/dist/core/codegen/schemas/string-bool.d.ts +12 -1
- package/dist/core/codegen/schemas/string-bool.d.ts.map +1 -1
- package/dist/core/codegen/schemas/string-bool.js +19 -4
- package/dist/core/codegen/schemas/string-bool.js.map +1 -1
- package/dist/core/codegen/schemas/string.d.ts.map +1 -1
- package/dist/core/codegen/schemas/string.js +60 -26
- package/dist/core/codegen/schemas/string.js.map +1 -1
- package/dist/core/codegen/schemas/tuple.d.ts +14 -11
- package/dist/core/codegen/schemas/tuple.d.ts.map +1 -1
- package/dist/core/codegen/schemas/tuple.js +99 -49
- package/dist/core/codegen/schemas/tuple.js.map +1 -1
- package/dist/core/codegen/well-known-regex.d.ts +26 -1
- package/dist/core/codegen/well-known-regex.d.ts.map +1 -1
- package/dist/core/codegen/well-known-regex.js +31 -4
- package/dist/core/codegen/well-known-regex.js.map +1 -1
- package/dist/core/extract/checks.d.ts.map +1 -1
- package/dist/core/extract/checks.js +1 -0
- package/dist/core/extract/checks.js.map +1 -1
- package/dist/core/extract/extractors/intersection.js +21 -6
- package/dist/core/extract/extractors/intersection.js.map +1 -1
- package/dist/core/extract/extractors/object.d.ts.map +1 -1
- package/dist/core/extract/extractors/object.js +25 -9
- package/dist/core/extract/extractors/object.js.map +1 -1
- package/dist/core/extract/extractors/optional.d.ts.map +1 -1
- package/dist/core/extract/extractors/optional.js +1 -28
- package/dist/core/extract/extractors/optional.js.map +1 -1
- package/dist/core/extract/extractors/record.js +9 -3
- package/dist/core/extract/extractors/record.js.map +1 -1
- package/dist/core/extract/extractors/tuple.d.ts.map +1 -1
- package/dist/core/extract/extractors/tuple.js +16 -20
- package/dist/core/extract/extractors/tuple.js.map +1 -1
- package/dist/core/extract/types.d.ts +16 -8
- package/dist/core/extract/types.d.ts.map +1 -1
- package/dist/core/iife.d.ts +2 -1
- package/dist/core/iife.d.ts.map +1 -1
- package/dist/core/iife.js +2 -1
- package/dist/core/iife.js.map +1 -1
- package/dist/core/types.d.ts +70 -21
- package/dist/core/types.d.ts.map +1 -1
- package/dist/jit.d.ts.map +1 -1
- package/dist/jit.js +47 -12
- package/dist/jit.js.map +1 -1
- package/dist/runtime.d.ts +4 -1
- package/dist/runtime.js +14 -11
- package/package.json +2 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** All issue factory declarations indexed by helper name. */
|
|
2
2
|
const ISSUE_DECLS = {
|
|
3
3
|
__zcTS: "function __zcTS(m,o,i,inp,p,msg){var r={origin:o,code:\"too_small\",minimum:m,inclusive:i,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}",
|
|
4
|
-
|
|
4
|
+
__zcTSt: "function __zcTSt(m,o,inp,p,msg){var r={code:\"too_small\",minimum:m,inclusive:true,origin:o,input:inp,path:p,continue:false};if(msg!==undefined)r.message=msg;return r;}",
|
|
5
5
|
__zcTSx: "function __zcTSx(m,o,inp,p,msg){var r={origin:o,code:\"too_small\",minimum:m,inclusive:true,exact:true,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}",
|
|
6
6
|
__zcTB: "function __zcTB(m,o,i,inp,p,msg){var r={origin:o,code:\"too_big\",maximum:m,inclusive:i,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}",
|
|
7
7
|
__zcTBt: "function __zcTBt(m,o,inp,p,msg){var r={code:\"too_big\",maximum:m,inclusive:true,origin:o,input:inp,path:p,continue:false};if(msg!==undefined)r.message=msg;return r;}",
|
|
@@ -14,10 +14,17 @@ const ISSUE_DECLS = {
|
|
|
14
14
|
};
|
|
15
15
|
/**
|
|
16
16
|
* Float-safe remainder — byte-for-byte port of zod's util.floatSafeRemainder.
|
|
17
|
-
* Raw `%` mis-rejects valid multiples of decimal steps (0.3 % 0.1 !== 0)
|
|
18
|
-
*
|
|
17
|
+
* Raw `%` mis-rejects valid multiples of decimal steps (0.3 % 0.1 !== 0).
|
|
18
|
+
*
|
|
19
|
+
* zod 4.5 REPLACED the decimal-scaling implementation this once mirrored with a
|
|
20
|
+
* ratio-and-tolerance one, and the two disagree in both directions: the old form
|
|
21
|
+
* accepted `1e-7` as a multiple of 3 (its `toFixed` scaling collapsed the value
|
|
22
|
+
* to 0) and rejected `1e21` (where `toFixed` yields exponential notation and
|
|
23
|
+
* `parseInt` then reads 1). The tolerance is 4x epsilon because `val` and `step`
|
|
24
|
+
* each round to a double before the division rounds again, so a true decimal
|
|
25
|
+
* multiple's quotient can sit up to 1.5 scaled epsilons from the integer.
|
|
19
26
|
*/
|
|
20
|
-
const ZC_FSR_DECL = "function __zcFsr(v,s){var
|
|
27
|
+
const ZC_FSR_DECL = "function __zcFsr(v,s){var r=v/s;var q=Math.round(r);var t=4*Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-q)<t?0:r-q;}";
|
|
21
28
|
/**
|
|
22
29
|
* Hoisted `Object.prototype.hasOwnProperty` reference. Record fast/slow paths
|
|
23
30
|
* iterate keys with `for(k in o)` (no `Object.keys` array allocation) and guard
|
|
@@ -51,12 +58,54 @@ const ZC_HOP_DECL = "const __zcHop=Object.prototype.hasOwnProperty;";
|
|
|
51
58
|
* than `Object.getPrototypeOf(o) === Object.prototype` is what lets a plain
|
|
52
59
|
* object from another realm (a vm context, an iframe) still count as plain.
|
|
53
60
|
*
|
|
61
|
+
* `c===Object` is a short-cut, not a fourth rule: it is exactly the case where
|
|
62
|
+
* zod's remaining steps are foregone — `Object.prototype` is an object and has
|
|
63
|
+
* its own `isPrototypeOf` — so the answer is `true` either way. It is also the
|
|
64
|
+
* case every ordinary record takes (an object literal, `JSON.parse` output, a
|
|
65
|
+
* `Map`-free DTO), and taking it saves the `prototype` load and the
|
|
66
|
+
* `hasOwnProperty` call: measured 9.6 → 5.7 ns on a monomorphic record and
|
|
67
|
+
* 15.7 → 9.2 ns across 16 shapes, i.e. 22% of a five-key record's whole parse.
|
|
68
|
+
* A plain object from another realm has a different `Object` and simply takes
|
|
69
|
+
* the long road to the same verdict, as before.
|
|
70
|
+
*
|
|
54
71
|
* Self-contained (`Object.prototype.hasOwnProperty` spelled out rather than
|
|
55
72
|
* reusing `__zcHop`) so inline mode can emit this decl alone: `emitRuntimeHelper`
|
|
56
73
|
* pushes only the decl it is asked for, and a helper that closed over another
|
|
57
74
|
* name would dangle wherever that one was not also emitted.
|
|
58
75
|
*/
|
|
59
|
-
const ZC_PLAIN_DECL = "function __zcPlain(o){if(typeof o!==\"object\"||o===null||Array.isArray(o))return false;var c=o.constructor;if(c===undefined||typeof c!==\"function\")return true;var p=c.prototype;if(typeof p!==\"object\"||p===null||Array.isArray(p))return false;return Object.prototype.hasOwnProperty.call(p,\"isPrototypeOf\");}";
|
|
76
|
+
const ZC_PLAIN_DECL = "function __zcPlain(o){if(typeof o!==\"object\"||o===null||Array.isArray(o))return false;var c=o.constructor;if(c===Object||c===undefined||typeof c!==\"function\")return true;var p=c.prototype;if(typeof p!==\"object\"||p===null||Array.isArray(p))return false;return Object.prototype.hasOwnProperty.call(p,\"isPrototypeOf\");}";
|
|
77
|
+
/**
|
|
78
|
+
* `z.email()`'s default validator, `regexes.email`, as a single linear scan.
|
|
79
|
+
*
|
|
80
|
+
* Zod's pattern is
|
|
81
|
+
* `^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$`,
|
|
82
|
+
* and even its lookahead-free rewrite (EMAIL_FAST_REGEX_SOURCE) backtracks at
|
|
83
|
+
* every dot it fails to find: `(?:[X]+\.)*` re-tries the run one character
|
|
84
|
+
* shorter each time, and the domain's `(?:label\.)+` does the same over the
|
|
85
|
+
* TLD. Written as a scanner the language is:
|
|
86
|
+
*
|
|
87
|
+
* local — `[A-Za-z0-9_'+.-]+`, no leading `.`, no `..`, and the character
|
|
88
|
+
* before `@` is neither `.` nor `'` (that last is the `[A-Za-z0-9_+-]`
|
|
89
|
+
* the pattern demands there);
|
|
90
|
+
* domain — one or more labels `[A-Za-z0-9][A-Za-z0-9-]*` each ending in `.`,
|
|
91
|
+
* then a TLD of two or more letters running to the end.
|
|
92
|
+
*
|
|
93
|
+
* A trailing `\n` is not accepted: the pattern has no `m` flag, so its `$`
|
|
94
|
+
* matches only at the end of input, and the scan reads to `length`.
|
|
95
|
+
*
|
|
96
|
+
* Measured against the fast regex on V8: 32 → 16 ns for `alice@example.com`,
|
|
97
|
+
* 48 → 40 for `bob_smith-99@mail-server.io`, 39 → 20 for a non-address, and a
|
|
98
|
+
* tie from ~35 characters up (the regex's per-character work is cheaper than a
|
|
99
|
+
* `charCodeAt` loop's; its fixed dispatch cost is what the scanner avoids). A
|
|
100
|
+
* lookbehind rewrite runs about as fast but needs ES2018 regex support, which
|
|
101
|
+
* the CLI's React Native / Hermes and older-Safari consumers cannot assume.
|
|
102
|
+
*
|
|
103
|
+
* Equivalence to zod's regex — every string, both verdicts — is pinned by
|
|
104
|
+
* tests/core/codegen/email-scanner.test.ts. Reached only behind a `typeof`
|
|
105
|
+
* string guard, like the `.test()` it replaces; issue sites keep reporting
|
|
106
|
+
* zod's own pattern string (see `emitRegexSourceString`).
|
|
107
|
+
*/
|
|
108
|
+
const ZC_EMAIL_DECL = "function __zcEmail(s){var n=s.length,i=0,c,p=46;for(;;){if(i===n)return false;c=s.charCodeAt(i);if(c===64)break;if(c===46){if(p===46)return false;}else if(!((c>=97&&c<=122)||(c>=65&&c<=90)||(c>=48&&c<=57)||c===95||c===39||c===43||c===45))return false;p=c;i++;}if(p===46||p===39)return false;var l=++i,d=0,t=true;for(;i<n;i++){c=s.charCodeAt(i);if((c>=97&&c<=122)||(c>=65&&c<=90))continue;if(c===46){if(i===l)return false;d++;l=i+1;t=true;continue;}if((c>=48&&c<=57)||c===45){if(c===45&&i===l)return false;t=false;continue;}return false;}return d>0&&t&&n-l>=2;}";
|
|
60
109
|
/**
|
|
61
110
|
* Ports of `util.getLengthableOrigin` / `util.getSizableOrigin` — the `origin` a
|
|
62
111
|
* length/size check puts on its issue, computed from the RUNTIME INPUT rather
|
|
@@ -75,6 +124,31 @@ const ZC_PLAIN_DECL = "function __zcPlain(o){if(typeof o!==\"object\"||o===null|
|
|
|
75
124
|
* not run in, and not one worth reproducing a crash for.
|
|
76
125
|
*/
|
|
77
126
|
const ZC_LENGTH_ORIGIN_DECL = "function __zcLo(v){return Array.isArray(v)?\"array\":typeof v===\"string\"?\"string\":\"unknown\";}";
|
|
127
|
+
/**
|
|
128
|
+
* Drop an own `__proto__` from a container the parse hands back BY REFERENCE.
|
|
129
|
+
*
|
|
130
|
+
* zod never lets the key into an output: `$ZodObject`'s shape loop strips a
|
|
131
|
+
* declared one, `handleCatchall` skips an undeclared one, and `$ZodRecord` skips
|
|
132
|
+
* it while copying — all so the assignment into their fresh `{}` cannot replace
|
|
133
|
+
* the result's prototype. A compiled loose/catchall object or record IS its
|
|
134
|
+
* input, so the key has to be removed here instead; leaving it made
|
|
135
|
+
* `Object.assign({}, parsed)` a prototype-pollution sink, since [[Set]] runs the
|
|
136
|
+
* inherited setter the spread that built the value did not.
|
|
137
|
+
*
|
|
138
|
+
* Copies rather than editing in place: the divergence note promises the caller
|
|
139
|
+
* its own container back, not one with a key silently deleted from it. The
|
|
140
|
+
* common object has no such key and is returned untouched, so the cost is one
|
|
141
|
+
* `hasOwnProperty` call.
|
|
142
|
+
*/
|
|
143
|
+
const ZC_PROTO_SCRUB_DECL = "function __zcPs(o){if(!Object.prototype.hasOwnProperty.call(o,\"__proto__\"))return o;var c={...o};delete c[\"__proto__\"];return c;}";
|
|
144
|
+
/**
|
|
145
|
+
* Code points in a string — zod's `util.codePointLength`, verbatim. A surrogate
|
|
146
|
+
* pair counts once and a lone surrogate as itself. The regex probe is the fast
|
|
147
|
+
* exit for a string with no astral characters, and the hand-rolled loop avoids
|
|
148
|
+
* the allocating string iterator. Only reached from a length check whose
|
|
149
|
+
* UTF-16 count leaves the verdict in doubt (see stringLengthTests).
|
|
150
|
+
*/
|
|
151
|
+
const ZC_CPL_DECL = "function __zcCpl(s){var n=s.length;if(!/[\\uD800-\\uDBFF]/.test(s))return n;var c=n;for(var i=0;i<n-1;i++){if((s.charCodeAt(i)&0xfc00)===0xd800&&(s.charCodeAt(i+1)&0xfc00)===0xdc00){c--;i++;}}return c;}";
|
|
78
152
|
const ZC_SIZE_ORIGIN_DECL = "function __zcSo(v){return v instanceof Set?\"set\":v instanceof Map?\"map\":(typeof File!==\"undefined\"&&v instanceof File)?\"file\":\"unknown\";}";
|
|
79
153
|
/**
|
|
80
154
|
* Issue codes zod raises from a schema's `_zod.parse` rather than from a check,
|
|
@@ -86,6 +160,11 @@ const ZC_SIZE_ORIGIN_DECL = "function __zcSo(v){return v instanceof Set?\"set\":
|
|
|
86
160
|
* compiled path anyway — so classifying by code alone is exact for generated
|
|
87
161
|
* issues.
|
|
88
162
|
*
|
|
163
|
+
* `unrecognized_keys` is the one parse-level issue zod pushes WITH
|
|
164
|
+
* `continue: true`: it describes the shape of the input rather than the
|
|
165
|
+
* validity of the parsed value, so the parse still fails but the object's own
|
|
166
|
+
* refines run first and a union does not count the option as aborted.
|
|
167
|
+
*
|
|
89
168
|
* Read by {@link ZC_AB_DECL} and by the union's option-pruning loop, which
|
|
90
169
|
* applies the same rule inline over a per-option issue array.
|
|
91
170
|
*/
|
|
@@ -93,7 +172,6 @@ const ABORTING_ISSUE_CODES = [
|
|
|
93
172
|
"invalid_type",
|
|
94
173
|
"invalid_value",
|
|
95
174
|
"invalid_union",
|
|
96
|
-
"unrecognized_keys",
|
|
97
175
|
"invalid_key",
|
|
98
176
|
"invalid_element"
|
|
99
177
|
];
|
|
@@ -184,8 +262,10 @@ const ZC_CUSTOM_OK_DECL = "function __zcCu(f,v){var r=f(v);if(r&&typeof r.then==
|
|
|
184
262
|
/**
|
|
185
263
|
* superRefine slow-path merge: run the callback, then move its issues onto the
|
|
186
264
|
* validator's list the way zod's finalizeIssue does — the node's path prefixed
|
|
187
|
-
* onto any path the user supplied,
|
|
188
|
-
* dropped (they are zod bookkeeping, deleted before the issue is user-visible)
|
|
265
|
+
* onto any path the user supplied, the internal `inst`/`continue` fields
|
|
266
|
+
* dropped (they are zod bookkeeping, deleted before the issue is user-visible),
|
|
267
|
+
* and the owning schema's static message `m` applied to an issue that carries
|
|
268
|
+
* none of its own, since zod stamps the owner onto every issue a check raises.
|
|
189
269
|
*
|
|
190
270
|
* Returns the payload, so the caller can write `.value` back (the callback may
|
|
191
271
|
* have rewritten it) and read `.aborted`. Aborted is set when any issue aborts
|
|
@@ -196,7 +276,7 @@ const ZC_CUSTOM_OK_DECL = "function __zcCu(f,v){var r=f(v);if(r&&typeof r.then==
|
|
|
196
276
|
* failing only through superRefine would be surfaced directly instead of inside
|
|
197
277
|
* `invalid_union`.
|
|
198
278
|
*/
|
|
199
|
-
const ZC_SR_DECL = "function __zcSr(f,v,p,e){var q={value:v,issues:[]};__zcSrRun(f,q);for(var i=0;i<q.issues.length;i++){var s=q.issues[i],t={};for(var k in s){if(k!==\"inst\"&&k!==\"continue\")t[k]=s[k];}if(s.continue!==true)q.aborted=true;t.path=s.path&&s.path.length?p.concat(s.path):p;e.push(t);}return q;}";
|
|
279
|
+
const ZC_SR_DECL = "function __zcSr(f,v,p,e,m){var q={value:v,issues:[]};__zcSrRun(f,q);for(var i=0;i<q.issues.length;i++){var s=q.issues[i],t={};for(var k in s){if(k!==\"inst\"&&k!==\"continue\")t[k]=s[k];}if(s.continue!==true)q.aborted=true;t.path=s.path&&s.path.length?p.concat(s.path):p;if(t.message===undefined&&m!==undefined)t.message=m;e.push(t);}return q;}";
|
|
200
280
|
/** Non-issue runtime helper declarations hosted in the virtual module. */
|
|
201
281
|
const RUNTIME_HELPER_DECLS = {
|
|
202
282
|
__zcAb: ZC_AB_DECL,
|
|
@@ -205,6 +285,9 @@ const RUNTIME_HELPER_DECLS = {
|
|
|
205
285
|
__zcHop: ZC_HOP_DECL,
|
|
206
286
|
__zcLo: ZC_LENGTH_ORIGIN_DECL,
|
|
207
287
|
__zcSo: ZC_SIZE_ORIGIN_DECL,
|
|
288
|
+
__zcCpl: ZC_CPL_DECL,
|
|
289
|
+
__zcEmail: ZC_EMAIL_DECL,
|
|
290
|
+
__zcPs: ZC_PROTO_SCRUB_DECL,
|
|
208
291
|
__zcPlain: ZC_PLAIN_DECL,
|
|
209
292
|
__zcPfx: ZC_PFX_DECL,
|
|
210
293
|
__zcCu: ZC_CUSTOM_OK_DECL,
|
|
@@ -212,6 +295,6 @@ const RUNTIME_HELPER_DECLS = {
|
|
|
212
295
|
__zcSrOk: ZC_SR_OK_DECL
|
|
213
296
|
};
|
|
214
297
|
//#endregion
|
|
215
|
-
export { ISSUE_DECLS, RUNTIME_HELPER_DECLS, ZC_AB_DECL, ZC_CUSTOM_OK_DECL, ZC_FSR_DECL, ZC_FZ_DECL, ZC_HOP_DECL, ZC_LENGTH_ORIGIN_DECL, ZC_PFX_DECL, ZC_PLAIN_DECL, ZC_SIZE_ORIGIN_DECL, ZC_SR_DECL, ZC_SR_OK_DECL, ZC_SR_RUN_DECL, abortingCodeTest, propertyKeyTest };
|
|
298
|
+
export { ISSUE_DECLS, RUNTIME_HELPER_DECLS, ZC_AB_DECL, ZC_CPL_DECL, ZC_CUSTOM_OK_DECL, ZC_EMAIL_DECL, ZC_FSR_DECL, ZC_FZ_DECL, ZC_HOP_DECL, ZC_LENGTH_ORIGIN_DECL, ZC_PFX_DECL, ZC_PLAIN_DECL, ZC_PROTO_SCRUB_DECL, ZC_SIZE_ORIGIN_DECL, ZC_SR_DECL, ZC_SR_OK_DECL, ZC_SR_RUN_DECL, abortingCodeTest, propertyKeyTest };
|
|
216
299
|
|
|
217
300
|
//# sourceMappingURL=issue-decls.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"issue-decls.js","names":[],"sources":["../../../src/core/codegen/issue-decls.ts"],"sourcesContent":["/**\n * Issue factory function bodies (statement form).\n *\n * These functions produce the same `{code, ...}` shapes that lean-mode\n * generated code would otherwise inline at every check site.\n * Hosted in \"virtual:zod-compiler/runtime\" and called as `__zcTS(...)` etc.\n *\n * Argument convention (positional, kept short to minimize call-site bytes):\n * __zcTS(minimum, origin, inclusive, input, path, msg?) — too_small\n * __zcTSn(minimum, origin, input, path, msg?) — too_small with NO `inclusive` key\n * __zcTBt(maximum, origin, input, path, msg?) — too_big, tuple key order\n * __zcTB(maximum, origin, inclusive, input, path, msg?) — too_big\n * __zcIT(expected, input, path, msg?) — invalid_type\n * __zcITc(expected, input, path, msg?) — invalid_type, `code` first\n * __zcIF(origin, format, input, path, extra?, msg?) — invalid_format (extra merged into result)\n * __zcIV(values, input, path, extra?, msg?) — invalid_value (extra merged into result)\n * __zcUK(keys, input, path, msg?) — unrecognized_keys\n *\n * The trailing msg argument carries a static custom error message; when\n * absent, the __zcFin finalizer applies the configured locale default.\n *\n * KEY ORDER IS PART OF THE CONTRACT. `ZodError.message` is\n * `JSON.stringify(issues, …, 2)`, so the order these factories insert keys in is\n * printed verbatim in the message every consumer logs, snapshots or serializes.\n * Each literal below therefore reproduces the order of the corresponding\n * `payload.issues.push({…})` in zod, which is irregular by type — `too_small`\n * from a check leads with `origin` while the same code from a tuple's length\n * branch leads with `code` — and every factory writes `message` LAST, because\n * zod's `finalizeIssue` assigns it after the fact (`full.message = …`) even for\n * a custom message baked into the check's error map.\n */\n\nconst ZC_TS_DECL =\n 'function __zcTS(m,o,i,inp,p,msg){var r={origin:o,code:\"too_small\",minimum:m,inclusive:i,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\n/**\n * too_small with the `inclusive` key ABSENT, not false. $ZodTuple's under-length\n * branch pushes `{ code: \"too_small\", minimum: items.length }` and nothing else\n * — the over-length branch of the same ternary is the one that spells out\n * `inclusive: true` — so the tuple's issue must not carry the key at all.\n * Separate from __zcTS because the value cannot express absence.\n */\nconst ZC_TS_NO_INCLUSIVE_DECL =\n 'function __zcTSn(m,o,inp,p,msg){var r={code:\"too_small\",minimum:m,origin:o,input:inp,path:p,continue:false};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_TS_EXACT_DECL =\n 'function __zcTSx(m,o,inp,p,msg){var r={origin:o,code:\"too_small\",minimum:m,inclusive:true,exact:true,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_TB_DECL =\n 'function __zcTB(m,o,i,inp,p,msg){var r={origin:o,code:\"too_big\",maximum:m,inclusive:i,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\n/**\n * too_big in the TUPLE over-length key order. $ZodTuple spreads\n * `{ code, maximum, inclusive }` and appends `origin` after `input`/`inst`, so\n * its `origin` trails `inclusive` where every check-created size issue leads\n * with it. Its under-length sibling is __zcTSn.\n */\nconst ZC_TB_TUPLE_DECL =\n 'function __zcTBt(m,o,inp,p,msg){var r={code:\"too_big\",maximum:m,inclusive:true,origin:o,input:inp,path:p,continue:false};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_TB_EXACT_DECL =\n 'function __zcTBx(m,o,inp,p,msg){var r={origin:o,code:\"too_big\",maximum:m,inclusive:true,exact:true,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_IT_DECL =\n 'function __zcIT(e,inp,p,msg){var r={expected:e,code:\"invalid_type\",input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\n/**\n * invalid_type with `code` ahead of `expected`. Every schema in zod spells this\n * issue `{ expected, code }` — except `$ZodDiscriminatedUnion`, whose\n * non-object guard writes `{ code, expected }`. One literal, one key order, and\n * it shows up in `ZodError.message`.\n */\nconst ZC_IT_CODE_FIRST_DECL =\n 'function __zcITc(e,inp,p,msg){var r={code:\"invalid_type\",expected:e,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\n/**\n * `o` is the leading `origin`, present only for the formats whose issue carries\n * one: `$ZodCheckStringFormat`'s default pattern check and the regex /\n * includes / starts_with / ends_with checks all lead with `origin: \"string\"`,\n * while `z.url()`'s own pushes and every `$ZodCustomStringFormat` omit it\n * entirely. `extra` holds the per-format tail (`pattern`, `includes`, `prefix`,\n * `suffix`, `note`) and is merged BEFORE input/path so it lands where zod\n * writes it.\n */\nconst ZC_IF_DECL =\n 'function __zcIF(o,f,inp,p,extra,msg){var r=o===undefined?{code:\"invalid_format\",format:f}:{origin:o,code:\"invalid_format\",format:f};if(extra)Object.assign(r,extra);r.input=inp;r.path=p;if(msg!==undefined)r.message=msg;return r;}';\n\n/**\n * `extra` carries the per-producer fields: enum and literal push `values` only,\n * while z.stringbool()'s codec transform also pushes `expected: \"stringbool\"`.\n * Merged the same way __zcIF merges its own.\n */\nconst ZC_IV_DECL =\n 'function __zcIV(values,inp,p,extra,msg){var r={code:\"invalid_value\"};if(extra)Object.assign(r,extra);r.values=values;r.input=inp;r.path=p;if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_UK_DECL =\n 'function __zcUK(k,inp,p,msg){var r={code:\"unrecognized_keys\",keys:k,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\n/** All issue factory declarations indexed by helper name. */\nexport const ISSUE_DECLS: Readonly<Record<string, string>> = {\n __zcTS: ZC_TS_DECL,\n __zcTSn: ZC_TS_NO_INCLUSIVE_DECL,\n __zcTSx: ZC_TS_EXACT_DECL,\n __zcTB: ZC_TB_DECL,\n __zcTBt: ZC_TB_TUPLE_DECL,\n __zcTBx: ZC_TB_EXACT_DECL,\n __zcIT: ZC_IT_DECL,\n __zcITc: ZC_IT_CODE_FIRST_DECL,\n __zcIF: ZC_IF_DECL,\n __zcIV: ZC_IV_DECL,\n __zcUK: ZC_UK_DECL,\n};\n\n/**\n * Float-safe remainder — byte-for-byte port of zod's util.floatSafeRemainder.\n * Raw `%` mis-rejects valid multiples of decimal steps (0.3 % 0.1 !== 0);\n * zod scales both operands to integers by their decimal-place count first.\n */\nexport const ZC_FSR_DECL =\n 'function __zcFsr(v,s){var vd=((\"\"+v).split(\".\")[1]||\"\").length;var ss=\"\"+s;var sd=(ss.split(\".\")[1]||\"\").length;if(sd===0&&/\\\\d?e-\\\\d?/.test(ss)){var m=ss.match(/\\\\d?e-(\\\\d?)/);if(m&&m[1]){sd=parseInt(m[1],10);}}var d=vd>sd?vd:sd;var vi=parseInt(v.toFixed(d).replace(\".\",\"\"),10);var si=parseInt(s.toFixed(d).replace(\".\",\"\"),10);return (vi%si)/Math.pow(10,d);}';\n\n/**\n * Hoisted `Object.prototype.hasOwnProperty` reference. Record fast/slow paths\n * iterate keys with `for(k in o)` (no `Object.keys` array allocation) and guard\n * each key with `__zcHop.call(o,k)` to skip inherited enumerable properties —\n * yielding the exact own-enumerable string-key set `Object.keys` would, so\n * fast/slow stay in agreement and parity with zod's own-key record semantics is\n * preserved. The hoisted reference inlines in V8; reading the prototype property\n * per call would not.\n */\nexport const ZC_HOP_DECL = \"const __zcHop=Object.prototype.hasOwnProperty;\";\n\n/**\n * Port of zod's `util.isPlainObject` — the guard `$ZodRecord` applies to its\n * input, and a STRICTLY narrower test than the `util.isObject` (`typeof\n * \"object\"`, not null, not an array) that `$ZodObject` uses.\n *\n * The distinction is load-bearing and was a validation hole while records shared\n * the object guard: `z.record(z.string(), z.string())` accepted a `Date`, a\n * `Map`, a `RegExp`, an `Error`, a `File` and any class instance — every one of\n * which zod rejects with `invalid_type`/`expected: \"record\"`, and none of which\n * has own enumerable string keys for the value schema to catch. Compiled output\n * therefore said \"valid\" to inputs zod refuses, which is the one direction a\n * validator must never diverge in.\n *\n * The algorithm is zod's, step for step, because the answer is observable and\n * the edge cases are deliberate:\n * - `constructor === undefined` (a null-prototype object) is PLAIN;\n * - a non-function own `constructor` (`{ constructor: 1 }`) is PLAIN;\n * - otherwise the constructor's `prototype` must be an object carrying its OWN\n * `isPrototypeOf` — which `Object.prototype` does and `Date.prototype`,\n * `Map.prototype` and every user class prototype do not. Testing that rather\n * than `Object.getPrototypeOf(o) === Object.prototype` is what lets a plain\n * object from another realm (a vm context, an iframe) still count as plain.\n *\n * Self-contained (`Object.prototype.hasOwnProperty` spelled out rather than\n * reusing `__zcHop`) so inline mode can emit this decl alone: `emitRuntimeHelper`\n * pushes only the decl it is asked for, and a helper that closed over another\n * name would dangle wherever that one was not also emitted.\n */\nexport const ZC_PLAIN_DECL =\n 'function __zcPlain(o){if(typeof o!==\"object\"||o===null||Array.isArray(o))return false;' +\n 'var c=o.constructor;if(c===undefined||typeof c!==\"function\")return true;' +\n 'var p=c.prototype;if(typeof p!==\"object\"||p===null||Array.isArray(p))return false;' +\n 'return Object.prototype.hasOwnProperty.call(p,\"isPrototypeOf\");}';\n\n/**\n * Ports of `util.getLengthableOrigin` / `util.getSizableOrigin` — the `origin` a\n * length/size check puts on its issue, computed from the RUNTIME INPUT rather\n * than from the schema.\n *\n * They only matter because those checks declare a `when` predicate\n * (`!nullish(value) && value.length/size !== undefined`), which bypasses zod's\n * abort gate: `z.string().min(2)` handed `[]` reports the `invalid_type` AND a\n * `too_small` whose origin is `\"array\"`, because the empty array satisfies the\n * `when`. Inside the matching type branch the origin is statically known and\n * these are not used; they exist for the type-MISMATCH branch, where the input\n * can be anything with a `.length` or a `.size`.\n *\n * `File` is probed through `typeof` first: zod tests `input instanceof File`\n * unguarded, which throws where the global is absent — an environment zod does\n * not run in, and not one worth reproducing a crash for.\n */\nexport const ZC_LENGTH_ORIGIN_DECL =\n 'function __zcLo(v){return Array.isArray(v)?\"array\":typeof v===\"string\"?\"string\":\"unknown\";}';\n\nexport const ZC_SIZE_ORIGIN_DECL =\n 'function __zcSo(v){return v instanceof Set?\"set\":v instanceof Map?\"map\":' +\n '(typeof File!==\"undefined\"&&v instanceof File)?\"file\":\"unknown\";}';\n\n/**\n * Issue codes zod raises from a schema's `_zod.parse` rather than from a check,\n * and which therefore carry `continue !== true` — what `util.aborted` looks for.\n *\n * Everything a CHECK produces (`too_small`, `too_big`, `invalid_format`,\n * `not_multiple_of`, a refine's `custom`) is continuable, because `$ZodCheck`\n * sets `continue: !def.abort` and an `abort: true` check costs the schema its\n * compiled path anyway — so classifying by code alone is exact for generated\n * issues.\n *\n * Read by {@link ZC_AB_DECL} and by the union's option-pruning loop, which\n * applies the same rule inline over a per-option issue array.\n */\nconst ABORTING_ISSUE_CODES: readonly string[] = [\n \"invalid_type\",\n \"invalid_value\",\n \"invalid_union\",\n \"unrecognized_keys\",\n \"invalid_key\",\n \"invalid_element\",\n];\n\n/** `c===\"invalid_type\"||c===\"invalid_value\"||…` over the code held in `codeExpr`. */\nexport function abortingCodeTest(codeExpr: string): string {\n return ABORTING_ISSUE_CODES.map((code) => `${codeExpr}===${JSON.stringify(code)}`).join(\"||\");\n}\n\n/**\n * Port of zod's `util.aborted(payload, startIndex)`: has anything since\n * `startIndex` produced a NON-continuable issue?\n *\n * zod gates a schema's check chain on this (`runChecks`: `else if (isAborted)\n * continue`), which is what makes a container's `.refine()` still run after a\n * property or element failed its own `min`/`max`/format check, and stop running\n * once one failed to parse at all. The `startIndex` is the issue count when the\n * node was entered, mirroring the fresh payload zod hands each sub-schema.\n *\n * Size/length checks are exempt in zod — they declare a `when` predicate, which\n * bypasses the abort gate — so generated code leaves those ungated and only\n * wraps the refine/superRefine effects.\n */\nexport const ZC_AB_DECL = `function __zcAb(e,i){for(;i<e.length;i++){var s=e[i];if(s.continue===false)return true;var c=s.code;if(${abortingCodeTest(\"c\")})return true;}return false;}`;\n\n/**\n * Port of zod's `util.finalizeIssue` for issues NESTED inside an\n * `invalid_key` / `invalid_element` wrapper. Those never reach the top-level\n * finalization loop (which walks only the outer array), so zod finalizes them\n * where it builds the wrapper: locale message applied when none was baked in,\n * `input` cleared. Their `path` stays RELATIVE to the key or value schema — zod\n * ran it on a fresh payload — so nothing rewrites it.\n *\n * `input` is `delete`d rather than assigned `undefined`, matching zod's own\n * `delete full.input` and the top-level finalizer: the key's PRESENCE is\n * observable (`\"input\" in issue`, `Object.keys`, spread, a strict deep-equal\n * against a zod issue), so assigning left a nested issue one key wider than\n * zod's. Only reached while an error is being built — never on a successful\n * parse — so the dictionary-mode transition it costs is confined to the path\n * that then constructs a ZodError anyway.\n */\nexport const ZC_FZ_DECL =\n \"function __zcFz(e){for(var i=0;i<e.length;i++){var s=e[i];\" +\n 'if(s.message===undefined&&typeof __zcMsg===\"function\")s.message=__zcMsg(s);' +\n \"delete s.input;delete s.continue;}return e;}\";\n\n/**\n * Port of zod's `util.prefixIssues(key, issues)` for a map entry whose key is a\n * property-key type: each issue's RELATIVE path is spliced onto the map's own\n * path plus the key, and the issue moves into the parent's array.\n *\n * `b.concat(k,x.path)` flattens `x.path` one level, giving exactly\n * `[...base, key, ...relative]`.\n */\nexport const ZC_PFX_DECL =\n \"function __zcPfx(d,s,b,k){for(var i=0;i<s.length;i++){var x=s[i];x.path=b.concat(k,x.path);d.push(x);}}\";\n\n/** Does `keyExpr` hold one of zod's `util.propertyKeyTypes` (string|number|symbol)? */\nexport function propertyKeyTest(keyExpr: string): string {\n return `typeof ${keyExpr}===\"string\"||typeof ${keyExpr}===\"number\"||typeof ${keyExpr}===\"symbol\"`;\n}\n\n/**\n * superRefine fast-check: run the payload callback on a throwaway payload and\n * report whether it both added nothing AND left the value alone. zod's own\n * wrapper (the referenced function) installs `addIssue` and normalizes what the\n * user adds, so the verdict is zod's; the issues themselves are re-collected by\n * the slow walk.\n *\n * The `p.value===v` half is what lets a superRefine node keep a fast path at\n * all. `value` is writable public API ($RefinementCtx extends ParsePayload), so\n * a callback may rewrite it, and the fast path's caller returns the ORIGINAL\n * input on success — which would then be stale. Reporting false when the value\n * moved routes those parses into the slow walk, which propagates the new value\n * (see ZC_SR_DECL). Callbacks that only validate — effectively all of them —\n * still take the fast exit.\n */\nexport const ZC_SR_OK_DECL =\n \"function __zcSrOk(f,v){var p={value:v,issues:[]};__zcSrRun(f,p);\" +\n \"return p.issues.length===0&&p.value===v;}\";\n\n/**\n * Module-local (never imported by generated code) — __zcSr/__zcSrOk call it.\n * Lean mode declares it in the runtime module beside them; inline mode pushes it\n * into the preamble alongside whichever of the two is used.\n *\n * Invoke the referenced wrapper, reproducing zod's synchronous-parse contract:\n * a callback that returns a promise makes zod raise $ZodAsyncError rather than\n * silently accepting. Because the ref points at zod's superRefine WRAPPER, not\n * the user's function, an async callback cannot be detected while extracting —\n * the returned thenable is the only evidence, so the test lives here. Sync\n * callbacks return undefined, so the guard short-circuits on the first operand.\n */\nexport const ZC_SR_RUN_DECL =\n \"function __zcSrRun(f,p){var r=f(p);\" +\n 'if(r&&typeof r.then===\"function\"){throw new __zcCore.$ZodAsyncError();}}';\n\n/**\n * z.custom()/z.instanceof() fast verdict. Zod treats truthy predicate returns\n * as success and raises $ZodAsyncError when a synchronous parse encounters a\n * thenable, including a non-async function that happens to return a Promise.\n */\nexport const ZC_CUSTOM_OK_DECL =\n \"function __zcCu(f,v){var r=f(v);\" +\n 'if(r&&typeof r.then===\"function\"){throw new __zcCore.$ZodAsyncError();}return !!r;}';\n\n/**\n * superRefine slow-path merge: run the callback, then move its issues onto the\n * validator's list the way zod's finalizeIssue does — the node's path prefixed\n * onto any path the user supplied, and the internal `inst`/`continue` fields\n * dropped (they are zod bookkeeping, deleted before the issue is user-visible).\n *\n * Returns the payload, so the caller can write `.value` back (the callback may\n * have rewritten it) and read `.aborted`. Aborted is set when any issue aborts\n * in zod's sense (`continue !== true`, which covers `fatal: true` and the string\n * shorthand, whose issue carries no `continue` at all) — or when the callback\n * set it directly, also public payload API. A union option uses it to mark\n * itself aborted, matching how zod prunes option errors; without it an option\n * failing only through superRefine would be surfaced directly instead of inside\n * `invalid_union`.\n */\nexport const ZC_SR_DECL =\n \"function __zcSr(f,v,p,e){var q={value:v,issues:[]};__zcSrRun(f,q);\" +\n \"for(var i=0;i<q.issues.length;i++){var s=q.issues[i],t={};\" +\n 'for(var k in s){if(k!==\"inst\"&&k!==\"continue\")t[k]=s[k];}' +\n \"if(s.continue!==true)q.aborted=true;\" +\n \"t.path=s.path&&s.path.length?p.concat(s.path):p;e.push(t);}return q;}\";\n\n/** Non-issue runtime helper declarations hosted in the virtual module. */\nexport const RUNTIME_HELPER_DECLS: Readonly<Record<string, string>> = {\n __zcAb: ZC_AB_DECL,\n __zcFsr: ZC_FSR_DECL,\n __zcFz: ZC_FZ_DECL,\n __zcHop: ZC_HOP_DECL,\n __zcLo: ZC_LENGTH_ORIGIN_DECL,\n __zcSo: ZC_SIZE_ORIGIN_DECL,\n __zcPlain: ZC_PLAIN_DECL,\n __zcPfx: ZC_PFX_DECL,\n __zcCu: ZC_CUSTOM_OK_DECL,\n __zcSr: ZC_SR_DECL,\n __zcSrOk: ZC_SR_OK_DECL,\n};\n"],"mappings":";AAmGA,MAAa,cAAgD;CAC3D,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;AACV;;;;;;AAOA,MAAa,cACX;;;;;;;;;;AAWF,MAAa,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8B3B,MAAa,gBACX;;;;;;;;;;;;;;;;;;AAsBF,MAAa,wBACX;AAEF,MAAa,sBACX;;;;;;;;;;;;;;AAgBF,MAAM,uBAA0C;CAC9C;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAgB,iBAAiB,UAA0B;CACzD,OAAO,qBAAqB,KAAK,SAAS,GAAG,SAAS,KAAK,KAAK,UAAU,IAAI,GAAG,CAAC,CAAC,KAAK,IAAI;AAC9F;;;;;;;;;;;;;;;AAgBA,MAAa,aAAa,0GAA0G,iBAAiB,GAAG,EAAE;;;;;;;;;;;;;;;;;AAkB1J,MAAa,aACX;;;;;;;;;AAYF,MAAa,cACX;;AAGF,SAAgB,gBAAgB,SAAyB;CACvD,OAAO,UAAU,QAAQ,sBAAsB,QAAQ,sBAAsB,QAAQ;AACvF;;;;;;;;;;;;;;;;AAiBA,MAAa,gBACX;;;;;;;;;;;;;AAeF,MAAa,iBACX;;;;;;AAQF,MAAa,oBACX;;;;;;;;;;;;;;;;AAkBF,MAAa,aACX;;AAOF,MAAa,uBAAyD;CACpE,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,WAAW;CACX,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,UAAU;AACZ"}
|
|
1
|
+
{"version":3,"file":"issue-decls.js","names":[],"sources":["../../../src/core/codegen/issue-decls.ts"],"sourcesContent":["/**\n * Issue factory function bodies (statement form).\n *\n * These functions produce the same `{code, ...}` shapes that lean-mode\n * generated code would otherwise inline at every check site.\n * Hosted in \"virtual:zod-compiler/runtime\" and called as `__zcTS(...)` etc.\n *\n * Argument convention (positional, kept short to minimize call-site bytes):\n * __zcTS(minimum, origin, inclusive, input, path, msg?) — too_small\n * __zcTSt(minimum, origin, input, path, msg?) — too_small, tuple key order\n * __zcTBt(maximum, origin, input, path, msg?) — too_big, tuple key order\n * __zcTB(maximum, origin, inclusive, input, path, msg?) — too_big\n * __zcIT(expected, input, path, msg?) — invalid_type\n * __zcITc(expected, input, path, msg?) — invalid_type, `code` first\n * __zcIF(origin, format, input, path, extra?, msg?) — invalid_format (extra merged into result)\n * __zcIV(values, input, path, extra?, msg?) — invalid_value (extra merged into result)\n * __zcUK(keys, input, path, msg?) — unrecognized_keys\n *\n * The trailing msg argument carries a static custom error message; when\n * absent, the __zcFin finalizer applies the configured locale default.\n *\n * KEY ORDER IS PART OF THE CONTRACT. `ZodError.message` is\n * `JSON.stringify(issues, …, 2)`, so the order these factories insert keys in is\n * printed verbatim in the message every consumer logs, snapshots or serializes.\n * Each literal below therefore reproduces the order of the corresponding\n * `payload.issues.push({…})` in zod, which is irregular by type — `too_small`\n * from a check leads with `origin` while the same code from a tuple's length\n * branch leads with `code` — and every factory writes `message` LAST, because\n * zod's `finalizeIssue` assigns it after the fact (`full.message = …`) even for\n * a custom message baked into the check's error map.\n */\n\nconst ZC_TS_DECL =\n 'function __zcTS(m,o,i,inp,p,msg){var r={origin:o,code:\"too_small\",minimum:m,inclusive:i,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\n/**\n * too_small in the TUPLE under-length key order. $ZodTuple pushes\n * `{ code, minimum, inclusive: true, input, inst, origin }`, so its `origin`\n * trails `inclusive` where every check-created size issue leads with it. Its\n * over-length sibling is __zcTBt.\n */\nconst ZC_TS_TUPLE_DECL =\n 'function __zcTSt(m,o,inp,p,msg){var r={code:\"too_small\",minimum:m,inclusive:true,origin:o,input:inp,path:p,continue:false};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_TS_EXACT_DECL =\n 'function __zcTSx(m,o,inp,p,msg){var r={origin:o,code:\"too_small\",minimum:m,inclusive:true,exact:true,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_TB_DECL =\n 'function __zcTB(m,o,i,inp,p,msg){var r={origin:o,code:\"too_big\",maximum:m,inclusive:i,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\n/**\n * too_big in the TUPLE over-length key order. $ZodTuple spreads\n * `{ code, maximum, inclusive }` and appends `origin` after `input`/`inst`, so\n * its `origin` trails `inclusive` where every check-created size issue leads\n * with it. Its under-length sibling is __zcTSt.\n */\nconst ZC_TB_TUPLE_DECL =\n 'function __zcTBt(m,o,inp,p,msg){var r={code:\"too_big\",maximum:m,inclusive:true,origin:o,input:inp,path:p,continue:false};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_TB_EXACT_DECL =\n 'function __zcTBx(m,o,inp,p,msg){var r={origin:o,code:\"too_big\",maximum:m,inclusive:true,exact:true,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_IT_DECL =\n 'function __zcIT(e,inp,p,msg){var r={expected:e,code:\"invalid_type\",input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\n/**\n * invalid_type with `code` ahead of `expected`. Every schema in zod spells this\n * issue `{ expected, code }` — except `$ZodDiscriminatedUnion`, whose\n * non-object guard writes `{ code, expected }`. One literal, one key order, and\n * it shows up in `ZodError.message`.\n */\nconst ZC_IT_CODE_FIRST_DECL =\n 'function __zcITc(e,inp,p,msg){var r={code:\"invalid_type\",expected:e,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\n/**\n * `o` is the leading `origin`, present only for the formats whose issue carries\n * one: `$ZodCheckStringFormat`'s default pattern check and the regex /\n * includes / starts_with / ends_with checks all lead with `origin: \"string\"`,\n * while `z.url()`'s own pushes and every `$ZodCustomStringFormat` omit it\n * entirely. `extra` holds the per-format tail (`pattern`, `includes`, `prefix`,\n * `suffix`, `note`) and is merged BEFORE input/path so it lands where zod\n * writes it.\n */\nconst ZC_IF_DECL =\n 'function __zcIF(o,f,inp,p,extra,msg){var r=o===undefined?{code:\"invalid_format\",format:f}:{origin:o,code:\"invalid_format\",format:f};if(extra)Object.assign(r,extra);r.input=inp;r.path=p;if(msg!==undefined)r.message=msg;return r;}';\n\n/**\n * `extra` carries the per-producer fields: enum and literal push `values` only,\n * while z.stringbool()'s codec transform also pushes `expected: \"stringbool\"`.\n * Merged the same way __zcIF merges its own.\n */\nconst ZC_IV_DECL =\n 'function __zcIV(values,inp,p,extra,msg){var r={code:\"invalid_value\"};if(extra)Object.assign(r,extra);r.values=values;r.input=inp;r.path=p;if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_UK_DECL =\n 'function __zcUK(k,inp,p,msg){var r={code:\"unrecognized_keys\",keys:k,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\n/** All issue factory declarations indexed by helper name. */\nexport const ISSUE_DECLS: Readonly<Record<string, string>> = {\n __zcTS: ZC_TS_DECL,\n __zcTSt: ZC_TS_TUPLE_DECL,\n __zcTSx: ZC_TS_EXACT_DECL,\n __zcTB: ZC_TB_DECL,\n __zcTBt: ZC_TB_TUPLE_DECL,\n __zcTBx: ZC_TB_EXACT_DECL,\n __zcIT: ZC_IT_DECL,\n __zcITc: ZC_IT_CODE_FIRST_DECL,\n __zcIF: ZC_IF_DECL,\n __zcIV: ZC_IV_DECL,\n __zcUK: ZC_UK_DECL,\n};\n\n/**\n * Float-safe remainder — byte-for-byte port of zod's util.floatSafeRemainder.\n * Raw `%` mis-rejects valid multiples of decimal steps (0.3 % 0.1 !== 0).\n *\n * zod 4.5 REPLACED the decimal-scaling implementation this once mirrored with a\n * ratio-and-tolerance one, and the two disagree in both directions: the old form\n * accepted `1e-7` as a multiple of 3 (its `toFixed` scaling collapsed the value\n * to 0) and rejected `1e21` (where `toFixed` yields exponential notation and\n * `parseInt` then reads 1). The tolerance is 4x epsilon because `val` and `step`\n * each round to a double before the division rounds again, so a true decimal\n * multiple's quotient can sit up to 1.5 scaled epsilons from the integer.\n */\nexport const ZC_FSR_DECL =\n \"function __zcFsr(v,s){var r=v/s;var q=Math.round(r);\" +\n \"var t=4*Number.EPSILON*Math.max(Math.abs(r),1);\" +\n \"return Math.abs(r-q)<t?0:r-q;}\";\n\n/**\n * Hoisted `Object.prototype.hasOwnProperty` reference. Record fast/slow paths\n * iterate keys with `for(k in o)` (no `Object.keys` array allocation) and guard\n * each key with `__zcHop.call(o,k)` to skip inherited enumerable properties —\n * yielding the exact own-enumerable string-key set `Object.keys` would, so\n * fast/slow stay in agreement and parity with zod's own-key record semantics is\n * preserved. The hoisted reference inlines in V8; reading the prototype property\n * per call would not.\n */\nexport const ZC_HOP_DECL = \"const __zcHop=Object.prototype.hasOwnProperty;\";\n\n/**\n * Port of zod's `util.isPlainObject` — the guard `$ZodRecord` applies to its\n * input, and a STRICTLY narrower test than the `util.isObject` (`typeof\n * \"object\"`, not null, not an array) that `$ZodObject` uses.\n *\n * The distinction is load-bearing and was a validation hole while records shared\n * the object guard: `z.record(z.string(), z.string())` accepted a `Date`, a\n * `Map`, a `RegExp`, an `Error`, a `File` and any class instance — every one of\n * which zod rejects with `invalid_type`/`expected: \"record\"`, and none of which\n * has own enumerable string keys for the value schema to catch. Compiled output\n * therefore said \"valid\" to inputs zod refuses, which is the one direction a\n * validator must never diverge in.\n *\n * The algorithm is zod's, step for step, because the answer is observable and\n * the edge cases are deliberate:\n * - `constructor === undefined` (a null-prototype object) is PLAIN;\n * - a non-function own `constructor` (`{ constructor: 1 }`) is PLAIN;\n * - otherwise the constructor's `prototype` must be an object carrying its OWN\n * `isPrototypeOf` — which `Object.prototype` does and `Date.prototype`,\n * `Map.prototype` and every user class prototype do not. Testing that rather\n * than `Object.getPrototypeOf(o) === Object.prototype` is what lets a plain\n * object from another realm (a vm context, an iframe) still count as plain.\n *\n * `c===Object` is a short-cut, not a fourth rule: it is exactly the case where\n * zod's remaining steps are foregone — `Object.prototype` is an object and has\n * its own `isPrototypeOf` — so the answer is `true` either way. It is also the\n * case every ordinary record takes (an object literal, `JSON.parse` output, a\n * `Map`-free DTO), and taking it saves the `prototype` load and the\n * `hasOwnProperty` call: measured 9.6 → 5.7 ns on a monomorphic record and\n * 15.7 → 9.2 ns across 16 shapes, i.e. 22% of a five-key record's whole parse.\n * A plain object from another realm has a different `Object` and simply takes\n * the long road to the same verdict, as before.\n *\n * Self-contained (`Object.prototype.hasOwnProperty` spelled out rather than\n * reusing `__zcHop`) so inline mode can emit this decl alone: `emitRuntimeHelper`\n * pushes only the decl it is asked for, and a helper that closed over another\n * name would dangle wherever that one was not also emitted.\n */\nexport const ZC_PLAIN_DECL =\n 'function __zcPlain(o){if(typeof o!==\"object\"||o===null||Array.isArray(o))return false;' +\n 'var c=o.constructor;if(c===Object||c===undefined||typeof c!==\"function\")return true;' +\n 'var p=c.prototype;if(typeof p!==\"object\"||p===null||Array.isArray(p))return false;' +\n 'return Object.prototype.hasOwnProperty.call(p,\"isPrototypeOf\");}';\n\n/**\n * `z.email()`'s default validator, `regexes.email`, as a single linear scan.\n *\n * Zod's pattern is\n * `^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$`,\n * and even its lookahead-free rewrite (EMAIL_FAST_REGEX_SOURCE) backtracks at\n * every dot it fails to find: `(?:[X]+\\.)*` re-tries the run one character\n * shorter each time, and the domain's `(?:label\\.)+` does the same over the\n * TLD. Written as a scanner the language is:\n *\n * local — `[A-Za-z0-9_'+.-]+`, no leading `.`, no `..`, and the character\n * before `@` is neither `.` nor `'` (that last is the `[A-Za-z0-9_+-]`\n * the pattern demands there);\n * domain — one or more labels `[A-Za-z0-9][A-Za-z0-9-]*` each ending in `.`,\n * then a TLD of two or more letters running to the end.\n *\n * A trailing `\\n` is not accepted: the pattern has no `m` flag, so its `$`\n * matches only at the end of input, and the scan reads to `length`.\n *\n * Measured against the fast regex on V8: 32 → 16 ns for `alice@example.com`,\n * 48 → 40 for `bob_smith-99@mail-server.io`, 39 → 20 for a non-address, and a\n * tie from ~35 characters up (the regex's per-character work is cheaper than a\n * `charCodeAt` loop's; its fixed dispatch cost is what the scanner avoids). A\n * lookbehind rewrite runs about as fast but needs ES2018 regex support, which\n * the CLI's React Native / Hermes and older-Safari consumers cannot assume.\n *\n * Equivalence to zod's regex — every string, both verdicts — is pinned by\n * tests/core/codegen/email-scanner.test.ts. Reached only behind a `typeof`\n * string guard, like the `.test()` it replaces; issue sites keep reporting\n * zod's own pattern string (see `emitRegexSourceString`).\n */\nexport const ZC_EMAIL_DECL =\n \"function __zcEmail(s){var n=s.length,i=0,c,p=46;\" +\n // Local part. `p` starts as `.` so a leading dot trips the `..` rule.\n \"for(;;){if(i===n)return false;c=s.charCodeAt(i);if(c===64)break;\" +\n \"if(c===46){if(p===46)return false;}\" +\n \"else if(!((c>=97&&c<=122)||(c>=65&&c<=90)||(c>=48&&c<=57)||c===95||c===39||c===43||c===45))return false;\" +\n \"p=c;i++;}\" +\n \"if(p===46||p===39)return false;\" +\n // Domain. `l` is the current label's start, `t` whether it is letters-only.\n \"var l=++i,d=0,t=true;\" +\n \"for(;i<n;i++){c=s.charCodeAt(i);\" +\n \"if((c>=97&&c<=122)||(c>=65&&c<=90))continue;\" +\n \"if(c===46){if(i===l)return false;d++;l=i+1;t=true;continue;}\" +\n \"if((c>=48&&c<=57)||c===45){if(c===45&&i===l)return false;t=false;continue;}\" +\n \"return false;}\" +\n \"return d>0&&t&&n-l>=2;}\";\n\n/**\n * Ports of `util.getLengthableOrigin` / `util.getSizableOrigin` — the `origin` a\n * length/size check puts on its issue, computed from the RUNTIME INPUT rather\n * than from the schema.\n *\n * They only matter because those checks declare a `when` predicate\n * (`!nullish(value) && value.length/size !== undefined`), which bypasses zod's\n * abort gate: `z.string().min(2)` handed `[]` reports the `invalid_type` AND a\n * `too_small` whose origin is `\"array\"`, because the empty array satisfies the\n * `when`. Inside the matching type branch the origin is statically known and\n * these are not used; they exist for the type-MISMATCH branch, where the input\n * can be anything with a `.length` or a `.size`.\n *\n * `File` is probed through `typeof` first: zod tests `input instanceof File`\n * unguarded, which throws where the global is absent — an environment zod does\n * not run in, and not one worth reproducing a crash for.\n */\nexport const ZC_LENGTH_ORIGIN_DECL =\n 'function __zcLo(v){return Array.isArray(v)?\"array\":typeof v===\"string\"?\"string\":\"unknown\";}';\n\n/**\n * Drop an own `__proto__` from a container the parse hands back BY REFERENCE.\n *\n * zod never lets the key into an output: `$ZodObject`'s shape loop strips a\n * declared one, `handleCatchall` skips an undeclared one, and `$ZodRecord` skips\n * it while copying — all so the assignment into their fresh `{}` cannot replace\n * the result's prototype. A compiled loose/catchall object or record IS its\n * input, so the key has to be removed here instead; leaving it made\n * `Object.assign({}, parsed)` a prototype-pollution sink, since [[Set]] runs the\n * inherited setter the spread that built the value did not.\n *\n * Copies rather than editing in place: the divergence note promises the caller\n * its own container back, not one with a key silently deleted from it. The\n * common object has no such key and is returned untouched, so the cost is one\n * `hasOwnProperty` call.\n */\nexport const ZC_PROTO_SCRUB_DECL =\n 'function __zcPs(o){if(!Object.prototype.hasOwnProperty.call(o,\"__proto__\"))return o;' +\n 'var c={...o};delete c[\"__proto__\"];return c;}';\n\n/**\n * Code points in a string — zod's `util.codePointLength`, verbatim. A surrogate\n * pair counts once and a lone surrogate as itself. The regex probe is the fast\n * exit for a string with no astral characters, and the hand-rolled loop avoids\n * the allocating string iterator. Only reached from a length check whose\n * UTF-16 count leaves the verdict in doubt (see stringLengthTests).\n */\nexport const ZC_CPL_DECL =\n \"function __zcCpl(s){var n=s.length;if(!/[\\\\uD800-\\\\uDBFF]/.test(s))return n;var c=n;for(var i=0;i<n-1;i++){if((s.charCodeAt(i)&0xfc00)===0xd800&&(s.charCodeAt(i+1)&0xfc00)===0xdc00){c--;i++;}}return c;}\";\n\nexport const ZC_SIZE_ORIGIN_DECL =\n 'function __zcSo(v){return v instanceof Set?\"set\":v instanceof Map?\"map\":' +\n '(typeof File!==\"undefined\"&&v instanceof File)?\"file\":\"unknown\";}';\n\n/**\n * Issue codes zod raises from a schema's `_zod.parse` rather than from a check,\n * and which therefore carry `continue !== true` — what `util.aborted` looks for.\n *\n * Everything a CHECK produces (`too_small`, `too_big`, `invalid_format`,\n * `not_multiple_of`, a refine's `custom`) is continuable, because `$ZodCheck`\n * sets `continue: !def.abort` and an `abort: true` check costs the schema its\n * compiled path anyway — so classifying by code alone is exact for generated\n * issues.\n *\n * `unrecognized_keys` is the one parse-level issue zod pushes WITH\n * `continue: true`: it describes the shape of the input rather than the\n * validity of the parsed value, so the parse still fails but the object's own\n * refines run first and a union does not count the option as aborted.\n *\n * Read by {@link ZC_AB_DECL} and by the union's option-pruning loop, which\n * applies the same rule inline over a per-option issue array.\n */\nconst ABORTING_ISSUE_CODES: readonly string[] = [\n \"invalid_type\",\n \"invalid_value\",\n \"invalid_union\",\n \"invalid_key\",\n \"invalid_element\",\n];\n\n/** `c===\"invalid_type\"||c===\"invalid_value\"||…` over the code held in `codeExpr`. */\nexport function abortingCodeTest(codeExpr: string): string {\n return ABORTING_ISSUE_CODES.map((code) => `${codeExpr}===${JSON.stringify(code)}`).join(\"||\");\n}\n\n/**\n * Port of zod's `util.aborted(payload, startIndex)`: has anything since\n * `startIndex` produced a NON-continuable issue?\n *\n * zod gates a schema's check chain on this (`runChecks`: `else if (isAborted)\n * continue`), which is what makes a container's `.refine()` still run after a\n * property or element failed its own `min`/`max`/format check, and stop running\n * once one failed to parse at all. The `startIndex` is the issue count when the\n * node was entered, mirroring the fresh payload zod hands each sub-schema.\n *\n * Size/length checks are exempt in zod — they declare a `when` predicate, which\n * bypasses the abort gate — so generated code leaves those ungated and only\n * wraps the refine/superRefine effects.\n */\nexport const ZC_AB_DECL = `function __zcAb(e,i){for(;i<e.length;i++){var s=e[i];if(s.continue===false)return true;var c=s.code;if(${abortingCodeTest(\"c\")})return true;}return false;}`;\n\n/**\n * Port of zod's `util.finalizeIssue` for issues NESTED inside an\n * `invalid_key` / `invalid_element` wrapper. Those never reach the top-level\n * finalization loop (which walks only the outer array), so zod finalizes them\n * where it builds the wrapper: locale message applied when none was baked in,\n * `input` cleared. Their `path` stays RELATIVE to the key or value schema — zod\n * ran it on a fresh payload — so nothing rewrites it.\n *\n * `input` is `delete`d rather than assigned `undefined`, matching zod's own\n * `delete full.input` and the top-level finalizer: the key's PRESENCE is\n * observable (`\"input\" in issue`, `Object.keys`, spread, a strict deep-equal\n * against a zod issue), so assigning left a nested issue one key wider than\n * zod's. Only reached while an error is being built — never on a successful\n * parse — so the dictionary-mode transition it costs is confined to the path\n * that then constructs a ZodError anyway.\n */\nexport const ZC_FZ_DECL =\n \"function __zcFz(e){for(var i=0;i<e.length;i++){var s=e[i];\" +\n 'if(s.message===undefined&&typeof __zcMsg===\"function\")s.message=__zcMsg(s);' +\n \"delete s.input;delete s.continue;}return e;}\";\n\n/**\n * Port of zod's `util.prefixIssues(key, issues)` for a map entry whose key is a\n * property-key type: each issue's RELATIVE path is spliced onto the map's own\n * path plus the key, and the issue moves into the parent's array.\n *\n * `b.concat(k,x.path)` flattens `x.path` one level, giving exactly\n * `[...base, key, ...relative]`.\n */\nexport const ZC_PFX_DECL =\n \"function __zcPfx(d,s,b,k){for(var i=0;i<s.length;i++){var x=s[i];x.path=b.concat(k,x.path);d.push(x);}}\";\n\n/** Does `keyExpr` hold one of zod's `util.propertyKeyTypes` (string|number|symbol)? */\nexport function propertyKeyTest(keyExpr: string): string {\n return `typeof ${keyExpr}===\"string\"||typeof ${keyExpr}===\"number\"||typeof ${keyExpr}===\"symbol\"`;\n}\n\n/**\n * superRefine fast-check: run the payload callback on a throwaway payload and\n * report whether it both added nothing AND left the value alone. zod's own\n * wrapper (the referenced function) installs `addIssue` and normalizes what the\n * user adds, so the verdict is zod's; the issues themselves are re-collected by\n * the slow walk.\n *\n * The `p.value===v` half is what lets a superRefine node keep a fast path at\n * all. `value` is writable public API ($RefinementCtx extends ParsePayload), so\n * a callback may rewrite it, and the fast path's caller returns the ORIGINAL\n * input on success — which would then be stale. Reporting false when the value\n * moved routes those parses into the slow walk, which propagates the new value\n * (see ZC_SR_DECL). Callbacks that only validate — effectively all of them —\n * still take the fast exit.\n */\nexport const ZC_SR_OK_DECL =\n \"function __zcSrOk(f,v){var p={value:v,issues:[]};__zcSrRun(f,p);\" +\n \"return p.issues.length===0&&p.value===v;}\";\n\n/**\n * Module-local (never imported by generated code) — __zcSr/__zcSrOk call it.\n * Lean mode declares it in the runtime module beside them; inline mode pushes it\n * into the preamble alongside whichever of the two is used.\n *\n * Invoke the referenced wrapper, reproducing zod's synchronous-parse contract:\n * a callback that returns a promise makes zod raise $ZodAsyncError rather than\n * silently accepting. Because the ref points at zod's superRefine WRAPPER, not\n * the user's function, an async callback cannot be detected while extracting —\n * the returned thenable is the only evidence, so the test lives here. Sync\n * callbacks return undefined, so the guard short-circuits on the first operand.\n */\nexport const ZC_SR_RUN_DECL =\n \"function __zcSrRun(f,p){var r=f(p);\" +\n 'if(r&&typeof r.then===\"function\"){throw new __zcCore.$ZodAsyncError();}}';\n\n/**\n * z.custom()/z.instanceof() fast verdict. Zod treats truthy predicate returns\n * as success and raises $ZodAsyncError when a synchronous parse encounters a\n * thenable, including a non-async function that happens to return a Promise.\n */\nexport const ZC_CUSTOM_OK_DECL =\n \"function __zcCu(f,v){var r=f(v);\" +\n 'if(r&&typeof r.then===\"function\"){throw new __zcCore.$ZodAsyncError();}return !!r;}';\n\n/**\n * superRefine slow-path merge: run the callback, then move its issues onto the\n * validator's list the way zod's finalizeIssue does — the node's path prefixed\n * onto any path the user supplied, the internal `inst`/`continue` fields\n * dropped (they are zod bookkeeping, deleted before the issue is user-visible),\n * and the owning schema's static message `m` applied to an issue that carries\n * none of its own, since zod stamps the owner onto every issue a check raises.\n *\n * Returns the payload, so the caller can write `.value` back (the callback may\n * have rewritten it) and read `.aborted`. Aborted is set when any issue aborts\n * in zod's sense (`continue !== true`, which covers `fatal: true` and the string\n * shorthand, whose issue carries no `continue` at all) — or when the callback\n * set it directly, also public payload API. A union option uses it to mark\n * itself aborted, matching how zod prunes option errors; without it an option\n * failing only through superRefine would be surfaced directly instead of inside\n * `invalid_union`.\n */\nexport const ZC_SR_DECL =\n \"function __zcSr(f,v,p,e,m){var q={value:v,issues:[]};__zcSrRun(f,q);\" +\n \"for(var i=0;i<q.issues.length;i++){var s=q.issues[i],t={};\" +\n 'for(var k in s){if(k!==\"inst\"&&k!==\"continue\")t[k]=s[k];}' +\n \"if(s.continue!==true)q.aborted=true;\" +\n \"t.path=s.path&&s.path.length?p.concat(s.path):p;\" +\n \"if(t.message===undefined&&m!==undefined)t.message=m;e.push(t);}return q;}\";\n\n/** Non-issue runtime helper declarations hosted in the virtual module. */\nexport const RUNTIME_HELPER_DECLS: Readonly<Record<string, string>> = {\n __zcAb: ZC_AB_DECL,\n __zcFsr: ZC_FSR_DECL,\n __zcFz: ZC_FZ_DECL,\n __zcHop: ZC_HOP_DECL,\n __zcLo: ZC_LENGTH_ORIGIN_DECL,\n __zcSo: ZC_SIZE_ORIGIN_DECL,\n __zcCpl: ZC_CPL_DECL,\n __zcEmail: ZC_EMAIL_DECL,\n __zcPs: ZC_PROTO_SCRUB_DECL,\n __zcPlain: ZC_PLAIN_DECL,\n __zcPfx: ZC_PFX_DECL,\n __zcCu: ZC_CUSTOM_OK_DECL,\n __zcSr: ZC_SR_DECL,\n __zcSrOk: ZC_SR_OK_DECL,\n};\n"],"mappings":";AAkGA,MAAa,cAAgD;CAC3D,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;AACV;;;;;;;;;;;;;AAcA,MAAa,cACX;;;;;;;;;;AAaF,MAAa,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwC3B,MAAa,gBACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCF,MAAa,gBACX;;;;;;;;;;;;;;;;;;AAiCF,MAAa,wBACX;;;;;;;;;;;;;;;;;AAkBF,MAAa,sBACX;;;;;;;;AAUF,MAAa,cACX;AAEF,MAAa,sBACX;;;;;;;;;;;;;;;;;;;AAqBF,MAAM,uBAA0C;CAC9C;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAgB,iBAAiB,UAA0B;CACzD,OAAO,qBAAqB,KAAK,SAAS,GAAG,SAAS,KAAK,KAAK,UAAU,IAAI,GAAG,CAAC,CAAC,KAAK,IAAI;AAC9F;;;;;;;;;;;;;;;AAgBA,MAAa,aAAa,0GAA0G,iBAAiB,GAAG,EAAE;;;;;;;;;;;;;;;;;AAkB1J,MAAa,aACX;;;;;;;;;AAYF,MAAa,cACX;;AAGF,SAAgB,gBAAgB,SAAyB;CACvD,OAAO,UAAU,QAAQ,sBAAsB,QAAQ,sBAAsB,QAAQ;AACvF;;;;;;;;;;;;;;;;AAiBA,MAAa,gBACX;;;;;;;;;;;;;AAeF,MAAa,iBACX;;;;;;AAQF,MAAa,oBACX;;;;;;;;;;;;;;;;;;AAoBF,MAAa,aACX;;AAQF,MAAa,uBAAyD;CACpE,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,WAAW;CACX,QAAQ;CACR,WAAW;CACX,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,UAAU;AACZ"}
|
|
@@ -9,7 +9,7 @@ function slowArray(ir, g) {
|
|
|
9
9
|
let code = emit`
|
|
10
10
|
if(!Array.isArray(${g.input})){
|
|
11
11
|
${invalidType(g, "array")}
|
|
12
|
-
${whenGatedSizeChecks(ir.checks, g, "length")}
|
|
12
|
+
${whenGatedSizeChecks(ir.checks, g, "length", true)}
|
|
13
13
|
}else{`;
|
|
14
14
|
if (hasMutation(ir.element)) code += `${g.output}=${g.input}.slice();`;
|
|
15
15
|
const refineMark = ir.checks.some((c) => c.kind === "refine_effect" || c.kind === "super_refine_effect") ? g.temp("rm") : "";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"array.js","names":[],"sources":["../../../../src/core/codegen/schemas/array.ts"],"sourcesContent":["import type { ArrayIR, CheckIR, SchemaIR } from \"../../types.js\";\nimport type { FastGen, SlowGen } from \"../context.js\";\nimport {\n checkPriority,\n declareFastTemps,\n emitEffectCallable,\n emitRuntimeHelper,\n extendPath,\n hasMutation,\n} from \"../context.js\";\nimport { emit } from \"../emit.js\";\nimport { invalidType, tooBig, tooSmall } from \"../emit-issue.js\";\nimport { ZC_AB_DECL } from \"../issue-decls.js\";\nimport { refineCheck, superRefineCheck, superRefineFastTest } from \"./effect.js\";\nimport { whenGatedSizeChecks } from \"./sizeable.js\";\n\nexport function slowArray(ir: SchemaIR & { type: \"array\" }, g: SlowGen): string {\n let code = emit`\n if(!Array.isArray(${g.input})){\n ${invalidType(g, \"array\")}\n ${whenGatedSizeChecks(ir.checks, g, \"length\")}\n }else{`;\n\n if (hasMutation(ir.element)) {\n code += `${g.output}=${g.input}.slice();`;\n }\n\n // Element validation precedes the size/refine checks: Zod parses elements\n // (the base type) first and only then runs its checks, so for an input that\n // both has an invalid element AND fails a size check, the per-element issue\n // is surfaced before too_small/too_big. Emitting the checks first would\n // reverse that order (the slow path collects all issues with no\n // short-circuit, so insertion order IS issue order).\n\n // Snapshot before the elements, for the same reason slowObject does: the\n // array's refine effects are gated on zod's abort rule over the issues THIS\n // node's parse produced. Size checks are exempt — zod's length checks declare\n // a `when` predicate, which bypasses the abort gate, so\n // `z.array(z.string()).min(2)` still reports too_small next to a bad element's\n // invalid_type.\n const hasRefine = ir.checks.some(\n (c) => c.kind === \"refine_effect\" || c.kind === \"super_refine_effect\",\n );\n const refineMark = hasRefine ? g.temp(\"rm\") : \"\";\n if (refineMark) code += `var ${refineMark}=${g.issues}.length;`;\n\n const idxVar = g.temp(\"i\");\n const elemExpr = `${g.input}[${idxVar}]`;\n const elemPath = extendPath(g.path, idxVar);\n code += emit`\n for(var ${idxVar}=0;${idxVar}<${g.input}.length;${idxVar}++){\n ${g.visit(ir.element, { input: elemExpr, output: elemExpr, path: elemPath })}\n }`;\n\n /** Wrap one refine effect in zod's abort gate, preserving declaration order. */\n const gated = (body: string): string => {\n const aborted = emitRuntimeHelper(g.ctx, \"__zcAb\", ZC_AB_DECL);\n return `if(!${aborted}(${g.issues},${refineMark})){${body}}`;\n };\n\n for (const check of ir.checks) {\n switch (check.kind) {\n case \"min_length\":\n code += emit`\n if(${g.input}.length<${check.minimum}){\n ${tooSmall(g, check.minimum, \"array\", true, { message: check.message })}\n }`;\n break;\n case \"max_length\":\n code += emit`\n if(${g.input}.length>${check.maximum}){\n ${tooBig(g, check.maximum, \"array\", true, { message: check.message })}\n }`;\n break;\n case \"length_equals\":\n code += emit`\n if(${g.input}.length<${check.length}){\n ${tooSmall(g, check.length, \"array\", true, { exact: true, message: check.message })}\n }else if(${g.input}.length>${check.length}){\n ${tooBig(g, check.length, \"array\", true, { exact: true, message: check.message })}\n }`;\n break;\n case \"refine_effect\":\n code += gated(refineCheck(check, g.input, g));\n break;\n case \"super_refine_effect\":\n code += gated(superRefineCheck(check, g.input, g));\n break;\n }\n }\n\n code += `}`;\n return `${code}\\n`;\n}\n\nexport function fastArray(ir: ArrayIR, g: FastGen): string | null {\n const x = g.input;\n const parts: string[] = [`Array.isArray(${x})`];\n const checks = ir.checks.filter((c): c is CheckIR => c.kind !== \"refine_effect\");\n\n // Size checks\n for (const check of checks.sort(checkPriority)) {\n switch (check.kind) {\n case \"min_length\":\n parts.push(`${x}.length>=${check.minimum}`);\n break;\n case \"max_length\":\n parts.push(`${x}.length<=${check.maximum}`);\n break;\n case \"length_equals\":\n parts.push(`${x}.length===${check.length}`);\n break;\n }\n }\n\n // Element validation via preamble helper (avoids .every() closure allocation).\n // Fresh scope: the helper is its own function, size-gated independently.\n const elemVar = g.temp(\"ae\");\n const elemGen = g.scoped(elemVar);\n const elemCheck = elemGen.visit(ir.element);\n if (elemCheck === null) return null;\n if (elemCheck !== \"true\") {\n const helperName = g.temp(\"af\");\n g.ctx.preamble.push(\n `function ${helperName}(a){${declareFastTemps(elemGen.scope)}for(var ${elemVar},i=0;i<a.length;i++){${elemVar}=a[i];if(!(${elemCheck})){return false;}}return true;}`,\n );\n parts.push(`${helperName}(${x})`);\n }\n\n // Refine effect checks (appended last — run after cheap checks short-circuit)\n for (const check of ir.checks) {\n if (check.kind === \"refine_effect\") {\n parts.push(`${emitEffectCallable(g.ctx, check)}(${x})`);\n } else if (check.kind === \"super_refine_effect\") {\n parts.push(superRefineFastTest(check, x, g));\n }\n }\n\n return parts.join(\"&&\");\n}\n"],"mappings":";;;;;;;AAgBA,SAAgB,UAAU,IAAkC,GAAoB;CAC9E,IAAI,OAAO,IAAI;wBACO,EAAE,MAAM;QACxB,YAAY,GAAG,OAAO,EAAE;QACxB,oBAAoB,GAAG,QAAQ,GAAG,
|
|
1
|
+
{"version":3,"file":"array.js","names":[],"sources":["../../../../src/core/codegen/schemas/array.ts"],"sourcesContent":["import type { ArrayIR, CheckIR, SchemaIR } from \"../../types.js\";\nimport type { FastGen, SlowGen } from \"../context.js\";\nimport {\n checkPriority,\n declareFastTemps,\n emitEffectCallable,\n emitRuntimeHelper,\n extendPath,\n hasMutation,\n} from \"../context.js\";\nimport { emit } from \"../emit.js\";\nimport { invalidType, tooBig, tooSmall } from \"../emit-issue.js\";\nimport { ZC_AB_DECL } from \"../issue-decls.js\";\nimport { refineCheck, superRefineCheck, superRefineFastTest } from \"./effect.js\";\nimport { whenGatedSizeChecks } from \"./sizeable.js\";\n\nexport function slowArray(ir: SchemaIR & { type: \"array\" }, g: SlowGen): string {\n let code = emit`\n if(!Array.isArray(${g.input})){\n ${invalidType(g, \"array\")}\n ${whenGatedSizeChecks(ir.checks, g, \"length\", true)}\n }else{`;\n\n if (hasMutation(ir.element)) {\n code += `${g.output}=${g.input}.slice();`;\n }\n\n // Element validation precedes the size/refine checks: Zod parses elements\n // (the base type) first and only then runs its checks, so for an input that\n // both has an invalid element AND fails a size check, the per-element issue\n // is surfaced before too_small/too_big. Emitting the checks first would\n // reverse that order (the slow path collects all issues with no\n // short-circuit, so insertion order IS issue order).\n\n // Snapshot before the elements, for the same reason slowObject does: the\n // array's refine effects are gated on zod's abort rule over the issues THIS\n // node's parse produced. Size checks are exempt — zod's length checks declare\n // a `when` predicate, which bypasses the abort gate, so\n // `z.array(z.string()).min(2)` still reports too_small next to a bad element's\n // invalid_type.\n const hasRefine = ir.checks.some(\n (c) => c.kind === \"refine_effect\" || c.kind === \"super_refine_effect\",\n );\n const refineMark = hasRefine ? g.temp(\"rm\") : \"\";\n if (refineMark) code += `var ${refineMark}=${g.issues}.length;`;\n\n const idxVar = g.temp(\"i\");\n const elemExpr = `${g.input}[${idxVar}]`;\n const elemPath = extendPath(g.path, idxVar);\n code += emit`\n for(var ${idxVar}=0;${idxVar}<${g.input}.length;${idxVar}++){\n ${g.visit(ir.element, { input: elemExpr, output: elemExpr, path: elemPath })}\n }`;\n\n /** Wrap one refine effect in zod's abort gate, preserving declaration order. */\n const gated = (body: string): string => {\n const aborted = emitRuntimeHelper(g.ctx, \"__zcAb\", ZC_AB_DECL);\n return `if(!${aborted}(${g.issues},${refineMark})){${body}}`;\n };\n\n for (const check of ir.checks) {\n switch (check.kind) {\n case \"min_length\":\n code += emit`\n if(${g.input}.length<${check.minimum}){\n ${tooSmall(g, check.minimum, \"array\", true, { message: check.message })}\n }`;\n break;\n case \"max_length\":\n code += emit`\n if(${g.input}.length>${check.maximum}){\n ${tooBig(g, check.maximum, \"array\", true, { message: check.message })}\n }`;\n break;\n case \"length_equals\":\n code += emit`\n if(${g.input}.length<${check.length}){\n ${tooSmall(g, check.length, \"array\", true, { exact: true, message: check.message })}\n }else if(${g.input}.length>${check.length}){\n ${tooBig(g, check.length, \"array\", true, { exact: true, message: check.message })}\n }`;\n break;\n case \"refine_effect\":\n code += gated(refineCheck(check, g.input, g));\n break;\n case \"super_refine_effect\":\n code += gated(superRefineCheck(check, g.input, g));\n break;\n }\n }\n\n code += `}`;\n return `${code}\\n`;\n}\n\nexport function fastArray(ir: ArrayIR, g: FastGen): string | null {\n const x = g.input;\n const parts: string[] = [`Array.isArray(${x})`];\n const checks = ir.checks.filter((c): c is CheckIR => c.kind !== \"refine_effect\");\n\n // Size checks\n for (const check of checks.sort(checkPriority)) {\n switch (check.kind) {\n case \"min_length\":\n parts.push(`${x}.length>=${check.minimum}`);\n break;\n case \"max_length\":\n parts.push(`${x}.length<=${check.maximum}`);\n break;\n case \"length_equals\":\n parts.push(`${x}.length===${check.length}`);\n break;\n }\n }\n\n // Element validation via preamble helper (avoids .every() closure allocation).\n // Fresh scope: the helper is its own function, size-gated independently.\n const elemVar = g.temp(\"ae\");\n const elemGen = g.scoped(elemVar);\n const elemCheck = elemGen.visit(ir.element);\n if (elemCheck === null) return null;\n if (elemCheck !== \"true\") {\n const helperName = g.temp(\"af\");\n g.ctx.preamble.push(\n `function ${helperName}(a){${declareFastTemps(elemGen.scope)}for(var ${elemVar},i=0;i<a.length;i++){${elemVar}=a[i];if(!(${elemCheck})){return false;}}return true;}`,\n );\n parts.push(`${helperName}(${x})`);\n }\n\n // Refine effect checks (appended last — run after cheap checks short-circuit)\n for (const check of ir.checks) {\n if (check.kind === \"refine_effect\") {\n parts.push(`${emitEffectCallable(g.ctx, check)}(${x})`);\n } else if (check.kind === \"super_refine_effect\") {\n parts.push(superRefineFastTest(check, x, g));\n }\n }\n\n return parts.join(\"&&\");\n}\n"],"mappings":";;;;;;;AAgBA,SAAgB,UAAU,IAAkC,GAAoB;CAC9E,IAAI,OAAO,IAAI;wBACO,EAAE,MAAM;QACxB,YAAY,GAAG,OAAO,EAAE;QACxB,oBAAoB,GAAG,QAAQ,GAAG,UAAU,IAAI,EAAE;;CAGxD,IAAI,YAAY,GAAG,OAAO,GACxB,QAAQ,GAAG,EAAE,OAAO,GAAG,EAAE,MAAM;CAmBjC,MAAM,aAHY,GAAG,OAAO,MACzB,MAAM,EAAE,SAAS,mBAAmB,EAAE,SAAS,qBAEvB,IAAI,EAAE,KAAK,IAAI,IAAI;CAC9C,IAAI,YAAY,QAAQ,OAAO,WAAW,GAAG,EAAE,OAAO;CAEtD,MAAM,SAAS,EAAE,KAAK,GAAG;CACzB,MAAM,WAAW,GAAG,EAAE,MAAM,GAAG,OAAO;CACtC,MAAM,WAAW,WAAW,EAAE,MAAM,MAAM;CAC1C,QAAQ,IAAI;cACA,OAAO,KAAK,OAAO,GAAG,EAAE,MAAM,UAAU,OAAO;QACrD,EAAE,MAAM,GAAG,SAAS;EAAE,OAAO;EAAU,QAAQ;EAAU,MAAM;CAAS,CAAC,EAAE;;;CAIjF,MAAM,SAAS,SAAyB;EAEtC,OAAO,OADS,kBAAkB,EAAE,KAAK,UAAU,UAC/B,EAAE,GAAG,EAAE,OAAO,GAAG,WAAW,KAAK,KAAK;CAC5D;CAEA,KAAK,MAAM,SAAS,GAAG,QACrB,QAAQ,MAAM,MAAd;EACE,KAAK;GACH,QAAQ,IAAI;eACL,EAAE,MAAM,UAAU,MAAM,QAAQ;cACjC,SAAS,GAAG,MAAM,SAAS,SAAS,MAAM,EAAE,SAAS,MAAM,QAAQ,CAAC,EAAE;;GAE5E;EACF,KAAK;GACH,QAAQ,IAAI;eACL,EAAE,MAAM,UAAU,MAAM,QAAQ;cACjC,OAAO,GAAG,MAAM,SAAS,SAAS,MAAM,EAAE,SAAS,MAAM,QAAQ,CAAC,EAAE;;GAE1E;EACF,KAAK;GACH,QAAQ,IAAI;eACL,EAAE,MAAM,UAAU,MAAM,OAAO;cAChC,SAAS,GAAG,MAAM,QAAQ,SAAS,MAAM;IAAE,OAAO;IAAM,SAAS,MAAM;GAAQ,CAAC,EAAE;qBAC3E,EAAE,MAAM,UAAU,MAAM,OAAO;cACtC,OAAO,GAAG,MAAM,QAAQ,SAAS,MAAM;IAAE,OAAO;IAAM,SAAS,MAAM;GAAQ,CAAC,EAAE;;GAEtF;EACF,KAAK;GACH,QAAQ,MAAM,YAAY,OAAO,EAAE,OAAO,CAAC,CAAC;GAC5C;EACF,KAAK;GACH,QAAQ,MAAM,iBAAiB,OAAO,EAAE,OAAO,CAAC,CAAC;GACjD;CACJ;CAGF,QAAQ;CACR,OAAO,GAAG,KAAK;AACjB;AAEA,SAAgB,UAAU,IAAa,GAA2B;CAChE,MAAM,IAAI,EAAE;CACZ,MAAM,QAAkB,CAAC,iBAAiB,EAAE,EAAE;CAC9C,MAAM,SAAS,GAAG,OAAO,QAAQ,MAAoB,EAAE,SAAS,eAAe;CAG/E,KAAK,MAAM,SAAS,OAAO,KAAK,aAAa,GAC3C,QAAQ,MAAM,MAAd;EACE,KAAK;GACH,MAAM,KAAK,GAAG,EAAE,WAAW,MAAM,SAAS;GAC1C;EACF,KAAK;GACH,MAAM,KAAK,GAAG,EAAE,WAAW,MAAM,SAAS;GAC1C;EACF,KAAK;GACH,MAAM,KAAK,GAAG,EAAE,YAAY,MAAM,QAAQ;GAC1C;CACJ;CAKF,MAAM,UAAU,EAAE,KAAK,IAAI;CAC3B,MAAM,UAAU,EAAE,OAAO,OAAO;CAChC,MAAM,YAAY,QAAQ,MAAM,GAAG,OAAO;CAC1C,IAAI,cAAc,MAAM,OAAO;CAC/B,IAAI,cAAc,QAAQ;EACxB,MAAM,aAAa,EAAE,KAAK,IAAI;EAC9B,EAAE,IAAI,SAAS,KACb,YAAY,WAAW,MAAM,iBAAiB,QAAQ,KAAK,EAAE,UAAU,QAAQ,uBAAuB,QAAQ,aAAa,UAAU,gCACvI;EACA,MAAM,KAAK,GAAG,WAAW,GAAG,EAAE,EAAE;CAClC;CAGA,KAAK,MAAM,SAAS,GAAG,QACrB,IAAI,MAAM,SAAS,iBACjB,MAAM,KAAK,GAAG,mBAAmB,EAAE,KAAK,KAAK,EAAE,GAAG,EAAE,EAAE;MACjD,IAAI,MAAM,SAAS,uBACxB,MAAM,KAAK,oBAAoB,OAAO,GAAG,CAAC,CAAC;CAI/C,OAAO,MAAM,KAAK,IAAI;AACxB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bigint.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/bigint.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"bigint.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/bigint.ts"],"mappings":";;;iBAegB,WAAW,IAAI,UAAU,GAAG;iBAkE5B,WAAW,IAAI,UAAU,GAAG"}
|
|
@@ -2,6 +2,14 @@ import { checkPriority } from "../context.js";
|
|
|
2
2
|
import { emit } from "../emit.js";
|
|
3
3
|
import { invalidType, tooBig, tooSmall } from "../emit-issue.js";
|
|
4
4
|
//#region src/core/codegen/schemas/bigint.ts
|
|
5
|
+
/**
|
|
6
|
+
* A `bigint_multiple_of` divisor of zero, read from the IR's STRING form
|
|
7
|
+
* (`"0"`, and `-0n` stringifies to the same). `BigInt()` rather than a literal
|
|
8
|
+
* comparison so a value spelled any other way still lands here.
|
|
9
|
+
*/
|
|
10
|
+
function isZeroDivisor(value) {
|
|
11
|
+
return BigInt(value) === 0n;
|
|
12
|
+
}
|
|
5
13
|
function slowBigInt(ir, g) {
|
|
6
14
|
let code = "";
|
|
7
15
|
if (ir.coerce) code += emit`try{${g.output}=BigInt(${g.input});}catch(_){}`;
|
|
@@ -33,10 +41,13 @@ function slowBigInt(ir, g) {
|
|
|
33
41
|
}`;
|
|
34
42
|
break;
|
|
35
43
|
case "bigint_multiple_of": {
|
|
36
|
-
const
|
|
37
|
-
|
|
44
|
+
const message = check.message ?? g.typeMsg;
|
|
45
|
+
const msgProp = message !== void 0 ? `,message:${JSON.stringify(message)}` : "";
|
|
46
|
+
const push = `${g.issues}.push({origin:"bigint",code:"not_multiple_of",divisor:${check.value}n,input:${g.input},path:${g.path}${msgProp}});`;
|
|
47
|
+
code += isZeroDivisor(check.value) ? emit`
|
|
48
|
+
${push}` : emit`
|
|
38
49
|
if(${g.input}%${check.value}n!==0n){
|
|
39
|
-
${
|
|
50
|
+
${push}
|
|
40
51
|
}`;
|
|
41
52
|
break;
|
|
42
53
|
}
|
|
@@ -57,7 +68,7 @@ function fastBigInt(ir, g) {
|
|
|
57
68
|
parts.push(check.inclusive ? `${x}<=${check.value}n` : `${x}<${check.value}n`);
|
|
58
69
|
break;
|
|
59
70
|
case "bigint_multiple_of":
|
|
60
|
-
parts.push(`${x}%${check.value}n===0n`);
|
|
71
|
+
parts.push(isZeroDivisor(check.value) ? "false" : `${x}%${check.value}n===0n`);
|
|
61
72
|
break;
|
|
62
73
|
}
|
|
63
74
|
return parts.join("&&");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bigint.js","names":[],"sources":["../../../../src/core/codegen/schemas/bigint.ts"],"sourcesContent":["import type { BigIntIR } from \"../../types.js\";\nimport type { FastGen, SlowGen } from \"../context.js\";\nimport { checkPriority } from \"../context.js\";\nimport { emit } from \"../emit.js\";\nimport { invalidType, tooBig, tooSmall } from \"../emit-issue.js\";\n\nexport function slowBigInt(ir: BigIntIR, g: SlowGen): string {\n let code = \"\";\n if (ir.coerce) {\n code += emit`try{${g.output}=BigInt(${g.input});}catch(_){}`;\n }\n code += emit`\n if(typeof ${g.input}!==\"bigint\"){\n ${invalidType(g, \"bigint\")}\n }`;\n\n if (ir.checks.length > 0) {\n code += `else{`;\n // Insertion order mirrors zod's issue order for multi-failure inputs.\n for (const check of ir.checks) {\n switch (check.kind) {\n case \"bigint_greater_than\":\n if (check.inclusive) {\n code += emit`\n if(${g.input}<${check.value}n){\n ${tooSmall(g, `${check.value}n`, \"bigint\", true, { message: check.message })}\n }`;\n } else {\n code += emit`\n if(${g.input}<=${check.value}n){\n ${tooSmall(g, `${check.value}n`, \"bigint\", false, { message: check.message })}\n }`;\n }\n break;\n case \"bigint_less_than\":\n if (check.inclusive) {\n code += emit`\n if(${g.input}>${check.value}n){\n ${tooBig(g, `${check.value}n`, \"bigint\", true, { message: check.message })}\n }`;\n } else {\n code += emit`\n if(${g.input}>=${check.value}n){\n ${tooBig(g, `${check.value}n`, \"bigint\", false, { message: check.message })}\n }`;\n }\n break;\n case \"bigint_multiple_of\": {\n const
|
|
1
|
+
{"version":3,"file":"bigint.js","names":[],"sources":["../../../../src/core/codegen/schemas/bigint.ts"],"sourcesContent":["import type { BigIntIR } from \"../../types.js\";\nimport type { FastGen, SlowGen } from \"../context.js\";\nimport { checkPriority } from \"../context.js\";\nimport { emit } from \"../emit.js\";\nimport { invalidType, tooBig, tooSmall } from \"../emit-issue.js\";\n\n/**\n * A `bigint_multiple_of` divisor of zero, read from the IR's STRING form\n * (`\"0\"`, and `-0n` stringifies to the same). `BigInt()` rather than a literal\n * comparison so a value spelled any other way still lands here.\n */\nfunction isZeroDivisor(value: string): boolean {\n return BigInt(value) === 0n;\n}\n\nexport function slowBigInt(ir: BigIntIR, g: SlowGen): string {\n let code = \"\";\n if (ir.coerce) {\n code += emit`try{${g.output}=BigInt(${g.input});}catch(_){}`;\n }\n code += emit`\n if(typeof ${g.input}!==\"bigint\"){\n ${invalidType(g, \"bigint\")}\n }`;\n\n if (ir.checks.length > 0) {\n code += `else{`;\n // Insertion order mirrors zod's issue order for multi-failure inputs.\n for (const check of ir.checks) {\n switch (check.kind) {\n case \"bigint_greater_than\":\n if (check.inclusive) {\n code += emit`\n if(${g.input}<${check.value}n){\n ${tooSmall(g, `${check.value}n`, \"bigint\", true, { message: check.message })}\n }`;\n } else {\n code += emit`\n if(${g.input}<=${check.value}n){\n ${tooSmall(g, `${check.value}n`, \"bigint\", false, { message: check.message })}\n }`;\n }\n break;\n case \"bigint_less_than\":\n if (check.inclusive) {\n code += emit`\n if(${g.input}>${check.value}n){\n ${tooBig(g, `${check.value}n`, \"bigint\", true, { message: check.message })}\n }`;\n } else {\n code += emit`\n if(${g.input}>=${check.value}n){\n ${tooBig(g, `${check.value}n`, \"bigint\", false, { message: check.message })}\n }`;\n }\n break;\n case \"bigint_multiple_of\": {\n const message = check.message ?? g.typeMsg;\n const msgProp = message !== undefined ? `,message:${JSON.stringify(message)}` : \"\";\n const push = `${g.issues}.push({origin:\"bigint\",code:\"not_multiple_of\",divisor:${check.value}n,input:${g.input},path:${g.path}${msgProp}});`;\n // `x % 0n` THROWS RangeError, and nothing is a multiple of zero, so\n // zod 4.5 guards the divisor and reports the issue instead\n // ($ZodCheckMultipleOf; the number branch already lands there via\n // NaN). The divisor is static, so the guard costs nothing at runtime.\n code += isZeroDivisor(check.value)\n ? emit`\n ${push}`\n : emit`\n if(${g.input}%${check.value}n!==0n){\n ${push}\n }`;\n break;\n }\n }\n }\n code += `}`;\n }\n\n return `${code}\\n`;\n}\n\nexport function fastBigInt(ir: BigIntIR, g: FastGen): string | null {\n if (ir.coerce) return null;\n\n const x = g.input;\n const parts: string[] = [`typeof ${x}===\"bigint\"`];\n\n for (const check of [...ir.checks].sort(checkPriority)) {\n switch (check.kind) {\n case \"bigint_greater_than\":\n parts.push(check.inclusive ? `${x}>=${check.value}n` : `${x}>${check.value}n`);\n break;\n case \"bigint_less_than\":\n parts.push(check.inclusive ? `${x}<=${check.value}n` : `${x}<${check.value}n`);\n break;\n case \"bigint_multiple_of\":\n // See the slow path: a zero divisor rejects rather than throwing.\n parts.push(isZeroDivisor(check.value) ? \"false\" : `${x}%${check.value}n===0n`);\n break;\n }\n }\n\n return parts.join(\"&&\");\n}\n"],"mappings":";;;;;;;;;AAWA,SAAS,cAAc,OAAwB;CAC7C,OAAO,OAAO,KAAK,MAAM;AAC3B;AAEA,SAAgB,WAAW,IAAc,GAAoB;CAC3D,IAAI,OAAO;CACX,IAAI,GAAG,QACL,QAAQ,IAAI,OAAO,EAAE,OAAO,UAAU,EAAE,MAAM;CAEhD,QAAQ,IAAI;gBACE,EAAE,MAAM;QAChB,YAAY,GAAG,QAAQ,EAAE;;CAG/B,IAAI,GAAG,OAAO,SAAS,GAAG;EACxB,QAAQ;EAER,KAAK,MAAM,SAAS,GAAG,QACrB,QAAQ,MAAM,MAAd;GACE,KAAK;IACH,IAAI,MAAM,WACR,QAAQ,IAAI;mBACL,EAAE,MAAM,GAAG,MAAM,MAAM;kBACxB,SAAS,GAAG,GAAG,MAAM,MAAM,IAAI,UAAU,MAAM,EAAE,SAAS,MAAM,QAAQ,CAAC,EAAE;;SAGjF,QAAQ,IAAI;mBACL,EAAE,MAAM,IAAI,MAAM,MAAM;kBACzB,SAAS,GAAG,GAAG,MAAM,MAAM,IAAI,UAAU,OAAO,EAAE,SAAS,MAAM,QAAQ,CAAC,EAAE;;IAGpF;GACF,KAAK;IACH,IAAI,MAAM,WACR,QAAQ,IAAI;mBACL,EAAE,MAAM,GAAG,MAAM,MAAM;kBACxB,OAAO,GAAG,GAAG,MAAM,MAAM,IAAI,UAAU,MAAM,EAAE,SAAS,MAAM,QAAQ,CAAC,EAAE;;SAG/E,QAAQ,IAAI;mBACL,EAAE,MAAM,IAAI,MAAM,MAAM;kBACzB,OAAO,GAAG,GAAG,MAAM,MAAM,IAAI,UAAU,OAAO,EAAE,SAAS,MAAM,QAAQ,CAAC,EAAE;;IAGlF;GACF,KAAK,sBAAsB;IACzB,MAAM,UAAU,MAAM,WAAW,EAAE;IACnC,MAAM,UAAU,YAAY,KAAA,IAAY,YAAY,KAAK,UAAU,OAAO,MAAM;IAChF,MAAM,OAAO,GAAG,EAAE,OAAO,wDAAwD,MAAM,MAAM,UAAU,EAAE,MAAM,QAAQ,EAAE,OAAO,QAAQ;IAKxI,QAAQ,cAAc,MAAM,KAAK,IAC7B,IAAI;cACJ,SACA,IAAI;iBACD,EAAE,MAAM,GAAG,MAAM,MAAM;gBACxB,KAAK;;IAEX;GACF;EACF;EAEF,QAAQ;CACV;CAEA,OAAO,GAAG,KAAK;AACjB;AAEA,SAAgB,WAAW,IAAc,GAA2B;CAClE,IAAI,GAAG,QAAQ,OAAO;CAEtB,MAAM,IAAI,EAAE;CACZ,MAAM,QAAkB,CAAC,UAAU,EAAE,YAAY;CAEjD,KAAK,MAAM,SAAS,CAAC,GAAG,GAAG,MAAM,CAAC,CAAC,KAAK,aAAa,GACnD,QAAQ,MAAM,MAAd;EACE,KAAK;GACH,MAAM,KAAK,MAAM,YAAY,GAAG,EAAE,IAAI,MAAM,MAAM,KAAK,GAAG,EAAE,GAAG,MAAM,MAAM,EAAE;GAC7E;EACF,KAAK;GACH,MAAM,KAAK,MAAM,YAAY,GAAG,EAAE,IAAI,MAAM,MAAM,KAAK,GAAG,EAAE,GAAG,MAAM,MAAM,EAAE;GAC7E;EACF,KAAK;GAEH,MAAM,KAAK,cAAc,MAAM,KAAK,IAAI,UAAU,GAAG,EAAE,GAAG,MAAM,MAAM,OAAO;GAC7E;CACJ;CAGF,OAAO,MAAM,KAAK,IAAI;AACxB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"catch.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/catch.ts"],"mappings":";;;iBAGgB,UAAU,IAAI;EAAa;GAAiB,GAAG;
|
|
1
|
+
{"version":3,"file":"catch.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/catch.ts"],"mappings":";;;iBAGgB,UAAU,IAAI;EAAa;GAAiB,GAAG;iBAyC/C,UAAU,IAAI,SAAS,GAAG"}
|
|
@@ -3,8 +3,9 @@ function slowCatch(ir, g) {
|
|
|
3
3
|
const tempIssues = g.temp("ci");
|
|
4
4
|
const idxVar = g.temp("ck");
|
|
5
5
|
const cvVar = g.temp("cv");
|
|
6
|
+
const inVar = g.temp("cin");
|
|
6
7
|
return [
|
|
7
|
-
`var ${tempIssues}=[];`,
|
|
8
|
+
`var ${tempIssues}=[];var ${inVar}=${g.input};`,
|
|
8
9
|
g.visit(ir.inner, { issues: tempIssues }),
|
|
9
10
|
`if(${tempIssues}.length>0){`,
|
|
10
11
|
`for(var ${idxVar}=0;${idxVar}<${tempIssues}.length;${idxVar}++){`,
|
|
@@ -12,7 +13,7 @@ function slowCatch(ir, g) {
|
|
|
12
13
|
`delete ${tempIssues}[${idxVar}].input;`,
|
|
13
14
|
`}`,
|
|
14
15
|
`var ${cvVar}=__rf[${ir.refIndex}]._zod.def.catchValue;`,
|
|
15
|
-
`${g.output}=typeof ${cvVar}==="function"?${cvVar}({value:${
|
|
16
|
+
`${g.output}=typeof ${cvVar}==="function"?${cvVar}({value:${inVar},issues:${tempIssues},error:{issues:${tempIssues}},input:${inVar}}):${cvVar};`,
|
|
16
17
|
`}`,
|
|
17
18
|
""
|
|
18
19
|
].join("\n");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"catch.js","names":[],"sources":["../../../../src/core/codegen/schemas/catch.ts"],"sourcesContent":["import type { CatchIR, SchemaIR } from \"../../types.js\";\nimport type { FastGen, SlowGen } from \"../context.js\";\n\nexport function slowCatch(ir: SchemaIR & { type: \"catch\" }, g: SlowGen): string {\n const tempIssues = g.temp(\"ci\");\n const idxVar = g.temp(\"ck\");\n const cvVar = g.temp(\"cv\");\n // Mirrors $ZodCatch: on inner failure, catchValue receives a ctx of\n // { value, issues, error: { issues }, input } and its result replaces the\n // value; the issues are swallowed. Finalize messages first so ctx readers\n // see zod-shaped issues (one finalized array serves both fields).\n //\n // `input` is `delete`d, not assigned `undefined`, so `ctx.error.issues[n]` has\n // exactly zod's key set — zod's `finalizeIssue` deletes it, and the key's\n // presence shows through `Object.keys`/spread/strict deep-equal even when the\n // value reads as `undefined` either way. (`ctx.issues` is a documented\n // divergence: zod hands the callback the RAW payload array there, carrying\n // `inst` — the schema instance — which compiled code has no counterpart for.\n // See tests/known-divergences.test.ts.) Only reached on an inner failure, and\n // that failure is about to be swallowed by the catch value, so nothing on a\n // successful parse pays for the delete.\n return [\n `var ${tempIssues}=[];`,\n g.visit(ir.inner, { issues: tempIssues }),\n `if(${tempIssues}.length>0){`,\n `for(var ${idxVar}=0;${idxVar}<${tempIssues}.length;${idxVar}++){`,\n `if(${tempIssues}[${idxVar}].message===undefined&&typeof __zcMsg===\"function\"){${tempIssues}[${idxVar}].message=__zcMsg(${tempIssues}[${idxVar}]);}`,\n `delete ${tempIssues}[${idxVar}].input;`,\n `}`,\n `var ${cvVar}=__rf[${ir.refIndex}]._zod.def.catchValue;`,\n `${g.output}=typeof ${cvVar}===\"function\"?${cvVar}({value:${
|
|
1
|
+
{"version":3,"file":"catch.js","names":[],"sources":["../../../../src/core/codegen/schemas/catch.ts"],"sourcesContent":["import type { CatchIR, SchemaIR } from \"../../types.js\";\nimport type { FastGen, SlowGen } from \"../context.js\";\n\nexport function slowCatch(ir: SchemaIR & { type: \"catch\" }, g: SlowGen): string {\n const tempIssues = g.temp(\"ci\");\n const idxVar = g.temp(\"ck\");\n const cvVar = g.temp(\"cv\");\n const inVar = g.temp(\"cin\");\n // Mirrors $ZodCatch: on inner failure, catchValue receives a ctx of\n // { value, issues, error: { issues }, input } and its result replaces the\n // value; the issues are swallowed. Finalize messages first so ctx readers\n // see zod-shaped issues (one finalized array serves both fields).\n //\n // `value` and `input` are both the value the catch was HANDED, snapshotted\n // before the inner runs: zod runs the inner on a payload of its own and\n // spreads that, but overwrites `value` with the original input. The compiled\n // walk writes the inner's output through the same slot it reads from, so\n // without the snapshot a rebuilding inner (a strip object, a readonly) would\n // hand the callback its half-built copy instead.\n //\n // `input` is `delete`d, not assigned `undefined`, so `ctx.error.issues[n]` has\n // exactly zod's key set — zod's `finalizeIssue` deletes it, and the key's\n // presence shows through `Object.keys`/spread/strict deep-equal even when the\n // value reads as `undefined` either way. (`ctx.issues` is a documented\n // divergence: zod hands the callback the RAW payload array there, carrying\n // `inst` — the schema instance — which compiled code has no counterpart for.\n // See tests/known-divergences.test.ts.) Only reached on an inner failure, and\n // that failure is about to be swallowed by the catch value, so nothing on a\n // successful parse pays for the delete.\n return [\n `var ${tempIssues}=[];var ${inVar}=${g.input};`,\n g.visit(ir.inner, { issues: tempIssues }),\n `if(${tempIssues}.length>0){`,\n `for(var ${idxVar}=0;${idxVar}<${tempIssues}.length;${idxVar}++){`,\n `if(${tempIssues}[${idxVar}].message===undefined&&typeof __zcMsg===\"function\"){${tempIssues}[${idxVar}].message=__zcMsg(${tempIssues}[${idxVar}]);}`,\n `delete ${tempIssues}[${idxVar}].input;`,\n `}`,\n `var ${cvVar}=__rf[${ir.refIndex}]._zod.def.catchValue;`,\n `${g.output}=typeof ${cvVar}===\"function\"?${cvVar}({value:${inVar},issues:${tempIssues},error:{issues:${tempIssues}},input:${inVar}}):${cvVar};`,\n `}`,\n \"\",\n ].join(\"\\n\");\n}\n\nexport function fastCatch(ir: CatchIR, g: FastGen): string | null {\n return g.visit(ir.inner);\n}\n"],"mappings":";AAGA,SAAgB,UAAU,IAAkC,GAAoB;CAC9E,MAAM,aAAa,EAAE,KAAK,IAAI;CAC9B,MAAM,SAAS,EAAE,KAAK,IAAI;CAC1B,MAAM,QAAQ,EAAE,KAAK,IAAI;CACzB,MAAM,QAAQ,EAAE,KAAK,KAAK;CAsB1B,OAAO;EACL,OAAO,WAAW,UAAU,MAAM,GAAG,EAAE,MAAM;EAC7C,EAAE,MAAM,GAAG,OAAO,EAAE,QAAQ,WAAW,CAAC;EACxC,MAAM,WAAW;EACjB,WAAW,OAAO,KAAK,OAAO,GAAG,WAAW,UAAU,OAAO;EAC7D,MAAM,WAAW,GAAG,OAAO,sDAAsD,WAAW,GAAG,OAAO,oBAAoB,WAAW,GAAG,OAAO;EAC/I,UAAU,WAAW,GAAG,OAAO;EAC/B;EACA,OAAO,MAAM,QAAQ,GAAG,SAAS;EACjC,GAAG,EAAE,OAAO,UAAU,MAAM,gBAAgB,MAAM,UAAU,MAAM,UAAU,WAAW,iBAAiB,WAAW,UAAU,MAAM,KAAK,MAAM;EAC9I;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;AAEA,SAAgB,UAAU,IAAa,GAA2B;CAChE,OAAO,EAAE,MAAM,GAAG,KAAK;AACzB"}
|
|
@@ -40,10 +40,14 @@ declare function fastDiscriminatedUnion(ir: DiscriminatedUnionIR, g: FastGen): s
|
|
|
40
40
|
* options (ambiguous), a non-switchable value (`undefined`/`NaN`), or a
|
|
41
41
|
* non-object option makes detection bail to the safe `||`-chain.
|
|
42
42
|
*
|
|
43
|
-
*
|
|
43
|
+
* The slow path is untouched: it keeps `z.union`'s sequential trial and its
|
|
44
44
|
* `invalid_union` error shape, so failure output stays byte-identical to Zod.
|
|
45
|
+
* The fast path and the build path both dispatch on the result — the build
|
|
46
|
+
* path from two options up (`minOptions`), since its options are hosted calls
|
|
47
|
+
* either way and a switch only ever replaces probes with one call; see
|
|
48
|
+
* `buildUnion`.
|
|
45
49
|
*/
|
|
46
|
-
declare function detectUnionDiscriminator(options: readonly SchemaIR[]): {
|
|
50
|
+
declare function detectUnionDiscriminator(options: readonly SchemaIR[], minOptions?: number): {
|
|
47
51
|
discriminator: string;
|
|
48
52
|
cases: DiscriminatorCase[];
|
|
49
53
|
} | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discriminated-union.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/discriminated-union.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"discriminated-union.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/discriminated-union.ts"],"mappings":";;;;KAaK,oBAAoB;iBAET,uBACd,IAAI;EAAa;GACjB,GAAG;;;;;;;;;;;;;;;;;;iBAoEW,4BACd,GAAG,SACH,uBACA,gBAAgB,qBAChB,kBAAkB;iBAmCJ,uBAAuB,IAAI,sBAAsB,GAAG;;;;;;;;;;;;;;;;;;;;;;;iBAyDpD,yBACd,kBAAkB,YAClB;EACG;EAAuB,OAAO"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { declareFastTemps,
|
|
1
|
+
import { declareFastTemps, escapeString, extendPath, hasMutation, literalToJs } from "../context.js";
|
|
2
2
|
import { emit } from "../emit.js";
|
|
3
3
|
import { invalidType } from "../emit-issue.js";
|
|
4
4
|
//#region src/core/codegen/schemas/discriminated-union.ts
|
|
@@ -21,9 +21,10 @@ function slowDiscriminatedUnion(ir, g) {
|
|
|
21
21
|
break;`;
|
|
22
22
|
}
|
|
23
23
|
const msgProp = g.typeMsg === void 0 ? "" : `,message:${JSON.stringify(g.typeMsg)}`;
|
|
24
|
+
const optionsList = ir.cases.map(({ value }) => literalToJs(value)).join(",");
|
|
24
25
|
code += emit`
|
|
25
26
|
default:
|
|
26
|
-
${g.issues}.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:${discKey},input:${g.input},path:${extendPath(g.path, discKey)}${msgProp}});
|
|
27
|
+
${g.issues}.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:${discKey},options:[${optionsList}],input:${g.input},path:${extendPath(g.path, discKey)}${msgProp}});
|
|
27
28
|
}`;
|
|
28
29
|
if (ir.options.some(hasMutation)) code += `${g.output}=${objVar};`;
|
|
29
30
|
code += `}`;
|
|
@@ -52,60 +53,15 @@ function emitFastDiscriminatedSwitch(g, discriminator, cases, options) {
|
|
|
52
53
|
const helperName = g.temp("du");
|
|
53
54
|
const helperParam = g.temp("dx");
|
|
54
55
|
const body = g.scoped(helperParam);
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
if (check === null) return null;
|
|
61
|
-
caseStrs.push(`case ${literalToJs(value)}:return ${check};`);
|
|
62
|
-
}
|
|
63
|
-
g.ctx.preamble.push(`function ${helperName}(${helperParam}){${declareFastTemps(body.scope)}switch(${helperParam}[${discKey}]){${caseStrs.join("")}default:return false;}}`);
|
|
64
|
-
} else {
|
|
65
|
-
const caseStrs = [];
|
|
66
|
-
for (const [optionIndex, ordinal] of table.ordinals) {
|
|
67
|
-
const check = body.visit(options[optionIndex], { discSkipKey: discriminator });
|
|
68
|
-
if (check === null) return null;
|
|
69
|
-
caseStrs.push(`case ${ordinal}:return ${check};`);
|
|
70
|
-
}
|
|
71
|
-
const tableVar = emitConstant(g.ctx, "dt", table.initializer);
|
|
72
|
-
const t = g.temp("dv");
|
|
73
|
-
g.ctx.preamble.push(`function ${helperName}(${helperParam}){${declareFastTemps(body.scope)}var ${t}=${helperParam}[${discKey}];switch(typeof ${t}==="string"?${tableVar}[${t}]:0){${caseStrs.join("")}default:return false;}}`);
|
|
56
|
+
const caseStrs = [];
|
|
57
|
+
for (const { value, option: index } of cases) {
|
|
58
|
+
const check = body.visit(options[index], { discSkipKey: discriminator });
|
|
59
|
+
if (check === null) return null;
|
|
60
|
+
caseStrs.push(`case ${literalToJs(value)}:return ${check};`);
|
|
74
61
|
}
|
|
62
|
+
g.ctx.preamble.push(`function ${helperName}(${helperParam}){${declareFastTemps(body.scope)}switch(${helperParam}[${discKey}]){${caseStrs.join("")}default:return false;}}`);
|
|
75
63
|
return `typeof ${x}==="object"&&${x}!==null&&!Array.isArray(${x})&&${helperName}(${x})`;
|
|
76
64
|
}
|
|
77
|
-
/**
|
|
78
|
-
* Minimum case count for ordinal dispatch. Measured crossover is 3: at 2 cases
|
|
79
|
-
* the string switch is one comparison and beats the extra table lookup
|
|
80
|
-
* (4.1 ns vs 4.5), at 3 the table already wins (6.1 vs 4.6).
|
|
81
|
-
*/
|
|
82
|
-
const MIN_TABLE_DISPATCH = 3;
|
|
83
|
-
/**
|
|
84
|
-
* Build the `{value: ordinal}` dispatch table for a set of cases, or null when
|
|
85
|
-
* the plain string switch should be kept. Requires every discriminator value to
|
|
86
|
-
* be a string — mixed types would collide once coerced to property keys (`5`
|
|
87
|
-
* and `"5"`) — and excludes `__proto__`, which an object literal cannot hold as
|
|
88
|
-
* an own key. Values that select the SAME option share one ordinal, so a
|
|
89
|
-
* multi-value literal emits its check once instead of per value.
|
|
90
|
-
*/
|
|
91
|
-
function stringDispatchTable(cases) {
|
|
92
|
-
if (cases.length < MIN_TABLE_DISPATCH) return null;
|
|
93
|
-
if (!cases.every((c) => typeof c.value === "string" && c.value !== "__proto__")) return null;
|
|
94
|
-
const ordinals = /* @__PURE__ */ new Map();
|
|
95
|
-
const entries = [];
|
|
96
|
-
for (const { value, option } of cases) {
|
|
97
|
-
let ordinal = ordinals.get(option);
|
|
98
|
-
if (ordinal === void 0) {
|
|
99
|
-
ordinal = ordinals.size + 1;
|
|
100
|
-
ordinals.set(option, ordinal);
|
|
101
|
-
}
|
|
102
|
-
entries.push(`${escapeString(value)}:${ordinal}`);
|
|
103
|
-
}
|
|
104
|
-
return {
|
|
105
|
-
initializer: `{${entries.join(",")}}`,
|
|
106
|
-
ordinals
|
|
107
|
-
};
|
|
108
|
-
}
|
|
109
65
|
function fastDiscriminatedUnion(ir, g) {
|
|
110
66
|
return emitFastDiscriminatedSwitch(g, ir.discriminator, ir.cases, ir.options);
|
|
111
67
|
}
|
|
@@ -147,11 +103,15 @@ function isSwitchableDiscriminant(v) {
|
|
|
147
103
|
* options (ambiguous), a non-switchable value (`undefined`/`NaN`), or a
|
|
148
104
|
* non-object option makes detection bail to the safe `||`-chain.
|
|
149
105
|
*
|
|
150
|
-
*
|
|
106
|
+
* The slow path is untouched: it keeps `z.union`'s sequential trial and its
|
|
151
107
|
* `invalid_union` error shape, so failure output stays byte-identical to Zod.
|
|
108
|
+
* The fast path and the build path both dispatch on the result — the build
|
|
109
|
+
* path from two options up (`minOptions`), since its options are hosted calls
|
|
110
|
+
* either way and a switch only ever replaces probes with one call; see
|
|
111
|
+
* `buildUnion`.
|
|
152
112
|
*/
|
|
153
|
-
function detectUnionDiscriminator(options) {
|
|
154
|
-
if (options.length <
|
|
113
|
+
function detectUnionDiscriminator(options, minOptions = MIN_AUTO_DISCRIMINATE_OPTIONS) {
|
|
114
|
+
if (options.length < minOptions) return null;
|
|
155
115
|
const objects = [];
|
|
156
116
|
for (const option of options) {
|
|
157
117
|
if (option.type !== "object") return null;
|