zod-compiler 2.0.2 → 2.0.3

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.
Files changed (56) hide show
  1. package/README.md +8 -6
  2. package/dist/cli/commands/check.d.ts.map +1 -1
  3. package/dist/cli/commands/check.js +5 -0
  4. package/dist/cli/commands/check.js.map +1 -1
  5. package/dist/core/codegen/build-path.js +18 -6
  6. package/dist/core/codegen/build-path.js.map +1 -1
  7. package/dist/core/codegen/context.d.ts +10 -1
  8. package/dist/core/codegen/context.d.ts.map +1 -1
  9. package/dist/core/codegen/context.js +15 -1
  10. package/dist/core/codegen/context.js.map +1 -1
  11. package/dist/core/codegen/issue-decls.d.ts +67 -5
  12. package/dist/core/codegen/issue-decls.d.ts.map +1 -1
  13. package/dist/core/codegen/issue-decls.js +72 -7
  14. package/dist/core/codegen/issue-decls.js.map +1 -1
  15. package/dist/core/codegen/schemas/array.d.ts.map +1 -1
  16. package/dist/core/codegen/schemas/array.js +3 -3
  17. package/dist/core/codegen/schemas/array.js.map +1 -1
  18. package/dist/core/codegen/schemas/effect.d.ts +13 -1
  19. package/dist/core/codegen/schemas/effect.d.ts.map +1 -1
  20. package/dist/core/codegen/schemas/effect.js +26 -3
  21. package/dist/core/codegen/schemas/effect.js.map +1 -1
  22. package/dist/core/codegen/schemas/fallback.d.ts +17 -1
  23. package/dist/core/codegen/schemas/fallback.d.ts.map +1 -1
  24. package/dist/core/codegen/schemas/fallback.js +31 -15
  25. package/dist/core/codegen/schemas/fallback.js.map +1 -1
  26. package/dist/core/codegen/schemas/number.d.ts.map +1 -1
  27. package/dist/core/codegen/schemas/number.js +35 -35
  28. package/dist/core/codegen/schemas/number.js.map +1 -1
  29. package/dist/core/codegen/schemas/object.d.ts.map +1 -1
  30. package/dist/core/codegen/schemas/object.js +64 -29
  31. package/dist/core/codegen/schemas/object.js.map +1 -1
  32. package/dist/core/codegen/schemas/string.d.ts.map +1 -1
  33. package/dist/core/codegen/schemas/string.js +3 -3
  34. package/dist/core/codegen/schemas/string.js.map +1 -1
  35. package/dist/core/codegen/schemas/template-literal.d.ts.map +1 -1
  36. package/dist/core/codegen/schemas/template-literal.js +1 -1
  37. package/dist/core/codegen/schemas/template-literal.js.map +1 -1
  38. package/dist/core/extract/index.d.ts.map +1 -1
  39. package/dist/core/extract/index.js +2 -0
  40. package/dist/core/extract/index.js.map +1 -1
  41. package/dist/core/extract/zod-version.d.ts +78 -0
  42. package/dist/core/extract/zod-version.d.ts.map +1 -0
  43. package/dist/core/extract/zod-version.js +109 -0
  44. package/dist/core/extract/zod-version.js.map +1 -0
  45. package/dist/jit.d.ts.map +1 -1
  46. package/dist/jit.js +9 -1
  47. package/dist/jit.js.map +1 -1
  48. package/dist/runtime.d.ts +3 -0
  49. package/dist/runtime.js +4 -1
  50. package/dist/unplugin/hoist-compile.d.ts.map +1 -1
  51. package/dist/unplugin/hoist-compile.js +3 -1
  52. package/dist/unplugin/hoist-compile.js.map +1 -1
  53. package/dist/unplugin/transform.d.ts.map +1 -1
  54. package/dist/unplugin/transform.js +5 -0
  55. package/dist/unplugin/transform.js.map +1 -1
  56. package/package.json +1 -1
@@ -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 * __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"}
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 * Raise zod's synchronous-parse error. A user callback that hands back a\n * Promise — a `.refine()` predicate, a `.transform()`, a `z.preprocess()` —\n * makes zod's sync `safeParse` throw `$ZodAsyncError` rather than treat the\n * Promise as a value (a truthy one, for a predicate, which would ACCEPT the\n * input). The callback's source cannot tell: only an `async` function is\n * detectable at extraction time (those are delegated), and a plain function\n * that returns a Promise looks like any other. So the test is on the returned\n * value, at every call site that consumes one, with zod's own\n * `instanceof Promise` — a non-Promise thenable is a plain value to zod too.\n *\n * Hosted rather than inlined so the throw stays out of the hot path's inlining\n * budget: call sites test `x instanceof Promise` themselves and branch here\n * only in the exotic case. The compiled `parseAsync`/`safeParseAsync` wrappers\n * catch this and re-run through zod's async pipeline (see MK_VALIDATOR_DECL),\n * so an async-capable caller still gets zod's answer.\n *\n * `.catch()`, `.default()` and `.overwrite()` callbacks are deliberately NOT\n * guarded: zod substitutes whatever they return, Promise included.\n */\nexport const ZC_ASYNC_DECL = \"function __zcAsy(){throw new __zcCore.$ZodAsyncError();}\";\n\n/**\n * Run a retained zod schema for a delegated sub-schema and return its RAW\n * payload — `_zod.run` on a fresh `{value, issues: []}`, the exact call zod's\n * own `safeParse` makes — rather than the finalized `SafeParseResult`.\n *\n * The raw payload is the only place zod's abort state survives.\n * `finalizeIssue` deletes `continue` from every issue and `safeParse` builds\n * its ZodError from the finalized copies, so a delegate that went through\n * `safeParse` could not tell a `z.custom()` failure (`continue: false` — zod\n * defaults `z.custom()` to `abort: true`) from a `.refine()` one\n * (`continue: true`). A plain union prunes its options on that flag\n * (`util.aborted`): with it lost, an option failing through a delegated\n * aborting check was surfaced as the sole non-aborted option instead of inside\n * `invalid_union`. Reading the payload keeps the flag until __zcRf copies it\n * onto the finalized issue, where the union's pruning loop reads it and the\n * top-level finalizer then deletes it, as zod's does.\n *\n * `_zod.run` is also immune to the aliasing hazard `__rfp_N` guards against:\n * `__zcMkv` installs the compiled methods as own `parse`/`safeParse` slots and\n * never touches `_zod`, so a retained entry that IS the compiled schema still\n * runs zod's implementation here. A Promise result is zod's `$ZodAsyncError`,\n * as in `_safeParse`.\n */\nexport const ZC_RUN_DELEGATE_DECL =\n \"function __zcRd(z,v,c){var r=z.run({value:v,issues:[]},c);\" +\n \"if(r instanceof Promise)throw new __zcCore.$ZodAsyncError();return r;}\";\n\n/**\n * Finalize a delegate's raw issues onto the validator's list. Each goes\n * through zod's own `util.finalizeIssue` — the check's and schema's error\n * maps, the per-call ctx, `customError`, the locale, then \"Invalid input\", with\n * `inst` and `input` stripped — which is the very function `safeParse` maps\n * every issue through, so the messages are zod's byte for byte. The node's\n * path is prefixed onto the issue's relative one as zod's `prefixIssues`\n * would, and the abort marker is re-applied: an issue whose raw `continue` was\n * not `true` aborted in zod's sense (`util.aborted`), which the union pruning\n * loop reads as `continue:false` before the top-level finalizer deletes the\n * key again (see ZC_RUN_DELEGATE_DECL).\n */\nexport const ZC_DELEGATE_ISSUES_DECL =\n \"function __zcRf(s,c,e,p){var g=__zcCore.config();for(var i=0;i<s.length;i++){\" +\n \"var q=s[i],f=__zcCore.util.finalizeIssue(q,c,g);f.path=p.concat(f.path);\" +\n \"if(q.continue!==true)f.continue=false;e.push(f);}}\";\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 at whose root the\n * superRefine sits reads the flag to mark itself aborted, matching how zod\n * prunes option errors. The aborting issue ALSO keeps a `continue:false`\n * marker of its own, because zod's `util.aborted` reads the flag off the\n * issues and those travel up through containers where the payload flag does\n * not: a fatal superRefine on an object's property aborts the union option\n * holding the object. The top-level finalizer deletes the marker, as zod's\n * `finalizeIssue` does, so no user-visible issue carries it.\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;t.continue=false;}\" +\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 __zcPf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,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;AAyB7B,MAAa,uBACX;;;;;;;;;;;;;AAeF,MAAa,0BACX;;;;;;;;;;;;;;;;;;;;;;AAyBF,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;CACV,SAAS;CACT,QAAQ;CACR,QAAQ;AACV"}
@@ -1 +1 @@
1
- {"version":3,"file":"array.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/array.ts"],"mappings":";;;iBAgBgB,UAAU,IAAI;EAAa;GAAiB,GAAG;iBA+E/C,UAAU,IAAI,SAAS,GAAG"}
1
+ {"version":3,"file":"array.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/array.ts"],"mappings":";;;iBAegB,UAAU,IAAI;EAAa;GAAiB,GAAG;iBA+E/C,UAAU,IAAI,SAAS,GAAG"}
@@ -1,8 +1,8 @@
1
- import { checkPriority, declareFastTemps, emitEffectCallable, emitRuntimeHelper, extendPath, hasMutation } from "../context.js";
1
+ import { checkPriority, declareFastTemps, emitRuntimeHelper, extendPath, hasMutation } from "../context.js";
2
2
  import { emit } from "../emit.js";
3
3
  import { invalidType, tooBig, tooSmall } from "../emit-issue.js";
4
4
  import { ZC_AB_DECL } from "../issue-decls.js";
5
- import { refineCheck, superRefineCheck, superRefineFastTest } from "./effect.js";
5
+ import { fastRefineTest, refineCheck, superRefineCheck, superRefineFastTest } from "./effect.js";
6
6
  import { whenGatedSizeChecks } from "./sizeable.js";
7
7
  //#region src/core/codegen/schemas/array.ts
8
8
  function slowArray(ir, g) {
@@ -90,7 +90,7 @@ function fastArray(ir, g) {
90
90
  g.ctx.preamble.push(`function ${helperName}(a){${declareFastTemps(elemGen.scope)}for(var ${elemVar},i=0;i<a.length;i++){${elemVar}=a[i];if(!(${elemCheck})){return false;}}return true;}`);
91
91
  parts.push(`${helperName}(${x})`);
92
92
  }
93
- for (const check of ir.checks) if (check.kind === "refine_effect") parts.push(`${emitEffectCallable(g.ctx, check)}(${x})`);
93
+ for (const check of ir.checks) if (check.kind === "refine_effect") parts.push(fastRefineTest(check, x, g));
94
94
  else if (check.kind === "super_refine_effect") parts.push(superRefineFastTest(check, x, g));
95
95
  return parts.join("&&");
96
96
  }
@@ -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\", 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,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AM,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
+ {"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 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 { fastRefineTest, 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(fastRefineTest(check, x, g));\n } else if (check.kind === \"super_refine_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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,eAAe,OAAO,GAAG,CAAC,CAAC;MACjC,IAAI,MAAM,SAAS,uBACxB,MAAM,KAAK,oBAAoB,OAAO,GAAG,CAAC,CAAC;CAI/C,OAAO,MAAM,KAAK,IAAI;AACxB"}
@@ -15,6 +15,18 @@ declare function slowEffect(ir: TransformEffectIR | PreprocessEffectIR, g: SlowG
15
15
  * @param g - SlowGen context (provides path, issues)
16
16
  */
17
17
  declare function refineCheck(check: RefineEffectCheckIR, expr: string, g: SlowGen): string;
18
+ /**
19
+ * Fast-path test for a RefineEffectCheckIR: the predicate's verdict, bound to a
20
+ * local so a Promise can be told apart from a truthy value. A Promise throws
21
+ * zod's `$ZodAsyncError` right here, EAGERLY: zod's `runChecks` throws the
22
+ * moment a check returns a Promise under a synchronous parse — before any later
23
+ * check, and even inside a union whose next option would have matched — so
24
+ * deferring the throw to the slow walk (which a fast-eligible schema only runs
25
+ * when `.error` is read) would turn zod's throw into a failure result. The
26
+ * throw itself lives in a hosted helper, so the hot expression only pays the
27
+ * `instanceof` test.
28
+ */
29
+ declare function fastRefineTest(check: RefineEffectCheckIR, expr: string, g: FastGen): string;
18
30
  /**
19
31
  * Fast-path test for a SuperRefineEffectCheckIR: a boolean term reporting that
20
32
  * the callback added no issue and left the value alone (see ZC_SR_OK_DECL).
@@ -34,5 +46,5 @@ declare function superRefineFastTest(check: SuperRefineEffectCheckIR, expr: stri
34
46
  */
35
47
  declare function superRefineCheck(check: SuperRefineEffectCheckIR, expr: string, g: SlowGen): string;
36
48
  //#endregion
37
- export { refineCheck, slowEffect, superRefineCheck, superRefineFastTest };
49
+ export { fastRefineTest, refineCheck, slowEffect, superRefineCheck, superRefineFastTest };
38
50
  //# sourceMappingURL=effect.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"effect.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/effect.ts"],"mappings":";;;;;;;iBAqBgB,WAAW,IAAI,oBAAoB,oBAAoB,GAAG;;;;;;;;;iBAmC1D,YAAY,OAAO,qBAAqB,cAAc,GAAG;;;;;iBA+CzD,oBACd,OAAO,0BACP,cACA,GAAG;;;;;;;;;;;;;iBAmBW,iBACd,OAAO,0BACP,cACA,GAAG"}
1
+ {"version":3,"file":"effect.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/effect.ts"],"mappings":";;;;;;;iBAqBgB,WAAW,IAAI,oBAAoB,oBAAoB,GAAG;;;;;;;;;iBAyC1D,YAAY,OAAO,qBAAqB,cAAc,GAAG;;;;;;;;;;;;iBAkDzD,eAAe,OAAO,qBAAqB,cAAc,GAAG;;;;;iBAqB5D,oBACd,OAAO,0BACP,cACA,GAAG;;;;;;;;;;;;;iBAmBW,iBACd,OAAO,0BACP,cACA,GAAG"}
@@ -1,16 +1,18 @@
1
1
  import { emitConstant, emitEffectCallable, emitRuntimeHelper, extendStaticPath, extendStaticPathIndex } from "../context.js";
2
2
  import { emit } from "../emit.js";
3
- import { ZC_SR_DECL, ZC_SR_OK_DECL, ZC_SR_RUN_DECL } from "../issue-decls.js";
3
+ import { ZC_ASYNC_DECL, ZC_SR_DECL, ZC_SR_OK_DECL, ZC_SR_RUN_DECL } from "../issue-decls.js";
4
4
  //#region src/core/codegen/schemas/effect.ts
5
5
  /**
6
6
  * Generate code for a TransformEffectIR node.
7
7
  * Validates the inner schema, then applies the transform function and writes back the result.
8
8
  */
9
9
  function slowEffect(ir, g) {
10
+ const asy = emitRuntimeHelper(g.ctx, "__zcAsy", ZC_ASYNC_DECL);
10
11
  if (ir.effectKind === "preprocess") {
11
12
  const valueVar = g.temp("pv");
12
13
  return `${emit`
13
14
  var ${valueVar}=${emitEffectCallable(g.ctx, ir)}(${g.input});
15
+ if(${valueVar} instanceof Promise)${asy}();
14
16
  ${g.output}=${valueVar};
15
17
  ${g.visit(ir.inner, {
16
18
  input: valueVar,
@@ -27,6 +29,7 @@ function slowEffect(ir, g) {
27
29
  ${innerCode}
28
30
  if(${g.issues}.length===${beforeVar}){
29
31
  ${g.output}=${emitEffectCallable(g.ctx, ir)}(${g.output});
32
+ if(${g.output} instanceof Promise)${asy}();
30
33
  }${abortBranch}
31
34
  `}\n`;
32
35
  }
@@ -43,12 +46,32 @@ function refineCheck(check, expr, g) {
43
46
  const messageProp = message === void 0 ? "" : `,message:${JSON.stringify(message)}`;
44
47
  const path = (check.path ?? []).reduce((acc, segment) => typeof segment === "number" ? extendStaticPathIndex(acc, segment) : extendStaticPath(acc, segment), g.path);
45
48
  const paramsProp = check.paramsRefIndex === void 0 ? "" : `,params:${emitConstant(g.ctx, "rpa", `__rf[${check.paramsRefIndex}]`)}`;
49
+ const asy = emitRuntimeHelper(g.ctx, "__zcAsy", ZC_ASYNC_DECL);
50
+ const result = g.temp("rr");
46
51
  return emit`
47
- if(!${emitEffectCallable(g.ctx, check)}(${expr})){
52
+ var ${result}=${emitEffectCallable(g.ctx, check)}(${expr});
53
+ if(${result} instanceof Promise)${asy}();
54
+ if(!${result}){
48
55
  ${g.issues}.push({code:"custom",path:${path}${paramsProp},input:${expr}${messageProp}});
49
56
  }`;
50
57
  }
51
58
  /**
59
+ * Fast-path test for a RefineEffectCheckIR: the predicate's verdict, bound to a
60
+ * local so a Promise can be told apart from a truthy value. A Promise throws
61
+ * zod's `$ZodAsyncError` right here, EAGERLY: zod's `runChecks` throws the
62
+ * moment a check returns a Promise under a synchronous parse — before any later
63
+ * check, and even inside a union whose next option would have matched — so
64
+ * deferring the throw to the slow walk (which a fast-eligible schema only runs
65
+ * when `.error` is read) would turn zod's throw into a failure result. The
66
+ * throw itself lives in a hosted helper, so the hot expression only pays the
67
+ * `instanceof` test.
68
+ */
69
+ function fastRefineTest(check, expr, g) {
70
+ const asy = emitRuntimeHelper(g.ctx, "__zcAsy", ZC_ASYNC_DECL);
71
+ const verdict = g.local("fr");
72
+ return `((${verdict}=${emitEffectCallable(g.ctx, check)}(${expr})) instanceof Promise?${asy}():${verdict})`;
73
+ }
74
+ /**
52
75
  * Declare the shared invoker both superRefine helpers call. It is module-local
53
76
  * rather than an imported helper (lean mode declares it in the runtime module
54
77
  * beside them), so inline mode must place it in the preamble itself.
@@ -87,6 +110,6 @@ function superRefineCheck(check, expr, g) {
87
110
  return code;
88
111
  }
89
112
  //#endregion
90
- export { refineCheck, slowEffect, superRefineCheck, superRefineFastTest };
113
+ export { fastRefineTest, refineCheck, slowEffect, superRefineCheck, superRefineFastTest };
91
114
 
92
115
  //# sourceMappingURL=effect.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"effect.js","names":[],"sources":["../../../../src/core/codegen/schemas/effect.ts"],"sourcesContent":["import type {\n PreprocessEffectIR,\n RefineEffectCheckIR,\n SuperRefineEffectCheckIR,\n TransformEffectIR,\n} from \"../../types.js\";\nimport type { FastGen, SlowGen } from \"../context.js\";\nimport {\n emitConstant,\n emitEffectCallable,\n emitRuntimeHelper,\n extendStaticPath,\n extendStaticPathIndex,\n} from \"../context.js\";\nimport { emit } from \"../emit.js\";\nimport { ZC_SR_DECL, ZC_SR_OK_DECL, ZC_SR_RUN_DECL } from \"../issue-decls.js\";\n\n/**\n * Generate code for a TransformEffectIR node.\n * Validates the inner schema, then applies the transform function and writes back the result.\n */\nexport function slowEffect(ir: TransformEffectIR | PreprocessEffectIR, g: SlowGen): string {\n if (ir.effectKind === \"preprocess\") {\n const valueVar = g.temp(\"pv\");\n return `${emit`\n var ${valueVar}=${emitEffectCallable(g.ctx, ir)}(${g.input});\n ${g.output}=${valueVar};\n ${g.visit(ir.inner, { input: valueVar, output: g.output, aborted: g.aborted })}\n `}\\n`;\n }\n\n const beforeVar = g.temp(\"ib\");\n const innerCode = g.visit(ir.inner);\n // A transform is `inner.transform(fn)` = a pipe(inner, transform): zod's\n // handlePipeResult aborts when `inner` produces any issue. Inside a union the\n // option must therefore count as aborted even if `inner`'s only issue is a\n // non-aborting `custom`/check-level code (mirrors slowPipe's abort branch).\n const abortBranch = g.aborted ? `else{${g.aborted}=true;}` : \"\";\n\n return `${emit`\n var ${beforeVar}=${g.issues}.length;\n ${innerCode}\n if(${g.issues}.length===${beforeVar}){\n ${g.output}=${emitEffectCallable(g.ctx, ir)}(${g.output});\n }${abortBranch}\n `}\\n`;\n}\n\n/**\n * Generate code for a RefineEffectCheckIR (inline refine function call).\n * Called from string/number/object check loops when a refine_effect is encountered.\n *\n * @param check - The refine effect check IR\n * @param expr - The expression to validate (may differ from g.input, e.g. objVar in object generators)\n * @param g - SlowGen context (provides path, issues)\n */\nexport function refineCheck(check: RefineEffectCheckIR, expr: string, g: SlowGen): string {\n // The refine's own message wins; without one, zod's finalizeIssue falls\n // through to the error map of the schema the check is attached to (the check\n // stamps its owner onto the issue), so the node's schema-level message is the\n // next rung. With neither, __zcFin applies the locale default.\n const message = check.message ?? g.typeMsg;\n const messageProp = message === undefined ? \"\" : `,message:${JSON.stringify(message)}`;\n // `.refine(fn, { path })` reports against a member of the refined value, so\n // the configured segments extend this node's path.\n const path = (check.path ?? []).reduce<string>(\n (acc, segment) =>\n typeof segment === \"number\"\n ? extendStaticPathIndex(acc, segment)\n : extendStaticPath(acc, segment),\n g.path,\n );\n // `.refine(fn, { params })`: $ZodCustom's check does\n // `if (def.params) _iss.params = def.params`, so the key is present only when\n // the schema declared one, and holds the ORIGINAL object — the extractor\n // parked it in `__rf` precisely so the reference survives (see\n // RefineEffectCheckIR.paramsRefIndex). Placed before `message` to keep the\n // key order zod produces.\n const paramsProp =\n check.paramsRefIndex === undefined\n ? \"\"\n : `,params:${emitConstant(g.ctx, \"rpa\", `__rf[${check.paramsRefIndex}]`)}`;\n return emit`\n if(!${emitEffectCallable(g.ctx, check)}(${expr})){\n ${g.issues}.push({code:\"custom\",path:${path}${paramsProp},input:${expr}${messageProp}});\n }`;\n}\n\n/**\n * Declare the shared invoker both superRefine helpers call. It is module-local\n * rather than an imported helper (lean mode declares it in the runtime module\n * beside them), so inline mode must place it in the preamble itself.\n */\nfunction emitSuperRefineRunner(ctx: SlowGen[\"ctx\"]): void {\n if (ctx.mode !== \"lean\" && !ctx.preamble.includes(ZC_SR_RUN_DECL)) {\n ctx.preamble.push(ZC_SR_RUN_DECL);\n }\n}\n\n/**\n * Fast-path test for a SuperRefineEffectCheckIR: a boolean term reporting that\n * the callback added no issue and left the value alone (see ZC_SR_OK_DECL).\n */\nexport function superRefineFastTest(\n check: SuperRefineEffectCheckIR,\n expr: string,\n g: FastGen,\n): string {\n emitSuperRefineRunner(g.ctx);\n const ok = emitRuntimeHelper(g.ctx, \"__zcSrOk\", ZC_SR_OK_DECL);\n return `${ok}(${emitEffectCallable(g.ctx, check)},${expr})`;\n}\n\n/**\n * Generate code for a SuperRefineEffectCheckIR: call the payload-taking\n * callback with a synthesized `{ value, issues }` and merge what it collected.\n * zod's own wrapper installs `addIssue` and normalizes the result, so the\n * issues are zod's — the helper only reprojects them onto this node's path and\n * strips the internal bookkeeping zod deletes before they become visible.\n *\n * The payload's `value` is writable public API, so it is written back to the\n * output slot the way an overwrite effect is. This walk is always the eager one\n * (the node reports as mutating, see hasMutation), so the write-back lands on\n * every parse that reaches it — not only on failures.\n */\nexport function superRefineCheck(\n check: SuperRefineEffectCheckIR,\n expr: string,\n g: SlowGen,\n): string {\n emitSuperRefineRunner(g.ctx);\n const helper = emitRuntimeHelper(g.ctx, \"__zcSr\", ZC_SR_DECL);\n const fn = emitEffectCallable(g.ctx, check);\n const p = g.temp(\"sp\");\n // The owning schema's message covers an added issue that carries none of its\n // own, as it does for a refine (see refineCheck); the helper applies it.\n const msgArg = g.typeMsg === undefined ? \"\" : `,${JSON.stringify(g.typeMsg)}`;\n let code = `var ${p}=${helper}(${fn},${expr},${g.path},${g.issues}${msgArg});${g.output}=${p}.value;`;\n // Inside a union option, an aborting issue must mark the option aborted so\n // pruning matches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AAK,EAAE,GAAG,KAAK;QAC3C,EAAE,OAAO,4BAA4B,OAAO,WAAW,SAAS,OAAO,YAAY;;AAE3F;;;;;;AAOA,SAAS,sBAAsB,KAA2B;CACxD,IAAI,IAAI,SAAS,UAAU,CAAC,IAAI,SAAS,SAAA,+GAAuB,GAC9D,IAAI,SAAS,KAAK,cAAc;AAEpC;;;;;AAMA,SAAgB,oBACd,OACA,MACA,GACQ;CACR,sBAAsB,EAAE,GAAG;CAE3B,OAAO,GADI,kBAAkB,EAAE,KAAK,YAAY,aACrC,EAAE,GAAG,mBAAmB,EAAE,KAAK,KAAK,EAAE,GAAG,KAAK;AAC3D;;;;;;;;;;;;;AAcA,SAAgB,iBACd,OACA,MACA,GACQ;CACR,sBAAsB,EAAE,GAAG;CAC3B,MAAM,SAAS,kBAAkB,EAAE,KAAK,UAAU,UAAU;CAC5D,MAAM,KAAK,mBAAmB,EAAE,KAAK,KAAK;CAC1C,MAAM,IAAI,EAAE,KAAK,IAAI;CAGrB,MAAM,SAAS,EAAE,YAAY,KAAA,IAAY,KAAK,IAAI,KAAK,UAAU,EAAE,OAAO;CAC1E,IAAI,OAAO,OAAO,EAAE,GAAG,OAAO,GAAG,GAAG,GAAG,KAAK,GAAG,EAAE,KAAK,GAAG,EAAE,SAAS,OAAO,IAAI,EAAE,OAAO,GAAG,EAAE;CAG7F,IAAI,EAAE,SAAS,QAAQ,MAAM,EAAE,YAAY,EAAE,QAAQ;CACrD,OAAO;AACT"}
1
+ {"version":3,"file":"effect.js","names":[],"sources":["../../../../src/core/codegen/schemas/effect.ts"],"sourcesContent":["import type {\n PreprocessEffectIR,\n RefineEffectCheckIR,\n SuperRefineEffectCheckIR,\n TransformEffectIR,\n} from \"../../types.js\";\nimport type { FastGen, SlowGen } from \"../context.js\";\nimport {\n emitConstant,\n emitEffectCallable,\n emitRuntimeHelper,\n extendStaticPath,\n extendStaticPathIndex,\n} from \"../context.js\";\nimport { emit } from \"../emit.js\";\nimport { ZC_ASYNC_DECL, ZC_SR_DECL, ZC_SR_OK_DECL, ZC_SR_RUN_DECL } from \"../issue-decls.js\";\n\n/**\n * Generate code for a TransformEffectIR node.\n * Validates the inner schema, then applies the transform function and writes back the result.\n */\nexport function slowEffect(ir: TransformEffectIR | PreprocessEffectIR, g: SlowGen): string {\n // A callback that returns a Promise is zod's synchronous-parse error, not a\n // value (see ZC_ASYNC_DECL); zod tests `_out instanceof Promise` right after\n // the call, so the guard sits at the same point.\n const asy = emitRuntimeHelper(g.ctx, \"__zcAsy\", ZC_ASYNC_DECL);\n if (ir.effectKind === \"preprocess\") {\n const valueVar = g.temp(\"pv\");\n return `${emit`\n var ${valueVar}=${emitEffectCallable(g.ctx, ir)}(${g.input});\n if(${valueVar} instanceof Promise)${asy}();\n ${g.output}=${valueVar};\n ${g.visit(ir.inner, { input: valueVar, output: g.output, aborted: g.aborted })}\n `}\\n`;\n }\n\n const beforeVar = g.temp(\"ib\");\n const innerCode = g.visit(ir.inner);\n // A transform is `inner.transform(fn)` = a pipe(inner, transform): zod's\n // handlePipeResult aborts when `inner` produces any issue. Inside a union the\n // option must therefore count as aborted even if `inner`'s only issue is a\n // non-aborting `custom`/check-level code (mirrors slowPipe's abort branch).\n const abortBranch = g.aborted ? `else{${g.aborted}=true;}` : \"\";\n\n return `${emit`\n var ${beforeVar}=${g.issues}.length;\n ${innerCode}\n if(${g.issues}.length===${beforeVar}){\n ${g.output}=${emitEffectCallable(g.ctx, ir)}(${g.output});\n if(${g.output} instanceof Promise)${asy}();\n }${abortBranch}\n `}\\n`;\n}\n\n/**\n * Generate code for a RefineEffectCheckIR (inline refine function call).\n * Called from string/number/object check loops when a refine_effect is encountered.\n *\n * @param check - The refine effect check IR\n * @param expr - The expression to validate (may differ from g.input, e.g. objVar in object generators)\n * @param g - SlowGen context (provides path, issues)\n */\nexport function refineCheck(check: RefineEffectCheckIR, expr: string, g: SlowGen): string {\n // The refine's own message wins; without one, zod's finalizeIssue falls\n // through to the error map of the schema the check is attached to (the check\n // stamps its owner onto the issue), so the node's schema-level message is the\n // next rung. With neither, __zcFin applies the locale default.\n const message = check.message ?? g.typeMsg;\n const messageProp = message === undefined ? \"\" : `,message:${JSON.stringify(message)}`;\n // `.refine(fn, { path })` reports against a member of the refined value, so\n // the configured segments extend this node's path.\n const path = (check.path ?? []).reduce<string>(\n (acc, segment) =>\n typeof segment === \"number\"\n ? extendStaticPathIndex(acc, segment)\n : extendStaticPath(acc, segment),\n g.path,\n );\n // `.refine(fn, { params })`: $ZodCustom's check does\n // `if (def.params) _iss.params = def.params`, so the key is present only when\n // the schema declared one, and holds the ORIGINAL object — the extractor\n // parked it in `__rf` precisely so the reference survives (see\n // RefineEffectCheckIR.paramsRefIndex). Placed before `message` to keep the\n // key order zod produces.\n const paramsProp =\n check.paramsRefIndex === undefined\n ? \"\"\n : `,params:${emitConstant(g.ctx, \"rpa\", `__rf[${check.paramsRefIndex}]`)}`;\n // The predicate's return value is tested for a Promise before its truthiness\n // (see ZC_ASYNC_DECL): a Promise is truthy, so without the guard a plain\n // function returning one would ACCEPT every input where zod throws.\n const asy = emitRuntimeHelper(g.ctx, \"__zcAsy\", ZC_ASYNC_DECL);\n const result = g.temp(\"rr\");\n return emit`\n var ${result}=${emitEffectCallable(g.ctx, check)}(${expr});\n if(${result} instanceof Promise)${asy}();\n if(!${result}){\n ${g.issues}.push({code:\"custom\",path:${path}${paramsProp},input:${expr}${messageProp}});\n }`;\n}\n\n/**\n * Fast-path test for a RefineEffectCheckIR: the predicate's verdict, bound to a\n * local so a Promise can be told apart from a truthy value. A Promise throws\n * zod's `$ZodAsyncError` right here, EAGERLY: zod's `runChecks` throws the\n * moment a check returns a Promise under a synchronous parse — before any later\n * check, and even inside a union whose next option would have matched — so\n * deferring the throw to the slow walk (which a fast-eligible schema only runs\n * when `.error` is read) would turn zod's throw into a failure result. The\n * throw itself lives in a hosted helper, so the hot expression only pays the\n * `instanceof` test.\n */\nexport function fastRefineTest(check: RefineEffectCheckIR, expr: string, g: FastGen): string {\n const asy = emitRuntimeHelper(g.ctx, \"__zcAsy\", ZC_ASYNC_DECL);\n const verdict = g.local(\"fr\");\n return `((${verdict}=${emitEffectCallable(g.ctx, check)}(${expr})) instanceof Promise?${asy}():${verdict})`;\n}\n\n/**\n * Declare the shared invoker both superRefine helpers call. It is module-local\n * rather than an imported helper (lean mode declares it in the runtime module\n * beside them), so inline mode must place it in the preamble itself.\n */\nfunction emitSuperRefineRunner(ctx: SlowGen[\"ctx\"]): void {\n if (ctx.mode !== \"lean\" && !ctx.preamble.includes(ZC_SR_RUN_DECL)) {\n ctx.preamble.push(ZC_SR_RUN_DECL);\n }\n}\n\n/**\n * Fast-path test for a SuperRefineEffectCheckIR: a boolean term reporting that\n * the callback added no issue and left the value alone (see ZC_SR_OK_DECL).\n */\nexport function superRefineFastTest(\n check: SuperRefineEffectCheckIR,\n expr: string,\n g: FastGen,\n): string {\n emitSuperRefineRunner(g.ctx);\n const ok = emitRuntimeHelper(g.ctx, \"__zcSrOk\", ZC_SR_OK_DECL);\n return `${ok}(${emitEffectCallable(g.ctx, check)},${expr})`;\n}\n\n/**\n * Generate code for a SuperRefineEffectCheckIR: call the payload-taking\n * callback with a synthesized `{ value, issues }` and merge what it collected.\n * zod's own wrapper installs `addIssue` and normalizes the result, so the\n * issues are zod's — the helper only reprojects them onto this node's path and\n * strips the internal bookkeeping zod deletes before they become visible.\n *\n * The payload's `value` is writable public API, so it is written back to the\n * output slot the way an overwrite effect is. This walk is always the eager one\n * (the node reports as mutating, see hasMutation), so the write-back lands on\n * every parse that reaches it — not only on failures.\n */\nexport function superRefineCheck(\n check: SuperRefineEffectCheckIR,\n expr: string,\n g: SlowGen,\n): string {\n emitSuperRefineRunner(g.ctx);\n const helper = emitRuntimeHelper(g.ctx, \"__zcSr\", ZC_SR_DECL);\n const fn = emitEffectCallable(g.ctx, check);\n const p = g.temp(\"sp\");\n // The owning schema's message covers an added issue that carries none of its\n // own, as it does for a refine (see refineCheck); the helper applies it.\n const msgArg = g.typeMsg === undefined ? \"\" : `,${JSON.stringify(g.typeMsg)}`;\n let code = `var ${p}=${helper}(${fn},${expr},${g.path},${g.issues}${msgArg});${g.output}=${p}.value;`;\n // Inside a union option, an aborting issue must mark the option aborted so\n // pruning matches zod (see ZC_SR_DECL); elsewhere the flag is unobserved.\n if (g.aborted) code += `if(${p}.aborted){${g.aborted}=true;}`;\n return code;\n}\n"],"mappings":";;;;;;;;AAqBA,SAAgB,WAAW,IAA4C,GAAoB;CAIzF,MAAM,MAAM,kBAAkB,EAAE,KAAK,WAAW,aAAa;CAC7D,IAAI,GAAG,eAAe,cAAc;EAClC,MAAM,WAAW,EAAE,KAAK,IAAI;EAC5B,OAAO,GAAG,IAAI;YACN,SAAS,GAAG,mBAAmB,EAAE,KAAK,EAAE,EAAE,GAAG,EAAE,MAAM;WACtD,SAAS,sBAAsB,IAAI;QACtC,EAAE,OAAO,GAAG,SAAS;QACrB,EAAE,MAAM,GAAG,OAAO;GAAE,OAAO;GAAU,QAAQ,EAAE;GAAQ,SAAS,EAAE;EAAQ,CAAC,EAAE;MAC/E;CACJ;CAEA,MAAM,YAAY,EAAE,KAAK,IAAI;CAC7B,MAAM,YAAY,EAAE,MAAM,GAAG,KAAK;CAKlC,MAAM,cAAc,EAAE,UAAU,QAAQ,EAAE,QAAQ,WAAW;CAE7D,OAAO,GAAG,IAAI;UACN,UAAU,GAAG,EAAE,OAAO;MAC1B,UAAU;SACP,EAAE,OAAO,YAAY,UAAU;QAChC,EAAE,OAAO,GAAG,mBAAmB,EAAE,KAAK,EAAE,EAAE,GAAG,EAAE,OAAO;WACnD,EAAE,OAAO,sBAAsB,IAAI;OACvC,YAAY;IACf;AACJ;;;;;;;;;AAUA,SAAgB,YAAY,OAA4B,MAAc,GAAoB;CAKxF,MAAM,UAAU,MAAM,WAAW,EAAE;CACnC,MAAM,cAAc,YAAY,KAAA,IAAY,KAAK,YAAY,KAAK,UAAU,OAAO;CAGnF,MAAM,QAAQ,MAAM,QAAQ,CAAC,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C1C,MAAM,IAAI,EAAE,KAAK,IAAI;CAGrB,MAAM,SAAS,EAAE,YAAY,KAAA,IAAY,KAAK,IAAI,KAAK,UAAU,EAAE,OAAO;CAC1E,IAAI,OAAO,OAAO,EAAE,GAAG,OAAO,GAAG,GAAG,GAAG,KAAK,GAAG,EAAE,KAAK,GAAG,EAAE,SAAS,OAAO,IAAI,EAAE,OAAO,GAAG,EAAE;CAG7F,IAAI,EAAE,SAAS,QAAQ,MAAM,EAAE,YAAY,EAAE,QAAQ;CACrD,OAAO;AACT"}
@@ -2,7 +2,23 @@ import { FallbackIR } from "../../types.js";
2
2
  import { SlowGen } from "../context.js";
3
3
  //#region src/core/codegen/schemas/fallback.d.ts
4
4
  declare function slowFallback(ir: FallbackIR, g: SlowGen): string;
5
- /** Delegate a cold slow-walk leaf to a pristine retained Zod schema. */
5
+ /**
6
+ * Delegate a cold slow-walk leaf to a pristine retained Zod schema.
7
+ *
8
+ * The schema is run through `_zod.run` and its RAW payload read, not through
9
+ * `safeParse`: the payload is where zod's per-issue `continue` flags and the
10
+ * `aborted` bit still exist, and a plain union prunes its options on exactly
11
+ * those (see ZC_RUN_DELEGATE_DECL). The issues are then finalized by zod's own
12
+ * `finalizeIssue` and re-homed under this node's path (ZC_DELEGATE_ISSUES_DECL),
13
+ * so what lands in the validator's list is what `safeParse` would have built,
14
+ * plus a `continue:false` marker on each aborting issue that the top-level
15
+ * finalizer strips again. The per-call `{async:false}` ctx is the one zod's
16
+ * `_safeParse` allocates, handed to both `run` and `finalizeIssue` as zod does.
17
+ *
18
+ * `payload.aborted` — set by a pipe whose `in` failed — is forwarded only when
19
+ * this delegate IS a union option (`g.aborted` bound). Nested deeper it is
20
+ * dropped, as zod's `handlePropertyResult` drops it: only the issues travel up.
21
+ */
6
22
  declare function slowZodDelegate(refIndex: number, g: SlowGen, onFailure?: string): string;
7
23
  //#endregion
8
24
  export { slowFallback, slowZodDelegate };
@@ -1 +1 @@
1
- {"version":3,"file":"fallback.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/fallback.ts"],"mappings":";;;iBAKgB,aAAa,IAAI,YAAY,GAAG;;iBAQhC,gBAAgB,kBAAkB,GAAG,SAAS"}
1
+ {"version":3,"file":"fallback.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/fallback.ts"],"mappings":";;;iBAMgB,aAAa,IAAI,YAAY,GAAG;;;;;;;;;;;;;;;;;;iBAwBhC,gBAAgB,kBAAkB,GAAG,SAAS"}
@@ -1,28 +1,44 @@
1
- import { emitRfDelegate } from "../context.js";
1
+ import { emitRfZod, emitRuntimeHelper } from "../context.js";
2
2
  import { emit } from "../emit.js";
3
+ import { ZC_DELEGATE_ISSUES_DECL, ZC_RUN_DELEGATE_DECL } from "../issue-decls.js";
3
4
  //#region src/core/codegen/schemas/fallback.ts
4
5
  function slowFallback(ir, g) {
5
6
  if (ir.refIndex !== void 0) return slowZodDelegate(ir.refIndex, g);
6
7
  return `${g.issues}.push({code:"custom",path:${g.path},message:"Fallback schema: ${ir.reason}"});\n`;
7
8
  }
8
- /** Delegate a cold slow-walk leaf to a pristine retained Zod schema. */
9
+ /**
10
+ * Delegate a cold slow-walk leaf to a pristine retained Zod schema.
11
+ *
12
+ * The schema is run through `_zod.run` and its RAW payload read, not through
13
+ * `safeParse`: the payload is where zod's per-issue `continue` flags and the
14
+ * `aborted` bit still exist, and a plain union prunes its options on exactly
15
+ * those (see ZC_RUN_DELEGATE_DECL). The issues are then finalized by zod's own
16
+ * `finalizeIssue` and re-homed under this node's path (ZC_DELEGATE_ISSUES_DECL),
17
+ * so what lands in the validator's list is what `safeParse` would have built,
18
+ * plus a `continue:false` marker on each aborting issue that the top-level
19
+ * finalizer strips again. The per-call `{async:false}` ctx is the one zod's
20
+ * `_safeParse` allocates, handed to both `run` and `finalizeIssue` as zod does.
21
+ *
22
+ * `payload.aborted` — set by a pipe whose `in` failed — is forwarded only when
23
+ * this delegate IS a union option (`g.aborted` bound). Nested deeper it is
24
+ * dropped, as zod's `handlePropertyResult` drops it: only the issues travel up.
25
+ */
9
26
  function slowZodDelegate(refIndex, g, onFailure = "") {
10
- const idx = refIndex;
11
- const delegate = emitRfDelegate(g.ctx, idx);
12
- const rVar = `__rf_r${idx}`;
13
- const iVar = `__rf_i${idx}`;
14
- const jVar = `__rf_j${idx}`;
27
+ const zod = emitRfZod(g.ctx, refIndex);
28
+ const run = emitRuntimeHelper(g.ctx, "__zcRd", ZC_RUN_DELEGATE_DECL);
29
+ const finalize = emitRuntimeHelper(g.ctx, "__zcRf", ZC_DELEGATE_ISSUES_DECL);
30
+ const cVar = `__rf_c${refIndex}`;
31
+ const rVar = `__rf_r${refIndex}`;
32
+ const abort = g.aborted === void 0 ? "" : `if(${rVar}.aborted===true){${g.aborted}=true;}`;
15
33
  return `${emit`
16
- var ${rVar}=${delegate}(${g.input});
17
- if(!${rVar}.success){
34
+ var ${cVar}={async:false};
35
+ var ${rVar}=${run}(${zod},${g.input},${cVar});
36
+ if(${rVar}.issues.length){
18
37
  ${onFailure}
19
- var ${iVar}=${rVar}.error.issues;
20
- for(var ${jVar}=0;${jVar}<${iVar}.length;${jVar}++){
21
- ${g.issues}.push({...${iVar}[${jVar}],
22
- path:${g.path}.concat(${iVar}[${jVar}].path)});
23
- }
38
+ ${finalize}(${rVar}.issues,${cVar},${g.issues},${g.path});
39
+ ${abort}
24
40
  }else{
25
- ${g.output}=${rVar}.data;
41
+ ${g.output}=${rVar}.value;
26
42
  }
27
43
  `}\n`;
28
44
  }
@@ -1 +1 @@
1
- {"version":3,"file":"fallback.js","names":[],"sources":["../../../../src/core/codegen/schemas/fallback.ts"],"sourcesContent":["import type { FallbackIR } from \"../../types.js\";\nimport type { SlowGen } from \"../context.js\";\nimport { emitRfDelegate } from \"../context.js\";\nimport { emit } from \"../emit.js\";\n\nexport function slowFallback(ir: FallbackIR, g: SlowGen): string {\n if (ir.refIndex !== undefined) {\n return slowZodDelegate(ir.refIndex, g);\n }\n return `${g.issues}.push({code:\"custom\",path:${g.path},message:\"Fallback schema: ${ir.reason}\"});\\n`;\n}\n\n/** Delegate a cold slow-walk leaf to a pristine retained Zod schema. */\nexport function slowZodDelegate(refIndex: number, g: SlowGen, onFailure = \"\"): string {\n const idx = refIndex;\n // Captured pre-__zcMkv (emitRfDelegate): a per-parse `__rf[N].safeParse`\n // read resolves to the compiled validator itself when CSE/dedup or an\n // identifier schemaExpr makes the entry alias the mutated schema object.\n const delegate = emitRfDelegate(g.ctx, idx);\n const rVar = `__rf_r${idx}`;\n const iVar = `__rf_i${idx}`;\n const jVar = `__rf_j${idx}`;\n return `${emit`\n var ${rVar}=${delegate}(${g.input});\n if(!${rVar}.success){\n ${onFailure}\n var ${iVar}=${rVar}.error.issues;\n for(var ${jVar}=0;${jVar}<${iVar}.length;${jVar}++){\n ${g.issues}.push({...${iVar}[${jVar}],\n path:${g.path}.concat(${iVar}[${jVar}].path)});\n }\n }else{\n ${g.output}=${rVar}.data;\n }\n `}\\n`;\n}\n"],"mappings":";;;AAKA,SAAgB,aAAa,IAAgB,GAAoB;CAC/D,IAAI,GAAG,aAAa,KAAA,GAClB,OAAO,gBAAgB,GAAG,UAAU,CAAC;CAEvC,OAAO,GAAG,EAAE,OAAO,4BAA4B,EAAE,KAAK,6BAA6B,GAAG,OAAO;AAC/F;;AAGA,SAAgB,gBAAgB,UAAkB,GAAY,YAAY,IAAY;CACpF,MAAM,MAAM;CAIZ,MAAM,WAAW,eAAe,EAAE,KAAK,GAAG;CAC1C,MAAM,OAAO,SAAS;CACtB,MAAM,OAAO,SAAS;CACtB,MAAM,OAAO,SAAS;CACtB,OAAO,GAAG,IAAI;UACN,KAAK,GAAG,SAAS,GAAG,EAAE,MAAM;UAC5B,KAAK;QACP,UAAU;YACN,KAAK,GAAG,KAAK;gBACT,KAAK,KAAK,KAAK,GAAG,KAAK,UAAU,KAAK;UAC5C,EAAE,OAAO,YAAY,KAAK,GAAG,KAAK;iBAC3B,EAAE,KAAK,UAAU,KAAK,GAAG,KAAK;;;QAGvC,EAAE,OAAO,GAAG,KAAK;;IAErB;AACJ"}
1
+ {"version":3,"file":"fallback.js","names":[],"sources":["../../../../src/core/codegen/schemas/fallback.ts"],"sourcesContent":["import type { FallbackIR } from \"../../types.js\";\nimport type { SlowGen } from \"../context.js\";\nimport { emitRfZod, emitRuntimeHelper } from \"../context.js\";\nimport { emit } from \"../emit.js\";\nimport { ZC_DELEGATE_ISSUES_DECL, ZC_RUN_DELEGATE_DECL } from \"../issue-decls.js\";\n\nexport function slowFallback(ir: FallbackIR, g: SlowGen): string {\n if (ir.refIndex !== undefined) {\n return slowZodDelegate(ir.refIndex, g);\n }\n return `${g.issues}.push({code:\"custom\",path:${g.path},message:\"Fallback schema: ${ir.reason}\"});\\n`;\n}\n\n/**\n * Delegate a cold slow-walk leaf to a pristine retained Zod schema.\n *\n * The schema is run through `_zod.run` and its RAW payload read, not through\n * `safeParse`: the payload is where zod's per-issue `continue` flags and the\n * `aborted` bit still exist, and a plain union prunes its options on exactly\n * those (see ZC_RUN_DELEGATE_DECL). The issues are then finalized by zod's own\n * `finalizeIssue` and re-homed under this node's path (ZC_DELEGATE_ISSUES_DECL),\n * so what lands in the validator's list is what `safeParse` would have built,\n * plus a `continue:false` marker on each aborting issue that the top-level\n * finalizer strips again. The per-call `{async:false}` ctx is the one zod's\n * `_safeParse` allocates, handed to both `run` and `finalizeIssue` as zod does.\n *\n * `payload.aborted` — set by a pipe whose `in` failed — is forwarded only when\n * this delegate IS a union option (`g.aborted` bound). Nested deeper it is\n * dropped, as zod's `handlePropertyResult` drops it: only the issues travel up.\n */\nexport function slowZodDelegate(refIndex: number, g: SlowGen, onFailure = \"\"): string {\n const zod = emitRfZod(g.ctx, refIndex);\n const run = emitRuntimeHelper(g.ctx, \"__zcRd\", ZC_RUN_DELEGATE_DECL);\n const finalize = emitRuntimeHelper(g.ctx, \"__zcRf\", ZC_DELEGATE_ISSUES_DECL);\n const cVar = `__rf_c${refIndex}`;\n const rVar = `__rf_r${refIndex}`;\n const abort = g.aborted === undefined ? \"\" : `if(${rVar}.aborted===true){${g.aborted}=true;}`;\n return `${emit`\n var ${cVar}={async:false};\n var ${rVar}=${run}(${zod},${g.input},${cVar});\n if(${rVar}.issues.length){\n ${onFailure}\n ${finalize}(${rVar}.issues,${cVar},${g.issues},${g.path});\n ${abort}\n }else{\n ${g.output}=${rVar}.value;\n }\n `}\\n`;\n}\n"],"mappings":";;;;AAMA,SAAgB,aAAa,IAAgB,GAAoB;CAC/D,IAAI,GAAG,aAAa,KAAA,GAClB,OAAO,gBAAgB,GAAG,UAAU,CAAC;CAEvC,OAAO,GAAG,EAAE,OAAO,4BAA4B,EAAE,KAAK,6BAA6B,GAAG,OAAO;AAC/F;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,gBAAgB,UAAkB,GAAY,YAAY,IAAY;CACpF,MAAM,MAAM,UAAU,EAAE,KAAK,QAAQ;CACrC,MAAM,MAAM,kBAAkB,EAAE,KAAK,UAAU,oBAAoB;CACnE,MAAM,WAAW,kBAAkB,EAAE,KAAK,UAAU,uBAAuB;CAC3E,MAAM,OAAO,SAAS;CACtB,MAAM,OAAO,SAAS;CACtB,MAAM,QAAQ,EAAE,YAAY,KAAA,IAAY,KAAK,MAAM,KAAK,mBAAmB,EAAE,QAAQ;CACrF,OAAO,GAAG,IAAI;UACN,KAAK;UACL,KAAK,GAAG,IAAI,GAAG,IAAI,GAAG,EAAE,MAAM,GAAG,KAAK;SACvC,KAAK;QACN,UAAU;QACV,SAAS,GAAG,KAAK,UAAU,KAAK,GAAG,EAAE,OAAO,GAAG,EAAE,KAAK;QACtD,MAAM;;QAEN,EAAE,OAAO,GAAG,KAAK;;IAErB;AACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"number.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/number.ts"],"mappings":";;;iBAQgB,WAAW,IAAI,UAAU,GAAG;iBA6I5B,WAAW,IAAI,UAAU,GAAG"}
1
+ {"version":3,"file":"number.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/number.ts"],"mappings":";;;iBAqBgB,WAAW,IAAI,UAAU,GAAG;iBAoJ5B,WAAW,IAAI,UAAU,GAAG"}
@@ -1,9 +1,21 @@
1
- import { checkPriority, emitEffectCallable, emitRuntimeHelper } from "../context.js";
1
+ import { checkPriority, emitRuntimeHelper } from "../context.js";
2
2
  import { emit } from "../emit.js";
3
3
  import { invalidType, tooBig, tooSmall } from "../emit-issue.js";
4
4
  import { ZC_FSR_DECL } from "../issue-decls.js";
5
- import { refineCheck, superRefineCheck, superRefineFastTest } from "./effect.js";
5
+ import { fastRefineTest, refineCheck, superRefineCheck, superRefineFastTest } from "./effect.js";
6
6
  //#region src/core/codegen/schemas/number.ts
7
+ /**
8
+ * The integer number formats, each with the range zod's `NUMBER_FORMAT_RANGES`
9
+ * gives it. `null` for safeint, whose own range IS the safe-integer range that
10
+ * every integer format reports first (see the number_format case below), so it
11
+ * has no range branch of its own. float32/float64 are absent on purpose: they
12
+ * are pure range checks and never report `invalid_type`.
13
+ */
14
+ const INT_FORMAT_RANGES = {
15
+ int32: [-2147483648, 2147483647],
16
+ safeint: null,
17
+ uint32: [0, 4294967295]
18
+ };
7
19
  function slowNumber(ir, g) {
8
20
  let code = "";
9
21
  if (ir.coerce) code += emit`try{${g.output}=Number(${g.input});}catch(_){}`;
@@ -17,7 +29,7 @@ function slowNumber(ir, g) {
17
29
  }`;
18
30
  if (ir.checks.length > 0) {
19
31
  code += `else{`;
20
- const opensIntGuard = (check) => check.kind === "number_format" && (check.format === "safeint" || check.format === "int32" || check.format === "uint32");
32
+ const opensIntGuard = (check) => check.kind === "number_format" && INT_FORMAT_RANGES[check.format] !== void 0;
21
33
  let seenIntFormat = false;
22
34
  let intGuardOpen = false;
23
35
  for (const check of ir.checks) {
@@ -48,46 +60,34 @@ function slowNumber(ir, g) {
48
60
  break;
49
61
  case "number_format": {
50
62
  const message = check.message ?? g.typeMsg;
51
- if (check.format === "safeint") {
63
+ const intRange = INT_FORMAT_RANGES[check.format];
64
+ if (intRange !== void 0) {
52
65
  const note = `note:"Integers must be within the safe integer range."`;
53
66
  const msgProp = message !== void 0 ? `,message:${JSON.stringify(message)}` : "";
54
67
  code += emit`
55
68
  if(!Number.isInteger(${g.input})){
56
69
  ${invalidType(g, "int", {
57
- extra: "format:\"safeint\"",
70
+ extra: `format:"${check.format}"`,
58
71
  extraBeforeCode: true,
59
72
  message
60
73
  })}
61
- }else if(${g.input}<-9007199254740991){
62
- ${g.issues}.push({code:"too_small",minimum:-9007199254740991,${note},origin:"int",inclusive:true,input:${g.input},path:${g.path}${msgProp}});
63
- }else if(${g.input}>9007199254740991){
64
- ${g.issues}.push({code:"too_big",maximum:9007199254740991,${note},origin:"int",inclusive:true,input:${g.input},path:${g.path}${msgProp}});
74
+ }else if(!Number.isSafeInteger(${g.input})){
75
+ if(${g.input}>0){
76
+ ${g.issues}.push({code:"too_big",maximum:9007199254740991,${note},origin:"int",inclusive:true,input:${g.input},path:${g.path}${msgProp}});
77
+ }else{
78
+ ${g.issues}.push({code:"too_small",minimum:-9007199254740991,${note},origin:"int",inclusive:true,input:${g.input},path:${g.path}${msgProp}});
79
+ }
65
80
  }`;
66
- } else if (check.format === "int32") code += emit`
67
- if(!Number.isInteger(${g.input})){
68
- ${invalidType(g, "int", {
69
- extra: "format:\"int32\"",
70
- extraBeforeCode: true,
71
- message
72
- })}
73
- }else if(${g.input}<-2147483648){
74
- ${tooSmall(g, -2147483648, "number", true, { message })}
75
- }else if(${g.input}>2147483647){
76
- ${tooBig(g, 2147483647, "number", true, { message })}
77
- }`;
78
- else if (check.format === "uint32") code += emit`
79
- if(!Number.isInteger(${g.input})){
80
- ${invalidType(g, "int", {
81
- extra: "format:\"uint32\"",
82
- extraBeforeCode: true,
83
- message
84
- })}
85
- }else if(${g.input}<0){
86
- ${tooSmall(g, 0, "number", true, { message })}
87
- }else if(${g.input}>4294967295){
88
- ${tooBig(g, 4294967295, "number", true, { message })}
89
- }`;
90
- else if (check.format === "float32") code += emit`
81
+ if (intRange !== null) {
82
+ const [minimum, maximum] = intRange;
83
+ code += emit`
84
+ else if(${g.input}<${minimum}){
85
+ ${tooSmall(g, minimum, "number", true, { message })}
86
+ }else if(${g.input}>${maximum}){
87
+ ${tooBig(g, maximum, "number", true, { message })}
88
+ }`;
89
+ }
90
+ } else if (check.format === "float32") code += emit`
91
91
  if(${g.input}<-3.4028234663852886e+38){
92
92
  ${tooSmall(g, "-3.4028234663852886e+38", "number", true, { message })}
93
93
  }else if(${g.input}>3.4028234663852886e+38){
@@ -165,7 +165,7 @@ function fastNumber(ir, g) {
165
165
  case "starts_with":
166
166
  case "ends_with": break;
167
167
  }
168
- for (const check of ir.checks) if (check.kind === "refine_effect") parts.push(`${emitEffectCallable(g.ctx, check)}(${x})`);
168
+ for (const check of ir.checks) if (check.kind === "refine_effect") parts.push(fastRefineTest(check, x, g));
169
169
  else if (check.kind === "super_refine_effect") parts.push(superRefineFastTest(check, x, g));
170
170
  return parts.join("&&");
171
171
  }