zod-compiler 1.23.3 → 1.23.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -13
- package/dist/core/codegen/build-path.d.ts.map +1 -1
- package/dist/core/codegen/build-path.js +3 -1
- package/dist/core/codegen/build-path.js.map +1 -1
- package/dist/core/codegen/context.d.ts.map +1 -1
- package/dist/core/codegen/context.js +4 -2
- package/dist/core/codegen/context.js.map +1 -1
- package/dist/core/codegen/dedupe.js +4 -1
- package/dist/core/codegen/dedupe.js.map +1 -1
- package/dist/core/codegen/fast-path.d.ts.map +1 -1
- package/dist/core/codegen/fast-path.js +4 -0
- package/dist/core/codegen/fast-path.js.map +1 -1
- package/dist/core/codegen/fast-size.d.ts.map +1 -1
- package/dist/core/codegen/fast-size.js +4 -1
- package/dist/core/codegen/fast-size.js.map +1 -1
- package/dist/core/codegen/index.js +18 -1
- package/dist/core/codegen/index.js.map +1 -1
- package/dist/core/codegen/issue-decls.d.ts +7 -1
- package/dist/core/codegen/issue-decls.d.ts.map +1 -1
- package/dist/core/codegen/issue-decls.js +8 -1
- package/dist/core/codegen/issue-decls.js.map +1 -1
- package/dist/core/codegen/schemas/custom.d.ts +10 -0
- package/dist/core/codegen/schemas/custom.d.ts.map +1 -0
- package/dist/core/codegen/schemas/custom.js +17 -0
- package/dist/core/codegen/schemas/custom.js.map +1 -0
- package/dist/core/codegen/schemas/fallback.d.ts +3 -1
- package/dist/core/codegen/schemas/fallback.d.ts.map +1 -1
- package/dist/core/codegen/schemas/fallback.js +23 -20
- package/dist/core/codegen/schemas/fallback.js.map +1 -1
- package/dist/core/codegen/schemas/zod-delegate.d.ts +12 -0
- package/dist/core/codegen/schemas/zod-delegate.d.ts.map +1 -0
- package/dist/core/codegen/schemas/zod-delegate.js +14 -0
- package/dist/core/codegen/schemas/zod-delegate.js.map +1 -0
- package/dist/core/codegen/slow-path.d.ts.map +1 -1
- package/dist/core/codegen/slow-path.js +5 -1
- package/dist/core/codegen/slow-path.js.map +1 -1
- package/dist/core/diagnostic.d.ts.map +1 -1
- package/dist/core/diagnostic.js +3 -0
- package/dist/core/diagnostic.js.map +1 -1
- package/dist/core/extract/extractors/custom.d.ts +12 -0
- package/dist/core/extract/extractors/custom.d.ts.map +1 -0
- package/dist/core/extract/extractors/custom.js +35 -0
- package/dist/core/extract/extractors/custom.js.map +1 -0
- package/dist/core/extract/extractors/intersection.d.ts.map +1 -1
- package/dist/core/extract/extractors/intersection.js +32 -0
- package/dist/core/extract/extractors/intersection.js.map +1 -1
- package/dist/core/extract/registry.d.ts +2 -0
- package/dist/core/extract/registry.d.ts.map +1 -1
- package/dist/core/extract/registry.js +2 -0
- package/dist/core/extract/registry.js.map +1 -1
- package/dist/core/extract/types.d.ts +7 -1
- package/dist/core/extract/types.d.ts.map +1 -1
- package/dist/core/iife.d.ts +3 -4
- package/dist/core/iife.d.ts.map +1 -1
- package/dist/core/iife.js +3 -4
- package/dist/core/iife.js.map +1 -1
- package/dist/core/types.d.ts +28 -2
- package/dist/core/types.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
**Compile Zod schemas into zero-overhead validation functions at build time.**
|
|
4
4
|
|
|
5
|
-
Keep your existing Zod schemas. Get **2-43x faster** validation
|
|
5
|
+
Keep your existing Zod schemas. Get **1.2-43x faster** validation, and up to **190x** on rejected
|
|
6
|
+
input. No code changes required.
|
|
6
7
|
|
|
7
8
|
- [What Gets Compiled](#what-gets-compiled)
|
|
8
9
|
- [Schema Hoisting](#schema-hoisting)
|
|
@@ -351,12 +352,13 @@ npx zod-compiler check src/schemas.ts --json --fail-under 80
|
|
|
351
352
|
|
|
352
353
|
## What Gets Compiled
|
|
353
354
|
|
|
354
|
-
### Fully Compiled (2-43x faster)
|
|
355
|
+
### Fully Compiled (1.2-43x faster)
|
|
355
356
|
|
|
356
357
|
Every Zod type except the fallbacks below — all primitives, `object` / `strictObject` / `looseObject`,
|
|
357
358
|
`array`, `tuple`, `record`, `set`, `map`, `union`, `discriminatedUnion`, `intersection`, `pipe`,
|
|
358
359
|
the `optional` / `nullable` / `readonly` / `default` / `catch` / `coerce` wrappers, `templateLiteral`,
|
|
359
|
-
recursive `lazy` (self, mutual and nested),
|
|
360
|
+
recursive `lazy` (self, mutual and nested), `custom` / `instanceof`, and
|
|
361
|
+
`transform` / `refine` / `superRefine`.
|
|
360
362
|
|
|
361
363
|
All standard checks are supported: `min`, `max`, `length`, `email`, `uuid`, `regex`, `int`, `positive`,
|
|
362
364
|
`multipleOf`, `includes`, `startsWith`, and the rest.
|
|
@@ -365,14 +367,13 @@ All standard checks are supported: `min`, `max`, `length`, `email`, `uuid`, `reg
|
|
|
365
367
|
|
|
366
368
|
A schema delegates to Zod when it reaches JavaScript the generated code cannot reproduce:
|
|
367
369
|
|
|
368
|
-
| Construct
|
|
369
|
-
|
|
|
370
|
-
| `.check(fn)`, `superRefine` + later checks
|
|
371
|
-
| `ctx`-taking or `async`
|
|
372
|
-
| `z.
|
|
373
|
-
|
|
|
374
|
-
|
|
|
375
|
-
| Dynamic error maps, unresolvable `z.lazy()` | Not knowable at build time |
|
|
370
|
+
| Construct | Why |
|
|
371
|
+
| ---------------------------------------------------- | -------------------------------------------------------------------------- |
|
|
372
|
+
| `.check(fn)`, `superRefine` + later checks | The callback holds Zod's payload unmediated, or `fatal` aborts Zod's chain |
|
|
373
|
+
| `ctx`-taking or `async` callbacks | Needs Zod's parse context / the async pipeline |
|
|
374
|
+
| `z.url()`, `z.jwt()` | Algorithmic formats (`new URL()`, signature parsing) |
|
|
375
|
+
| Overlapping or policy-sensitive object intersections | Zod's independent parse-and-merge semantics cannot be safely collapsed |
|
|
376
|
+
| Dynamic error maps, unresolvable `z.lazy()` | Not knowable at build time |
|
|
376
377
|
|
|
377
378
|
Everything else compiles, including `transform`/`refine`/`superRefine` whether or not the callback
|
|
378
379
|
captures — a zero-capture one is inlined, a capturing one called by reference. Delegation is
|
|
@@ -438,8 +439,12 @@ Schema-level `error` and `z.config()` maps are unaffected; for a per-call map us
|
|
|
438
439
|
| coerced query object (invalid) | 1.1M | 162K | **10.1M** | — | — | **62x** |
|
|
439
440
|
| stringbool config object (valid) | — | 1.9M | **6.0M** | — | — | 3.1x |
|
|
440
441
|
| stringbool config object (invalid) | — | 129K | **13.1M** | — | — | **101x** |
|
|
442
|
+
| custom/instanceof request (valid) | 894K | 3.0M | **8.6M** | — | — | 2.9x |
|
|
443
|
+
| custom/instanceof request (invalid) | 755K | 158K | **8.5M** | — | — | **54x** |
|
|
444
|
+
| disjoint object intersection (valid) | 1.4M | 1.7M | **9.7M** | — | — | 5.7x |
|
|
445
|
+
| disjoint object intersection (invalid) | 548K | 80K | **15.3M** | — | — | **190x** |
|
|
441
446
|
|
|
442
|
-
_ops/s, higher is better. `
|
|
447
|
+
_ops/s, higher is better. `vp test bench` on an Apple M4 Max (zod 4.3.6, zod v3 3.23.8, typia 12, ajv 8),
|
|
443
448
|
best of three runs. The harness costs ~55 ns per iteration, so the fastest rows sit at that floor and gaps
|
|
444
449
|
between the AOT columns there are noise, not real._
|
|
445
450
|
|
|
@@ -462,7 +467,12 @@ Regexes are pre-compiled with bounded repeats unrolled, checks run cheapest-firs
|
|
|
462
467
|
dispatch through a jump table (plain tagged unions are auto-discriminated into it), and oversized check
|
|
463
468
|
functions are split to stay within V8's optimizer budget. Stripping objects, native coercions,
|
|
464
469
|
`stringbool`, defaults, string rewrites and synchronous transforms validate and build their output in
|
|
465
|
-
one pass.
|
|
470
|
+
one pass. An intersection of two objects with disjoint keys compiles to that same single pass over the
|
|
471
|
+
merged shape, and `z.custom()` / `z.instanceof()` compile to a direct predicate call.
|
|
472
|
+
|
|
473
|
+
Where success is cheaper to compile than failure, only the verdict and output are compiled: intersections
|
|
474
|
+
and `custom` keep the original Zod schema to construct issues, so a rejection still reports exactly what
|
|
475
|
+
Zod would — including an intersection's one-issue-per-side shape — without slowing the hot path.
|
|
466
476
|
|
|
467
477
|
## Development
|
|
468
478
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-path.d.ts","names":[],"sources":["../../../src/core/codegen/build-path.ts"],"mappings":";;;;iBAmJgB,eAAe,IAAI;;;;;;
|
|
1
|
+
{"version":3,"file":"build-path.d.ts","names":[],"sources":["../../../src/core/codegen/build-path.ts"],"mappings":";;;;iBAmJgB,eAAe,IAAI;;;;;;iBAmGnB,cAAc,IAAI,UAAU,KAAK"}
|
|
@@ -99,7 +99,8 @@ function children(ir) {
|
|
|
99
99
|
case "default":
|
|
100
100
|
case "catch":
|
|
101
101
|
case "effect":
|
|
102
|
-
case "recursionTarget":
|
|
102
|
+
case "recursionTarget":
|
|
103
|
+
case "zodDelegate": return [ir.inner];
|
|
103
104
|
case "pipe": return [ir.in, ir.out];
|
|
104
105
|
default: return [];
|
|
105
106
|
}
|
|
@@ -206,6 +207,7 @@ function buildInline(ir, input, g) {
|
|
|
206
207
|
case "date": return buildCoercedPrimitive(ir, input, g);
|
|
207
208
|
case "effect": return buildEffect(ir, input, g);
|
|
208
209
|
case "readonly": return build(ir.inner, input, g);
|
|
210
|
+
case "zodDelegate": return build(ir.inner, input, g);
|
|
209
211
|
case "union":
|
|
210
212
|
case "discriminatedUnion": return buildUnion(ir, input, g);
|
|
211
213
|
default: return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-path.js","names":[],"sources":["../../../src/core/codegen/build-path.ts"],"sourcesContent":["/**\n * Build Path: one uninstrumented pass that VALIDATES and BUILDS rewritten\n * output together, abandoning the whole parse at the first failing check.\n *\n * `z.object()` strips unknown keys, so a successful parse cannot return the\n * input by reference — it must produce a fresh object. That rules out the Fast\n * Path (whose contract is `data === input`), and before this the only remaining\n * option was the eager slow walk: a fully instrumented traversal that collects\n * issues on every parse, valid or not.\n *\n * Two passes are wasteful in either direction. Validating first and building\n * afterwards reads every property twice (measured 29.7 ns vs 21.6 for the slow\n * walk on a 6-field object). Building with issue collection pays the\n * instrumentation even when nothing fails. Doing both in ONE pass, with a\n * sentinel instead of an issues array, beats both — and a failure costs only\n * the checks up to the first bad one, because the issue-producing walk is\n * deferred into `.error` exactly as `__zcFinD` does for mutation-free schemas:\n *\n * object clean object invalid array(8) invalid\n * slow walk 21.6 ns 30.4 ns 197.5 ns\n * build path 18.1 ns 7.7 ns 9.8 ns\n *\n * A subtree that rebuilds nothing is validated with its existing Fast Path\n * expression and passed through by reference, so only nodes that genuinely\n * produce a new value need code here; anything else returns null and keeps the\n * eager walk.\n *\n * Coverage is what decides whether this pass is reached at all, because it is\n * all-or-nothing per schema: ONE unmodelled node anywhere in the tree costs the\n * whole schema its single-pass parse. Modelled, beyond the stripping containers\n * this started with: array size checks and `.refine()`, object-level `.refine()`,\n * `.default()` substitution, ordered string rewrites (`.trim()`,\n * `.toLowerCase()`), sync `.transform()`, `z.stringbool()`, and the five native\n * coercions (`string`, `number`, `boolean`, `bigint`, `date`). Still declined, via\n * {@link mutatesBeyondStrip} — `.catch()` (its callback wants the inner schema's\n * issue list, which this pass never builds), `z.url()`, and `superRefine`.\n */\n\nimport type { ObjectIR, RefineEffectCheckIR, SchemaIR, StringBoolIR } from \"../types.js\";\nimport type { CodeGenContext, FastScope } from \"./context.js\";\nimport {\n declareFastTemps,\n emitEffectCallable,\n emitEffectFn,\n emitRuntimeHelper,\n emitTemp,\n escapeString,\n keyMembershipTest,\n outputAlwaysDefined,\n rejectsUndefined,\n} from \"./context.js\";\nimport { createFastGen, generateFast } from \"./fast-path.js\";\nimport { EXTRACT_CAP, estimateFastCost, MIN_EXTRACT, predictedInlineSize } from \"./fast-size.js\";\nimport { ZC_HOP_DECL } from \"./issue-decls.js\";\nimport { defaultValueExpr, needsPostInnerDefault } from \"./schemas/default.js\";\nimport { innerAppliesDefaultOnUndefined } from \"./schemas/optional.js\";\nimport { fastStringCheck } from \"./schemas/string.js\";\nimport { emitStringBoolMap, stringBoolUsesInline } from \"./schemas/string-bool.js\";\n\n/** Statements that leave the built value in `value`, or `return <FAIL>` on failure. */\ninterface Built {\n code: string;\n value: string;\n}\n\ninterface BuildGen {\n ctx: CodeGenContext;\n /** Identifier of the per-validator FAIL sentinel. */\n fail: string;\n /** `var` temps and running emitted size of the function being assembled. */\n scope: FastScope;\n /**\n * May THIS node be hosted in its own function? False for the node a hosted\n * build was created for — it already IS that function, so re-hosting it would\n * recurse forever. Children are always extractable, letting an oversized\n * helper split further.\n */\n extractable: boolean;\n /** Nodes of the root schema that rebuild (see rebuildSet). */\n rebuilds: ReadonlySet<SchemaIR>;\n}\n\n/**\n * Which nodes of `root` produce a value that is not their input — a stripping\n * object, coercion, codec, default, overwrite or transform, including\n * containers that contain one. Everything else can be validated in place and\n * passed through, which is what keeps this generator small.\n *\n * Computed as a fixpoint rather than a plain walk because of recursion: a\n * `recursiveRef` is a back-edge with no children, so a local walk reads false\n * for it and would pass the whole recursive subtree through by reference —\n * leaving every nested value unstripped while the outermost one was rebuilt.\n * Resolving the ref against its target closes the cycle, and iterating to a\n * fixpoint settles the mutual dependency between the two.\n */\nfunction rebuildSet(root: SchemaIR): ReadonlySet<SchemaIR> {\n const targets = new Map<number, SchemaIR>([[0, root]]);\n const nodes: SchemaIR[] = [];\n const seen = new Set<SchemaIR>();\n const collect = (node: SchemaIR): void => {\n if (seen.has(node)) return;\n seen.add(node);\n nodes.push(node);\n if (node.type === \"recursionTarget\") targets.set(node.refId, node.inner);\n for (const child of children(node)) collect(child);\n };\n collect(root);\n\n const rebuilds = new Set<SchemaIR>();\n for (let changed = true; changed;) {\n changed = false;\n for (const node of nodes) {\n if (rebuilds.has(node)) continue;\n const target = node.type === \"recursiveRef\" ? targets.get(node.refId ?? 0) : undefined;\n const rebuild =\n (node.type === \"object\" && node.stripUnknownKeys === true) ||\n // `.default()` substitutes its own value for `undefined`, so its output\n // is not its input even when the inner schema passes through — it must\n // never be handed to `passthrough`, whose fast check would reject the\n // absent value outright.\n node.type === \"default\" ||\n // `z.stringbool()` replaces its accepted string with a boolean.\n node.type === \"stringBool\" ||\n // An overwrite effect (`.trim()`, `.toLowerCase()`) rewrites the string,\n // so the node's output is a new value: it has to be BUILT rather than\n // validated in place (see buildString).\n (node.type === \"string\" &&\n (node.coerce === true || node.checks.some((c) => c.kind === \"overwrite_effect\"))) ||\n ((node.type === \"number\" ||\n node.type === \"boolean\" ||\n node.type === \"bigint\" ||\n node.type === \"date\") &&\n node.coerce === true) ||\n // `.transform(fn)` replaces the value with the callback's result.\n node.type === \"effect\" ||\n (target !== undefined && rebuilds.has(target)) ||\n children(node).some((child) => rebuilds.has(child));\n if (rebuild) {\n rebuilds.add(node);\n changed = true;\n }\n }\n }\n return rebuilds;\n}\n\n/** Does `ir`, taken as a whole schema, produce a value that is not its input? */\nexport function rebuildsOutput(ir: SchemaIR): boolean {\n return rebuildSet(ir).has(ir);\n}\n\n/**\n * True when the subtree mutates for any reason the build pass cannot reproduce —\n * `.catch()`, `z.url()`, `superRefine`. Those rewrite values in ways this pass\n * (which validates, coerces, decodes string booleans, substitutes declared\n * defaults, applies ordered string rewrites and copies) does not model, so the\n * schema keeps the eager walk.\n */\nfunction mutatesBeyondStrip(ir: SchemaIR): boolean {\n return mutatesHere(ir) || children(ir).some(mutatesBeyondStrip);\n}\n\n/**\n * Does this node rewrite values on its own account (ignoring its children, and\n * ignoring the reshaping a strip object does)? Mirrors the node-local half of\n * `hasMutation`; the recursion above supplies the other half.\n */\nfunction mutatesHere(ir: SchemaIR): boolean {\n switch (ir.type) {\n case \"string\":\n // Coercion and overwrite effects are absent: `buildString` applies them\n // in order. A `z.url()` check still is not — it trims, normalizes and\n // needs its own normalization/error semantics.\n return (\n superRefines(ir.checks) ||\n ir.checks.some((c) => c.kind === \"string_format\" && c.format === \"url\")\n );\n case \"number\":\n return superRefines(ir.checks);\n case \"boolean\":\n case \"bigint\":\n case \"date\":\n return false;\n // `default` and `effect` are absent: substituting a constant for `undefined`\n // and applying a sync transform are both modelled (see buildDefault /\n // buildEffect), and their inners are reached through `children`.\n //\n // `catch` is NOT: its catchValue callback receives a ctx carrying the inner\n // schema's collected issues, and this pass produces a sentinel instead of an\n // issue list — there is nothing to hand it.\n case \"catch\":\n case \"fallback\":\n return true;\n case \"object\":\n case \"array\":\n return superRefines(ir.checks);\n default:\n return false;\n }\n}\n\nfunction superRefines(checks: readonly { kind: string }[] | undefined): boolean {\n return checks !== undefined && checks.some((c) => c.kind === \"super_refine_effect\");\n}\n\nfunction children(ir: SchemaIR): readonly SchemaIR[] {\n switch (ir.type) {\n case \"object\":\n return ir.catchall\n ? [...Object.values(ir.properties), ir.catchall]\n : Object.values(ir.properties);\n case \"array\":\n return [ir.element];\n case \"tuple\":\n return ir.rest === null ? ir.items : [...ir.items, ir.rest];\n case \"record\":\n case \"map\":\n return [ir.keyType, ir.valueType];\n case \"set\":\n return [ir.valueType];\n case \"union\":\n case \"discriminatedUnion\":\n return ir.options;\n case \"intersection\":\n return [ir.left, ir.right];\n case \"optional\":\n case \"nullable\":\n case \"readonly\":\n case \"default\":\n case \"catch\":\n case \"effect\":\n case \"recursionTarget\":\n return [ir.inner];\n case \"pipe\":\n return [ir.in, ir.out];\n default:\n return [];\n }\n}\n\n/**\n * Host the whole schema as `function NAME(input){…}` returning the built value\n * or the FAIL sentinel. Returns the function name, or null when the schema is\n * not expressible as a single build pass.\n */\nexport function generateBuild(ir: SchemaIR, ctx: CodeGenContext): string | null {\n const rebuilds = rebuildSet(ir);\n if (!rebuilds.has(ir) || mutatesBeyondStrip(ir)) return null;\n const fail = emitFailSentinel(ctx);\n const scope: FastScope = { temps: [], used: 0 };\n const built = build(ir, \"input\", { ctx, extractable: false, fail, rebuilds, scope });\n if (built === null) return null;\n const name = emitTemp(ctx, \"vb\");\n ctx.preamble.push(\n `function ${name}(input){${declareFastTemps(scope)}${built.code}return ${built.value};}`,\n );\n return name;\n}\n\n/** One `{}` per validator, compared by identity — no parse output can equal it. */\nfunction emitFailSentinel(ctx: CodeGenContext): string {\n if (ctx.buildFailName === undefined) {\n ctx.buildFailName = `__bf_${ctx.counter++}`;\n ctx.preamble.push(`var ${ctx.buildFailName}={};`);\n }\n return ctx.buildFailName;\n}\n\n/**\n * Statements producing the built value of `ir` read from `input`, or null.\n *\n * Size-gated exactly like the fast path: once inlining `ir` would push the\n * function being assembled past EXTRACT_CAP, the sub-build is hosted as its own\n * `__vb_N(p)` returning value-or-FAIL and replaced by a call. Without this a\n * deeply nested schema emits one enormous build function — measured at 113 KB\n * and 354 KB on the deep fixtures — far past the bytecode size where V8 stops\n * running TurboFan on it, which would forfeit the speed this path exists for.\n */\nfunction build(ir: SchemaIR, input: string, g: BuildGen): Built | null {\n // Resolved before the passthrough shortcut below. A back-edge carries no\n // children, so `rebuildsOutput` reads false for it — and passing it through by\n // reference would leave every nested recursive value unstripped while the\n // outermost one was rebuilt.\n if (ir.type === \"recursiveRef\") return buildRecursiveCall(ir.refId ?? 0, input, g);\n if (ir.type === \"recursionTarget\") return buildRecursionTarget(ir, input, g);\n if (!g.rebuilds.has(ir)) return passthrough(ir, input, g);\n\n const cache = (g.ctx.fastSizeCache ??= new WeakMap<SchemaIR, number>());\n if (\n g.extractable &&\n g.scope.used + predictedInlineSize(ir, input.length, cache) > EXTRACT_CAP &&\n (g.scope.used > EXTRACT_CAP || estimateFastCost(ir, cache) >= MIN_EXTRACT)\n ) {\n const hosted = hostBuild(ir, g);\n if (hosted !== null) {\n const slot = local(g, \"bh\");\n const code = `${slot}=${hosted}(${input});if(${slot}===${g.fail})return ${g.fail};`;\n g.scope.used += code.length;\n return { code, value: slot };\n }\n }\n\n // This node's extraction decision is made; its descendants get to make their\n // own, so an oversized hosted helper keeps splitting.\n const before = g.scope.used;\n const out = buildInline(ir, input, { ...g, extractable: true });\n if (out !== null) g.scope.used = before + out.code.length;\n return out;\n}\n\n/** Host `ir`'s build in its own function over a fresh parameter; returns its name. */\nfunction hostBuild(ir: SchemaIR, g: BuildGen): string | null {\n const param = emitTemp(g.ctx, \"bp\");\n const scope: FastScope = { temps: [], used: 0 };\n const inner = build(ir, param, { ...g, extractable: false, scope });\n if (inner === null) return null;\n const name = emitTemp(g.ctx, \"vb\");\n g.ctx.preamble.push(\n `function ${name}(${param}){${declareFastTemps(scope)}${inner.code}return ${inner.value};}`,\n );\n return name;\n}\n\nfunction buildInline(ir: SchemaIR, input: string, g: BuildGen): Built | null {\n switch (ir.type) {\n case \"object\":\n return buildObject(ir, input, g);\n case \"array\":\n return buildArray(ir, input, g);\n case \"tuple\":\n return buildTuple(ir, input, g);\n case \"record\":\n return buildRecord(ir, input, g);\n case \"optional\":\n // A default further down the chain consumes undefined into a value, so\n // the `undefined → undefined` shortcut must not fire — same rule (and\n // same helper) the slow and fast paths already apply.\n return innerAppliesDefaultOnUndefined(ir.inner)\n ? build(ir.inner, input, g)\n : buildSentinel(ir.inner, input, g, \"===undefined\", \"undefined\");\n case \"nullable\":\n // `null` short-circuits unconditionally in zod, whatever the inner is;\n // undefined flows through, so an inner default still fires.\n return buildSentinel(ir.inner, input, g, \"===null\", \"null\");\n case \"default\":\n return buildDefault(ir, input, g);\n case \"string\":\n return buildString(ir, input, g);\n case \"stringBool\":\n return buildStringBool(ir, input, g);\n case \"number\":\n case \"boolean\":\n case \"bigint\":\n case \"date\":\n return buildCoercedPrimitive(ir, input, g);\n case \"effect\":\n return buildEffect(ir, input, g);\n case \"readonly\":\n return build(ir.inner, input, g);\n case \"union\":\n case \"discriminatedUnion\":\n return buildUnion(ir, input, g);\n default:\n // A rebuilding intersection, map or set: expressible in principle, but\n // each needs its own output-shaping rules, so they keep the eager walk\n // until there is a measured reason to add them.\n return null;\n }\n}\n\n/**\n * Host the target's build once under a name registered BEFORE its body is\n * generated, so the back-edges inside that body resolve to it.\n */\nfunction buildRecursionTarget(\n ir: SchemaIR & { type: \"recursionTarget\" },\n input: string,\n g: BuildGen,\n): Built | null {\n const table = (g.ctx.buildRecNames ??= new Map<number, string>());\n if (!table.has(ir.refId)) {\n const name = emitTemp(g.ctx, \"vbr\");\n table.set(ir.refId, name);\n const param = emitTemp(g.ctx, \"bp\");\n const scope: FastScope = { temps: [], used: 0 };\n const inner = build(ir.inner, param, { ...g, extractable: false, scope });\n if (inner === null) {\n table.delete(ir.refId);\n return null;\n }\n g.ctx.preamble.push(\n `function ${name}(${param}){${declareFastTemps(scope)}${inner.code}return ${inner.value};}`,\n );\n }\n return buildRecursiveCall(ir.refId, input, g);\n}\n\n/** Call the hosted build for a recursion target, propagating its FAIL. */\nfunction buildRecursiveCall(refId: number, input: string, g: BuildGen): Built | null {\n const name = g.ctx.buildRecNames?.get(refId);\n if (name === undefined) return null;\n const slot = local(g, \"bh\");\n return {\n code: `${slot}=${name}(${input});if(${slot}===${g.fail})return ${g.fail};`,\n value: slot,\n };\n}\n\n/**\n * Try each option in declaration order and take the first that builds — which\n * is what zod's union does with the first option that parses.\n *\n * Every option is HOSTED rather than inlined, and that is load-bearing: a\n * failing build signals with `return FAIL`, which inside the enclosing function\n * would abandon the whole parse instead of moving on to the next option. Behind\n * a call, the same signal is just a value to test.\n *\n * A discriminated union gets the same treatment rather than a switch: the\n * options still have to be probed by call, and its dispatch advantage is\n * already spent by the enclosing container's own work.\n */\nfunction buildUnion(\n ir: SchemaIR & { type: \"discriminatedUnion\" | \"union\" },\n input: string,\n g: BuildGen,\n): Built | null {\n const hosted: string[] = [];\n for (const option of ir.options) {\n const fn = g.rebuilds.has(option) ? hostBuild(option, g) : hostPassthrough(option, g);\n if (fn === null) return null;\n hosted.push(fn);\n }\n if (hosted.length === 0) return null;\n\n const out = local(g, \"bu\");\n let code = `${out}=${hosted[0] as string}(${input});`;\n for (const fn of hosted.slice(1)) {\n code += `if(${out}===${g.fail}){${out}=${fn}(${input});}`;\n }\n code += `if(${out}===${g.fail})return ${g.fail};`;\n return { code, value: out };\n}\n\n/**\n * Host a non-rebuilding option as `value-or-FAIL`, so a union can probe it with\n * the same protocol as a rebuilding one.\n */\nfunction hostPassthrough(ir: SchemaIR, g: BuildGen): string | null {\n const param = emitTemp(g.ctx, \"bp\");\n const scope: FastScope = { temps: [], used: 0 };\n const expr = generateFast(ir, createFastGen(param, g.ctx, true, scope));\n if (expr === null) return null;\n const name = emitTemp(g.ctx, \"vp\");\n g.ctx.preamble.push(\n `function ${name}(${param}){${declareFastTemps(scope)}return ${expr === \"true\" ? param : `(${expr})?${param}:${g.fail}`};}`,\n );\n return name;\n}\n\n/** Validate in place with the Fast Path and hand the input straight back. */\nfunction passthrough(ir: SchemaIR, input: string, g: BuildGen): Built | null {\n const scoped = createFastGen(input, g.ctx, true, g.scope);\n const expr = generateFast(ir, scoped);\n if (expr === null) return null;\n return { code: expr === \"true\" ? \"\" : `if(!(${expr}))return ${g.fail};`, value: input };\n}\n\n/**\n * Rebuild from the declared keys. Sound for a stripping object (that IS the\n * output) and for a strict one (unknown keys are rejected, so the declared keys\n * are the whole key set). A loose object or one with a `.catchall()` keeps keys\n * this pass does not enumerate, so those bail.\n */\nfunction buildObject(ir: ObjectIR, input: string, g: BuildGen): Built | null {\n if (ir.catchall !== undefined) return null;\n if (ir.stripUnknownKeys !== true && ir.strict !== true) return null;\n if (ir.suppressAbsentKeys !== undefined && ir.suppressAbsentKeys.length > 0) return null;\n // Object-level `.refine()` runs on the assembled output (below). superRefine\n // rewrites the payload, which this pass does not model — mutatesBeyondStrip\n // already rejects it, so this is a belt-and-braces narrowing of the type.\n const refines = ir.checks ?? [];\n if (refines.some((check) => check.kind !== \"refine_effect\")) return null;\n\n let code = `if(typeof ${input}!==\"object\"||${input}===null||Array.isArray(${input}))return ${g.fail};`;\n\n if (ir.strict === true) {\n const keyVar = local(g, \"bk\");\n code += `for(${keyVar} in ${input}){if(!(${keyMembershipTest(g.ctx, Object.keys(ir.properties), keyVar)}))return ${g.fail};}`;\n }\n\n const slots: { always: boolean; keyStr: string; value: string }[] = [];\n for (const [key, propIR] of Object.entries(ir.properties)) {\n const keyStr = escapeString(key);\n const slot = local(g, \"bv\");\n code += `${slot}=${input}[${keyStr}];`;\n const propBuilt = build(propIR, slot, g);\n if (propBuilt === null) return null;\n code += propBuilt.code;\n slots.push({ always: outputAlwaysDefined(propIR), keyStr, value: propBuilt.value });\n }\n\n // Same assembly the eager strip walk uses: the longest LEADING run of\n // always-present keys goes into one object literal (V8 stamps it from a\n // cached boilerplate map in a single allocation), and everything after the\n // first conditional key is appended so insertion order still matches zod.\n // The per-key test is zod's own — keep the key when the parsed value is\n // defined, or when it was present on the input at all.\n const out = local(g, \"bo\");\n const literal: string[] = [];\n let appends = \"\";\n let leading = true;\n for (const slot of slots) {\n if (leading && slot.always) {\n literal.push(`${slot.keyStr}:${slot.value}`);\n continue;\n }\n leading = false;\n appends += slot.always\n ? `${out}[${slot.keyStr}]=${slot.value};`\n : `if(${slot.value}!==undefined||(${slot.keyStr} in ${input})){${out}[${slot.keyStr}]=${slot.value};}`;\n }\n code += `${out}={${literal.join(\",\")}};${appends}`;\n // Zod parses the properties into the payload first and skips the check chain\n // when that produced issues, so a bad property suppresses the refine — which\n // this pass gets for free, having already returned FAIL at that property.\n for (const check of refines) {\n code += `if(!${emitEffectCallable(g.ctx, check as RefineEffectCheckIR)}(${out}))return ${g.fail};`;\n }\n return { code, value: out };\n}\n\nfunction buildArray(ir: SchemaIR & { type: \"array\" }, input: string, g: BuildGen): Built | null {\n // Length checks are pure predicates over `input.length`, so they hoist ahead\n // of the element loop: a size mismatch bails before a single element is\n // validated. Zod reports the per-element issue first when both fail, but the\n // build pass produces no issues — only the sentinel — and the deferred walk\n // that does produce them keeps zod's order.\n let sizes = \"\";\n const refines: RefineEffectCheckIR[] = [];\n for (const check of ir.checks) {\n switch (check.kind) {\n case \"min_length\":\n sizes += `if(${input}.length<${check.minimum})return ${g.fail};`;\n break;\n case \"max_length\":\n sizes += `if(${input}.length>${check.maximum})return ${g.fail};`;\n break;\n case \"length_equals\":\n sizes += `if(${input}.length!==${check.length})return ${g.fail};`;\n break;\n case \"refine_effect\":\n refines.push(check);\n break;\n default:\n // super_refine (rewrites the value) or a check kind not modelled here.\n return null;\n }\n }\n\n const out = local(g, \"ba\");\n const index = local(g, \"bi\");\n const elem = local(g, \"be\");\n const inner = build(ir.element, elem, g);\n if (inner === null) return null;\n let code =\n `if(!Array.isArray(${input}))return ${g.fail};` +\n sizes +\n `${out}=new Array(${input}.length);` +\n `for(${index}=0;${index}<${input}.length;${index}++){` +\n `${elem}=${input}[${index}];${inner.code}${out}[${index}]=${inner.value};}`;\n // `.refine()` sees the parsed payload, which for a rebuilding element is the\n // freshly assembled array — the same value zod hands its checks.\n for (const check of refines) {\n code += `if(!${emitEffectCallable(g.ctx, check)}(${out}))return ${g.fail};`;\n }\n return { code, value: out };\n}\n\nfunction buildTuple(ir: SchemaIR & { type: \"tuple\" }, input: string, g: BuildGen): Built | null {\n // Trailing-optional and rest handling shape the output length; keep those on\n // the eager walk rather than restating the rules here.\n if (ir.rest !== null) return null;\n if (ir.items.some((item) => !rejectsUndefined(item))) return null;\n\n let code = `if(!Array.isArray(${input})||${input}.length!==${ir.items.length})return ${g.fail};`;\n const values: string[] = [];\n for (const [index, itemIR] of ir.items.entries()) {\n const slot = local(g, \"bt\");\n code += `${slot}=${input}[${index}];`;\n const inner = build(itemIR as SchemaIR, slot, g);\n if (inner === null) return null;\n code += inner.code;\n values.push(inner.value);\n }\n const out = local(g, \"bl\");\n code += `${out}=[${values.join(\",\")}];`;\n return { code, value: out };\n}\n\nfunction buildRecord(ir: SchemaIR & { type: \"record\" }, input: string, g: BuildGen): Built | null {\n const plainStringKey =\n ir.keyType.type === \"string\" && ir.keyType.checks.length === 0 && ir.keyType.coerce !== true;\n if (!plainStringKey) return null;\n\n const out = local(g, \"br\");\n const keyVar = local(g, \"brk\");\n const valVar = local(g, \"brv\");\n const inner = build(ir.valueType, valVar, g);\n if (inner === null) return null;\n const hop = emitRuntimeHelper(g.ctx, \"__zcHop\", ZC_HOP_DECL);\n const code =\n `if(typeof ${input}!==\"object\"||${input}===null||Array.isArray(${input}))return ${g.fail};` +\n `${out}={};` +\n `for(${keyVar} in ${input}){if(${hop}.call(${input},${keyVar})){` +\n `${valVar}=${input}[${keyVar}];${inner.code}${out}[${keyVar}]=${inner.value};}}`;\n return { code, value: out };\n}\n\n/**\n * `.transform(fn)`: validate the inner schema, then hand its parsed value to the\n * callback. Zod's transform is a pipe whose `in` failing aborts the whole thing,\n * which is exactly what returning FAIL from the inner build does — so the\n * callback runs only on a clean parse, as `slowEffect` guarantees with its issue\n * count.\n *\n * The IR reaches here only for a synchronous single-argument callback: a\n * `ctx`-taking or async transform is extracted as a `fallback` instead\n * (see extractPipe), so there is no parse context to reproduce.\n */\nfunction buildEffect(ir: SchemaIR & { type: \"effect\" }, input: string, g: BuildGen): Built | null {\n const inner = build(ir.inner, input, g);\n if (inner === null) return null;\n const out = local(g, \"bx\");\n return {\n code: `${inner.code}${out}=${emitEffectCallable(g.ctx, ir)}(${inner.value});`,\n value: out,\n };\n}\n\n/**\n * A coercing and/or overwrite string (`z.coerce.string()`, `.trim()`,\n * `.toLowerCase()`, ...): coerce first, then emit checks one statement at a time\n * in DECLARATION order, interleaved with rewrites, because a rewrite is visible\n * to every check after it — `z.string().trim().min(1)` rejects `\" \"` where\n * `z.string().min(1).trim()` accepts it. That ordering is exactly why the fast\n * path, which sorts checks cheapest-first and returns the input unchanged, has\n * to decline these.\n *\n * Only reached for a rewriting string; a non-coercing, check-only one never\n * enters the rebuild set and is validated in place by `passthrough`.\n */\nfunction buildString(ir: SchemaIR & { type: \"string\" }, input: string, g: BuildGen): Built | null {\n const value = local(g, \"bs\");\n let code =\n ir.coerce === true\n ? `try{${value}=String(${input});}catch(_){return ${g.fail};}`\n : `if(typeof ${input}!==\"string\")return ${g.fail};${value}=${input};`;\n for (const check of ir.checks) {\n switch (check.kind) {\n case \"overwrite_effect\":\n code += `${value}=${emitEffectFn(g.ctx, check.source)}(${value});`;\n break;\n case \"refine_effect\":\n code += `if(!${emitEffectCallable(g.ctx, check)}(${value}))return ${g.fail};`;\n break;\n case \"super_refine_effect\":\n // Rewrites through zod's payload; mutatesBeyondStrip already rejects it.\n return null;\n default: {\n const expr = fastStringCheck(check, value, g.ctx);\n if (expr === null) return null; // z.url(), unknown format\n code += `if(!(${expr}))return ${g.fail};`;\n }\n }\n }\n return { code, value };\n}\n\n/**\n * `z.stringbool()`: normalize once, select the declared truthy/falsy side, and\n * return the boolean directly. The ordinary Fast Path cannot host this codec\n * because its contract returns the original input by reference; the build path\n * is designed for exactly this kind of small output rewrite.\n */\nfunction buildStringBool(ir: StringBoolIR, input: string, g: BuildGen): Built {\n let code = `if(typeof ${input}!==\"string\")return ${g.fail};`;\n let normalized = input;\n if (!ir.caseSensitive) {\n normalized = local(g, \"bn\");\n code += `${normalized}=${input}.toLowerCase();`;\n }\n\n const out = local(g, \"bb\");\n if (stringBoolUsesInline(ir)) {\n const membership = (values: readonly string[]): string =>\n values.map((value) => `${normalized}===${escapeString(value)}`).join(\"||\");\n code +=\n `if(${membership(ir.truthy)}){${out}=true;}` +\n `else if(${membership(ir.falsy)}){${out}=false;}` +\n `else{return ${g.fail};}`;\n } else {\n const lookup = emitStringBoolMap(ir, g.ctx);\n code += `${out}=${lookup}.get(${normalized});if(${out}===undefined)return ${g.fail};`;\n }\n return { code, value: out };\n}\n\n/** Primitive nodes whose `coerce` flag rewrites their output before checks run. */\ntype CoercedPrimitiveIR = Extract<SchemaIR, { type: \"number\" | \"boolean\" | \"bigint\" | \"date\" }>;\n\n/**\n * Coerce once into a local, then reuse the ordinary Fast Path as the acceptance\n * predicate over the converted value. The build path only needs a verdict on\n * its hot pass; if it fails, the existing deferred slow walk reruns the original\n * coercing schema and produces Zod-identical issues.\n *\n * Number/BigInt/Date conversion can invoke user hooks and throw. Zod catches\n * those throws and reports invalid_type, so the sentinel branch does the same\n * without allocating an issue. Boolean never invokes conversion hooks.\n */\nfunction buildCoercedPrimitive(ir: CoercedPrimitiveIR, input: string, g: BuildGen): Built | null {\n if (ir.coerce !== true) return null;\n const value = local(g, \"bc\");\n let conversion: string;\n switch (ir.type) {\n case \"number\":\n conversion = `Number(${input})`;\n break;\n case \"boolean\":\n conversion = `Boolean(${input})`;\n break;\n case \"bigint\":\n conversion = `BigInt(${input})`;\n break;\n case \"date\":\n conversion = `new Date(${input})`;\n break;\n }\n\n // A fresh shallow node is intentional: only the coerce flag changes. The\n // existing primitive generator remains the single source of truth for every\n // range, format, refine and finite/valid-date check.\n const predicate = generateFast(\n { ...ir, coerce: false },\n createFastGen(value, g.ctx, true, g.scope),\n );\n if (predicate === null) return null;\n\n const assign = `${value}=${conversion};`;\n const code = ir.type === \"boolean\" ? assign : `try{${assign}}catch(_){return ${g.fail};}`;\n return {\n code: code + (predicate === \"true\" ? \"\" : `if(!(${predicate}))return ${g.fail};`),\n value,\n };\n}\n\n/**\n * `.default(v)`: `undefined` yields the declared value without running the\n * inner schema, anything else parses normally — the same two branches\n * `slowDefault` emits, reading the value off the retained schema so a\n * reference-typed default keeps zod's identity (one shared object, not a copy).\n *\n * The substituted value is not validated, so it makes the fast path a PARTIAL\n * predicate (`fc(undefined)` is false where the schema accepts) — which is why\n * this records {@link CodeGenContext.buildSubstitutesValue}, on which\n * `generateValidator` withholds `.is()`.\n */\nfunction buildDefault(\n ir: SchemaIR & { type: \"default\" },\n input: string,\n g: BuildGen,\n): Built | null {\n const inner = build(ir.inner, input, g);\n if (inner === null) return null;\n // Every `default` node is in the rebuild set, so it is always BUILT and never\n // passed through — which makes this flag an exact record of whether the\n // finished pass substitutes a value.\n g.ctx.buildSubstitutesValue = true;\n const out = local(g, \"bq\");\n const value = defaultValueExpr(ir);\n // Zod re-applies the default when the inner returns undefined for a defined\n // input; only emitted when the inner can actually do that.\n const reapply = needsPostInnerDefault(ir) ? `if(${out}===undefined){${out}=${value};}` : \"\";\n return {\n code:\n `if(${input}===undefined){${out}=${value};}` +\n `else{${inner.code}${out}=${inner.value};${reapply}}`,\n value: out,\n };\n}\n\n/** `optional` / `nullable` around a rebuilding inner: pass the sentinel through. */\nfunction buildSentinel(\n innerIR: SchemaIR,\n input: string,\n g: BuildGen,\n test: string,\n sentinel: string,\n): Built | null {\n const inner = build(innerIR, input, g);\n if (inner === null) return null;\n const out = local(g, \"bw\");\n return {\n code: `if(${input}${test}){${out}=${sentinel};}else{${inner.code}${out}=${inner.value};}`,\n value: out,\n };\n}\n\n/** Allocate a `var` the hosted build function declares. */\nfunction local(g: BuildGen, prefix: string): string {\n const name = emitTemp(g.ctx, prefix);\n g.scope.temps.push(name);\n return name;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA+FA,SAAS,WAAW,MAAuC;CACzD,MAAM,0BAAU,IAAI,IAAsB,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;CACrD,MAAM,QAAoB,CAAC;CAC3B,MAAM,uBAAO,IAAI,IAAc;CAC/B,MAAM,WAAW,SAAyB;EACxC,IAAI,KAAK,IAAI,IAAI,GAAG;EACpB,KAAK,IAAI,IAAI;EACb,MAAM,KAAK,IAAI;EACf,IAAI,KAAK,SAAS,mBAAmB,QAAQ,IAAI,KAAK,OAAO,KAAK,KAAK;EACvE,KAAK,MAAM,SAAS,SAAS,IAAI,GAAG,QAAQ,KAAK;CACnD;CACA,QAAQ,IAAI;CAEZ,MAAM,2BAAW,IAAI,IAAc;CACnC,KAAK,IAAI,UAAU,MAAM,UAAU;EACjC,UAAU;EACV,KAAK,MAAM,QAAQ,OAAO;GACxB,IAAI,SAAS,IAAI,IAAI,GAAG;GACxB,MAAM,SAAS,KAAK,SAAS,iBAAiB,QAAQ,IAAI,KAAK,SAAS,CAAC,IAAI,KAAA;GAwB7E,IAtBG,KAAK,SAAS,YAAY,KAAK,qBAAqB,QAKrD,KAAK,SAAS,aAEd,KAAK,SAAS,gBAIb,KAAK,SAAS,aACZ,KAAK,WAAW,QAAQ,KAAK,OAAO,MAAM,MAAM,EAAE,SAAS,kBAAkB,OAC9E,KAAK,SAAS,YACd,KAAK,SAAS,aACd,KAAK,SAAS,YACd,KAAK,SAAS,WACd,KAAK,WAAW,QAElB,KAAK,SAAS,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M,OAAO;CAC3B,MAAM,MAAM,MAAM,GAAG,IAAI;CACzB,OAAO;EACL,MAAM,MAAM,QAAQ,KAAK,IAAI,IAAI,GAAG,SAAS,SAAS,MAAM,OAAO,IAAI,GAAG,MAAM,MAAM;EACtF,OAAO;CACT;AACF;;AAGA,SAAS,MAAM,GAAa,QAAwB;CAClD,MAAM,OAAO,SAAS,EAAE,KAAK,MAAM;CACnC,EAAE,MAAM,MAAM,KAAK,IAAI;CACvB,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"build-path.js","names":[],"sources":["../../../src/core/codegen/build-path.ts"],"sourcesContent":["/**\n * Build Path: one uninstrumented pass that VALIDATES and BUILDS rewritten\n * output together, abandoning the whole parse at the first failing check.\n *\n * `z.object()` strips unknown keys, so a successful parse cannot return the\n * input by reference — it must produce a fresh object. That rules out the Fast\n * Path (whose contract is `data === input`), and before this the only remaining\n * option was the eager slow walk: a fully instrumented traversal that collects\n * issues on every parse, valid or not.\n *\n * Two passes are wasteful in either direction. Validating first and building\n * afterwards reads every property twice (measured 29.7 ns vs 21.6 for the slow\n * walk on a 6-field object). Building with issue collection pays the\n * instrumentation even when nothing fails. Doing both in ONE pass, with a\n * sentinel instead of an issues array, beats both — and a failure costs only\n * the checks up to the first bad one, because the issue-producing walk is\n * deferred into `.error` exactly as `__zcFinD` does for mutation-free schemas:\n *\n * object clean object invalid array(8) invalid\n * slow walk 21.6 ns 30.4 ns 197.5 ns\n * build path 18.1 ns 7.7 ns 9.8 ns\n *\n * A subtree that rebuilds nothing is validated with its existing Fast Path\n * expression and passed through by reference, so only nodes that genuinely\n * produce a new value need code here; anything else returns null and keeps the\n * eager walk.\n *\n * Coverage is what decides whether this pass is reached at all, because it is\n * all-or-nothing per schema: ONE unmodelled node anywhere in the tree costs the\n * whole schema its single-pass parse. Modelled, beyond the stripping containers\n * this started with: array size checks and `.refine()`, object-level `.refine()`,\n * `.default()` substitution, ordered string rewrites (`.trim()`,\n * `.toLowerCase()`), sync `.transform()`, `z.stringbool()`, and the five native\n * coercions (`string`, `number`, `boolean`, `bigint`, `date`). Still declined, via\n * {@link mutatesBeyondStrip} — `.catch()` (its callback wants the inner schema's\n * issue list, which this pass never builds), `z.url()`, and `superRefine`.\n */\n\nimport type { ObjectIR, RefineEffectCheckIR, SchemaIR, StringBoolIR } from \"../types.js\";\nimport type { CodeGenContext, FastScope } from \"./context.js\";\nimport {\n declareFastTemps,\n emitEffectCallable,\n emitEffectFn,\n emitRuntimeHelper,\n emitTemp,\n escapeString,\n keyMembershipTest,\n outputAlwaysDefined,\n rejectsUndefined,\n} from \"./context.js\";\nimport { createFastGen, generateFast } from \"./fast-path.js\";\nimport { EXTRACT_CAP, estimateFastCost, MIN_EXTRACT, predictedInlineSize } from \"./fast-size.js\";\nimport { ZC_HOP_DECL } from \"./issue-decls.js\";\nimport { defaultValueExpr, needsPostInnerDefault } from \"./schemas/default.js\";\nimport { innerAppliesDefaultOnUndefined } from \"./schemas/optional.js\";\nimport { fastStringCheck } from \"./schemas/string.js\";\nimport { emitStringBoolMap, stringBoolUsesInline } from \"./schemas/string-bool.js\";\n\n/** Statements that leave the built value in `value`, or `return <FAIL>` on failure. */\ninterface Built {\n code: string;\n value: string;\n}\n\ninterface BuildGen {\n ctx: CodeGenContext;\n /** Identifier of the per-validator FAIL sentinel. */\n fail: string;\n /** `var` temps and running emitted size of the function being assembled. */\n scope: FastScope;\n /**\n * May THIS node be hosted in its own function? False for the node a hosted\n * build was created for — it already IS that function, so re-hosting it would\n * recurse forever. Children are always extractable, letting an oversized\n * helper split further.\n */\n extractable: boolean;\n /** Nodes of the root schema that rebuild (see rebuildSet). */\n rebuilds: ReadonlySet<SchemaIR>;\n}\n\n/**\n * Which nodes of `root` produce a value that is not their input — a stripping\n * object, coercion, codec, default, overwrite or transform, including\n * containers that contain one. Everything else can be validated in place and\n * passed through, which is what keeps this generator small.\n *\n * Computed as a fixpoint rather than a plain walk because of recursion: a\n * `recursiveRef` is a back-edge with no children, so a local walk reads false\n * for it and would pass the whole recursive subtree through by reference —\n * leaving every nested value unstripped while the outermost one was rebuilt.\n * Resolving the ref against its target closes the cycle, and iterating to a\n * fixpoint settles the mutual dependency between the two.\n */\nfunction rebuildSet(root: SchemaIR): ReadonlySet<SchemaIR> {\n const targets = new Map<number, SchemaIR>([[0, root]]);\n const nodes: SchemaIR[] = [];\n const seen = new Set<SchemaIR>();\n const collect = (node: SchemaIR): void => {\n if (seen.has(node)) return;\n seen.add(node);\n nodes.push(node);\n if (node.type === \"recursionTarget\") targets.set(node.refId, node.inner);\n for (const child of children(node)) collect(child);\n };\n collect(root);\n\n const rebuilds = new Set<SchemaIR>();\n for (let changed = true; changed;) {\n changed = false;\n for (const node of nodes) {\n if (rebuilds.has(node)) continue;\n const target = node.type === \"recursiveRef\" ? targets.get(node.refId ?? 0) : undefined;\n const rebuild =\n (node.type === \"object\" && node.stripUnknownKeys === true) ||\n // `.default()` substitutes its own value for `undefined`, so its output\n // is not its input even when the inner schema passes through — it must\n // never be handed to `passthrough`, whose fast check would reject the\n // absent value outright.\n node.type === \"default\" ||\n // `z.stringbool()` replaces its accepted string with a boolean.\n node.type === \"stringBool\" ||\n // An overwrite effect (`.trim()`, `.toLowerCase()`) rewrites the string,\n // so the node's output is a new value: it has to be BUILT rather than\n // validated in place (see buildString).\n (node.type === \"string\" &&\n (node.coerce === true || node.checks.some((c) => c.kind === \"overwrite_effect\"))) ||\n ((node.type === \"number\" ||\n node.type === \"boolean\" ||\n node.type === \"bigint\" ||\n node.type === \"date\") &&\n node.coerce === true) ||\n // `.transform(fn)` replaces the value with the callback's result.\n node.type === \"effect\" ||\n (target !== undefined && rebuilds.has(target)) ||\n children(node).some((child) => rebuilds.has(child));\n if (rebuild) {\n rebuilds.add(node);\n changed = true;\n }\n }\n }\n return rebuilds;\n}\n\n/** Does `ir`, taken as a whole schema, produce a value that is not its input? */\nexport function rebuildsOutput(ir: SchemaIR): boolean {\n return rebuildSet(ir).has(ir);\n}\n\n/**\n * True when the subtree mutates for any reason the build pass cannot reproduce —\n * `.catch()`, `z.url()`, `superRefine`. Those rewrite values in ways this pass\n * (which validates, coerces, decodes string booleans, substitutes declared\n * defaults, applies ordered string rewrites and copies) does not model, so the\n * schema keeps the eager walk.\n */\nfunction mutatesBeyondStrip(ir: SchemaIR): boolean {\n return mutatesHere(ir) || children(ir).some(mutatesBeyondStrip);\n}\n\n/**\n * Does this node rewrite values on its own account (ignoring its children, and\n * ignoring the reshaping a strip object does)? Mirrors the node-local half of\n * `hasMutation`; the recursion above supplies the other half.\n */\nfunction mutatesHere(ir: SchemaIR): boolean {\n switch (ir.type) {\n case \"string\":\n // Coercion and overwrite effects are absent: `buildString` applies them\n // in order. A `z.url()` check still is not — it trims, normalizes and\n // needs its own normalization/error semantics.\n return (\n superRefines(ir.checks) ||\n ir.checks.some((c) => c.kind === \"string_format\" && c.format === \"url\")\n );\n case \"number\":\n return superRefines(ir.checks);\n case \"boolean\":\n case \"bigint\":\n case \"date\":\n return false;\n // `default` and `effect` are absent: substituting a constant for `undefined`\n // and applying a sync transform are both modelled (see buildDefault /\n // buildEffect), and their inners are reached through `children`.\n //\n // `catch` is NOT: its catchValue callback receives a ctx carrying the inner\n // schema's collected issues, and this pass produces a sentinel instead of an\n // issue list — there is nothing to hand it.\n case \"catch\":\n case \"fallback\":\n return true;\n case \"object\":\n case \"array\":\n return superRefines(ir.checks);\n default:\n return false;\n }\n}\n\nfunction superRefines(checks: readonly { kind: string }[] | undefined): boolean {\n return checks !== undefined && checks.some((c) => c.kind === \"super_refine_effect\");\n}\n\nfunction children(ir: SchemaIR): readonly SchemaIR[] {\n switch (ir.type) {\n case \"object\":\n return ir.catchall\n ? [...Object.values(ir.properties), ir.catchall]\n : Object.values(ir.properties);\n case \"array\":\n return [ir.element];\n case \"tuple\":\n return ir.rest === null ? ir.items : [...ir.items, ir.rest];\n case \"record\":\n case \"map\":\n return [ir.keyType, ir.valueType];\n case \"set\":\n return [ir.valueType];\n case \"union\":\n case \"discriminatedUnion\":\n return ir.options;\n case \"intersection\":\n return [ir.left, ir.right];\n case \"optional\":\n case \"nullable\":\n case \"readonly\":\n case \"default\":\n case \"catch\":\n case \"effect\":\n case \"recursionTarget\":\n case \"zodDelegate\":\n return [ir.inner];\n case \"pipe\":\n return [ir.in, ir.out];\n default:\n return [];\n }\n}\n\n/**\n * Host the whole schema as `function NAME(input){…}` returning the built value\n * or the FAIL sentinel. Returns the function name, or null when the schema is\n * not expressible as a single build pass.\n */\nexport function generateBuild(ir: SchemaIR, ctx: CodeGenContext): string | null {\n const rebuilds = rebuildSet(ir);\n if (!rebuilds.has(ir) || mutatesBeyondStrip(ir)) return null;\n const fail = emitFailSentinel(ctx);\n const scope: FastScope = { temps: [], used: 0 };\n const built = build(ir, \"input\", { ctx, extractable: false, fail, rebuilds, scope });\n if (built === null) return null;\n const name = emitTemp(ctx, \"vb\");\n ctx.preamble.push(\n `function ${name}(input){${declareFastTemps(scope)}${built.code}return ${built.value};}`,\n );\n return name;\n}\n\n/** One `{}` per validator, compared by identity — no parse output can equal it. */\nfunction emitFailSentinel(ctx: CodeGenContext): string {\n if (ctx.buildFailName === undefined) {\n ctx.buildFailName = `__bf_${ctx.counter++}`;\n ctx.preamble.push(`var ${ctx.buildFailName}={};`);\n }\n return ctx.buildFailName;\n}\n\n/**\n * Statements producing the built value of `ir` read from `input`, or null.\n *\n * Size-gated exactly like the fast path: once inlining `ir` would push the\n * function being assembled past EXTRACT_CAP, the sub-build is hosted as its own\n * `__vb_N(p)` returning value-or-FAIL and replaced by a call. Without this a\n * deeply nested schema emits one enormous build function — measured at 113 KB\n * and 354 KB on the deep fixtures — far past the bytecode size where V8 stops\n * running TurboFan on it, which would forfeit the speed this path exists for.\n */\nfunction build(ir: SchemaIR, input: string, g: BuildGen): Built | null {\n // Resolved before the passthrough shortcut below. A back-edge carries no\n // children, so `rebuildsOutput` reads false for it — and passing it through by\n // reference would leave every nested recursive value unstripped while the\n // outermost one was rebuilt.\n if (ir.type === \"recursiveRef\") return buildRecursiveCall(ir.refId ?? 0, input, g);\n if (ir.type === \"recursionTarget\") return buildRecursionTarget(ir, input, g);\n if (!g.rebuilds.has(ir)) return passthrough(ir, input, g);\n\n const cache = (g.ctx.fastSizeCache ??= new WeakMap<SchemaIR, number>());\n if (\n g.extractable &&\n g.scope.used + predictedInlineSize(ir, input.length, cache) > EXTRACT_CAP &&\n (g.scope.used > EXTRACT_CAP || estimateFastCost(ir, cache) >= MIN_EXTRACT)\n ) {\n const hosted = hostBuild(ir, g);\n if (hosted !== null) {\n const slot = local(g, \"bh\");\n const code = `${slot}=${hosted}(${input});if(${slot}===${g.fail})return ${g.fail};`;\n g.scope.used += code.length;\n return { code, value: slot };\n }\n }\n\n // This node's extraction decision is made; its descendants get to make their\n // own, so an oversized hosted helper keeps splitting.\n const before = g.scope.used;\n const out = buildInline(ir, input, { ...g, extractable: true });\n if (out !== null) g.scope.used = before + out.code.length;\n return out;\n}\n\n/** Host `ir`'s build in its own function over a fresh parameter; returns its name. */\nfunction hostBuild(ir: SchemaIR, g: BuildGen): string | null {\n const param = emitTemp(g.ctx, \"bp\");\n const scope: FastScope = { temps: [], used: 0 };\n const inner = build(ir, param, { ...g, extractable: false, scope });\n if (inner === null) return null;\n const name = emitTemp(g.ctx, \"vb\");\n g.ctx.preamble.push(\n `function ${name}(${param}){${declareFastTemps(scope)}${inner.code}return ${inner.value};}`,\n );\n return name;\n}\n\nfunction buildInline(ir: SchemaIR, input: string, g: BuildGen): Built | null {\n switch (ir.type) {\n case \"object\":\n return buildObject(ir, input, g);\n case \"array\":\n return buildArray(ir, input, g);\n case \"tuple\":\n return buildTuple(ir, input, g);\n case \"record\":\n return buildRecord(ir, input, g);\n case \"optional\":\n // A default further down the chain consumes undefined into a value, so\n // the `undefined → undefined` shortcut must not fire — same rule (and\n // same helper) the slow and fast paths already apply.\n return innerAppliesDefaultOnUndefined(ir.inner)\n ? build(ir.inner, input, g)\n : buildSentinel(ir.inner, input, g, \"===undefined\", \"undefined\");\n case \"nullable\":\n // `null` short-circuits unconditionally in zod, whatever the inner is;\n // undefined flows through, so an inner default still fires.\n return buildSentinel(ir.inner, input, g, \"===null\", \"null\");\n case \"default\":\n return buildDefault(ir, input, g);\n case \"string\":\n return buildString(ir, input, g);\n case \"stringBool\":\n return buildStringBool(ir, input, g);\n case \"number\":\n case \"boolean\":\n case \"bigint\":\n case \"date\":\n return buildCoercedPrimitive(ir, input, g);\n case \"effect\":\n return buildEffect(ir, input, g);\n case \"readonly\":\n return build(ir.inner, input, g);\n case \"zodDelegate\":\n return build(ir.inner, input, g);\n case \"union\":\n case \"discriminatedUnion\":\n return buildUnion(ir, input, g);\n default:\n // A rebuilding intersection, map or set: expressible in principle, but\n // each needs its own output-shaping rules, so they keep the eager walk\n // until there is a measured reason to add them.\n return null;\n }\n}\n\n/**\n * Host the target's build once under a name registered BEFORE its body is\n * generated, so the back-edges inside that body resolve to it.\n */\nfunction buildRecursionTarget(\n ir: SchemaIR & { type: \"recursionTarget\" },\n input: string,\n g: BuildGen,\n): Built | null {\n const table = (g.ctx.buildRecNames ??= new Map<number, string>());\n if (!table.has(ir.refId)) {\n const name = emitTemp(g.ctx, \"vbr\");\n table.set(ir.refId, name);\n const param = emitTemp(g.ctx, \"bp\");\n const scope: FastScope = { temps: [], used: 0 };\n const inner = build(ir.inner, param, { ...g, extractable: false, scope });\n if (inner === null) {\n table.delete(ir.refId);\n return null;\n }\n g.ctx.preamble.push(\n `function ${name}(${param}){${declareFastTemps(scope)}${inner.code}return ${inner.value};}`,\n );\n }\n return buildRecursiveCall(ir.refId, input, g);\n}\n\n/** Call the hosted build for a recursion target, propagating its FAIL. */\nfunction buildRecursiveCall(refId: number, input: string, g: BuildGen): Built | null {\n const name = g.ctx.buildRecNames?.get(refId);\n if (name === undefined) return null;\n const slot = local(g, \"bh\");\n return {\n code: `${slot}=${name}(${input});if(${slot}===${g.fail})return ${g.fail};`,\n value: slot,\n };\n}\n\n/**\n * Try each option in declaration order and take the first that builds — which\n * is what zod's union does with the first option that parses.\n *\n * Every option is HOSTED rather than inlined, and that is load-bearing: a\n * failing build signals with `return FAIL`, which inside the enclosing function\n * would abandon the whole parse instead of moving on to the next option. Behind\n * a call, the same signal is just a value to test.\n *\n * A discriminated union gets the same treatment rather than a switch: the\n * options still have to be probed by call, and its dispatch advantage is\n * already spent by the enclosing container's own work.\n */\nfunction buildUnion(\n ir: SchemaIR & { type: \"discriminatedUnion\" | \"union\" },\n input: string,\n g: BuildGen,\n): Built | null {\n const hosted: string[] = [];\n for (const option of ir.options) {\n const fn = g.rebuilds.has(option) ? hostBuild(option, g) : hostPassthrough(option, g);\n if (fn === null) return null;\n hosted.push(fn);\n }\n if (hosted.length === 0) return null;\n\n const out = local(g, \"bu\");\n let code = `${out}=${hosted[0] as string}(${input});`;\n for (const fn of hosted.slice(1)) {\n code += `if(${out}===${g.fail}){${out}=${fn}(${input});}`;\n }\n code += `if(${out}===${g.fail})return ${g.fail};`;\n return { code, value: out };\n}\n\n/**\n * Host a non-rebuilding option as `value-or-FAIL`, so a union can probe it with\n * the same protocol as a rebuilding one.\n */\nfunction hostPassthrough(ir: SchemaIR, g: BuildGen): string | null {\n const param = emitTemp(g.ctx, \"bp\");\n const scope: FastScope = { temps: [], used: 0 };\n const expr = generateFast(ir, createFastGen(param, g.ctx, true, scope));\n if (expr === null) return null;\n const name = emitTemp(g.ctx, \"vp\");\n g.ctx.preamble.push(\n `function ${name}(${param}){${declareFastTemps(scope)}return ${expr === \"true\" ? param : `(${expr})?${param}:${g.fail}`};}`,\n );\n return name;\n}\n\n/** Validate in place with the Fast Path and hand the input straight back. */\nfunction passthrough(ir: SchemaIR, input: string, g: BuildGen): Built | null {\n const scoped = createFastGen(input, g.ctx, true, g.scope);\n const expr = generateFast(ir, scoped);\n if (expr === null) return null;\n return { code: expr === \"true\" ? \"\" : `if(!(${expr}))return ${g.fail};`, value: input };\n}\n\n/**\n * Rebuild from the declared keys. Sound for a stripping object (that IS the\n * output) and for a strict one (unknown keys are rejected, so the declared keys\n * are the whole key set). A loose object or one with a `.catchall()` keeps keys\n * this pass does not enumerate, so those bail.\n */\nfunction buildObject(ir: ObjectIR, input: string, g: BuildGen): Built | null {\n if (ir.catchall !== undefined) return null;\n if (ir.stripUnknownKeys !== true && ir.strict !== true) return null;\n if (ir.suppressAbsentKeys !== undefined && ir.suppressAbsentKeys.length > 0) return null;\n // Object-level `.refine()` runs on the assembled output (below). superRefine\n // rewrites the payload, which this pass does not model — mutatesBeyondStrip\n // already rejects it, so this is a belt-and-braces narrowing of the type.\n const refines = ir.checks ?? [];\n if (refines.some((check) => check.kind !== \"refine_effect\")) return null;\n\n let code = `if(typeof ${input}!==\"object\"||${input}===null||Array.isArray(${input}))return ${g.fail};`;\n\n if (ir.strict === true) {\n const keyVar = local(g, \"bk\");\n code += `for(${keyVar} in ${input}){if(!(${keyMembershipTest(g.ctx, Object.keys(ir.properties), keyVar)}))return ${g.fail};}`;\n }\n\n const slots: { always: boolean; keyStr: string; value: string }[] = [];\n for (const [key, propIR] of Object.entries(ir.properties)) {\n const keyStr = escapeString(key);\n const slot = local(g, \"bv\");\n code += `${slot}=${input}[${keyStr}];`;\n const propBuilt = build(propIR, slot, g);\n if (propBuilt === null) return null;\n code += propBuilt.code;\n slots.push({ always: outputAlwaysDefined(propIR), keyStr, value: propBuilt.value });\n }\n\n // Same assembly the eager strip walk uses: the longest LEADING run of\n // always-present keys goes into one object literal (V8 stamps it from a\n // cached boilerplate map in a single allocation), and everything after the\n // first conditional key is appended so insertion order still matches zod.\n // The per-key test is zod's own — keep the key when the parsed value is\n // defined, or when it was present on the input at all.\n const out = local(g, \"bo\");\n const literal: string[] = [];\n let appends = \"\";\n let leading = true;\n for (const slot of slots) {\n if (leading && slot.always) {\n literal.push(`${slot.keyStr}:${slot.value}`);\n continue;\n }\n leading = false;\n appends += slot.always\n ? `${out}[${slot.keyStr}]=${slot.value};`\n : `if(${slot.value}!==undefined||(${slot.keyStr} in ${input})){${out}[${slot.keyStr}]=${slot.value};}`;\n }\n code += `${out}={${literal.join(\",\")}};${appends}`;\n // Zod parses the properties into the payload first and skips the check chain\n // when that produced issues, so a bad property suppresses the refine — which\n // this pass gets for free, having already returned FAIL at that property.\n for (const check of refines) {\n code += `if(!${emitEffectCallable(g.ctx, check as RefineEffectCheckIR)}(${out}))return ${g.fail};`;\n }\n return { code, value: out };\n}\n\nfunction buildArray(ir: SchemaIR & { type: \"array\" }, input: string, g: BuildGen): Built | null {\n // Length checks are pure predicates over `input.length`, so they hoist ahead\n // of the element loop: a size mismatch bails before a single element is\n // validated. Zod reports the per-element issue first when both fail, but the\n // build pass produces no issues — only the sentinel — and the deferred walk\n // that does produce them keeps zod's order.\n let sizes = \"\";\n const refines: RefineEffectCheckIR[] = [];\n for (const check of ir.checks) {\n switch (check.kind) {\n case \"min_length\":\n sizes += `if(${input}.length<${check.minimum})return ${g.fail};`;\n break;\n case \"max_length\":\n sizes += `if(${input}.length>${check.maximum})return ${g.fail};`;\n break;\n case \"length_equals\":\n sizes += `if(${input}.length!==${check.length})return ${g.fail};`;\n break;\n case \"refine_effect\":\n refines.push(check);\n break;\n default:\n // super_refine (rewrites the value) or a check kind not modelled here.\n return null;\n }\n }\n\n const out = local(g, \"ba\");\n const index = local(g, \"bi\");\n const elem = local(g, \"be\");\n const inner = build(ir.element, elem, g);\n if (inner === null) return null;\n let code =\n `if(!Array.isArray(${input}))return ${g.fail};` +\n sizes +\n `${out}=new Array(${input}.length);` +\n `for(${index}=0;${index}<${input}.length;${index}++){` +\n `${elem}=${input}[${index}];${inner.code}${out}[${index}]=${inner.value};}`;\n // `.refine()` sees the parsed payload, which for a rebuilding element is the\n // freshly assembled array — the same value zod hands its checks.\n for (const check of refines) {\n code += `if(!${emitEffectCallable(g.ctx, check)}(${out}))return ${g.fail};`;\n }\n return { code, value: out };\n}\n\nfunction buildTuple(ir: SchemaIR & { type: \"tuple\" }, input: string, g: BuildGen): Built | null {\n // Trailing-optional and rest handling shape the output length; keep those on\n // the eager walk rather than restating the rules here.\n if (ir.rest !== null) return null;\n if (ir.items.some((item) => !rejectsUndefined(item))) return null;\n\n let code = `if(!Array.isArray(${input})||${input}.length!==${ir.items.length})return ${g.fail};`;\n const values: string[] = [];\n for (const [index, itemIR] of ir.items.entries()) {\n const slot = local(g, \"bt\");\n code += `${slot}=${input}[${index}];`;\n const inner = build(itemIR as SchemaIR, slot, g);\n if (inner === null) return null;\n code += inner.code;\n values.push(inner.value);\n }\n const out = local(g, \"bl\");\n code += `${out}=[${values.join(\",\")}];`;\n return { code, value: out };\n}\n\nfunction buildRecord(ir: SchemaIR & { type: \"record\" }, input: string, g: BuildGen): Built | null {\n const plainStringKey =\n ir.keyType.type === \"string\" && ir.keyType.checks.length === 0 && ir.keyType.coerce !== true;\n if (!plainStringKey) return null;\n\n const out = local(g, \"br\");\n const keyVar = local(g, \"brk\");\n const valVar = local(g, \"brv\");\n const inner = build(ir.valueType, valVar, g);\n if (inner === null) return null;\n const hop = emitRuntimeHelper(g.ctx, \"__zcHop\", ZC_HOP_DECL);\n const code =\n `if(typeof ${input}!==\"object\"||${input}===null||Array.isArray(${input}))return ${g.fail};` +\n `${out}={};` +\n `for(${keyVar} in ${input}){if(${hop}.call(${input},${keyVar})){` +\n `${valVar}=${input}[${keyVar}];${inner.code}${out}[${keyVar}]=${inner.value};}}`;\n return { code, value: out };\n}\n\n/**\n * `.transform(fn)`: validate the inner schema, then hand its parsed value to the\n * callback. Zod's transform is a pipe whose `in` failing aborts the whole thing,\n * which is exactly what returning FAIL from the inner build does — so the\n * callback runs only on a clean parse, as `slowEffect` guarantees with its issue\n * count.\n *\n * The IR reaches here only for a synchronous single-argument callback: a\n * `ctx`-taking or async transform is extracted as a `fallback` instead\n * (see extractPipe), so there is no parse context to reproduce.\n */\nfunction buildEffect(ir: SchemaIR & { type: \"effect\" }, input: string, g: BuildGen): Built | null {\n const inner = build(ir.inner, input, g);\n if (inner === null) return null;\n const out = local(g, \"bx\");\n return {\n code: `${inner.code}${out}=${emitEffectCallable(g.ctx, ir)}(${inner.value});`,\n value: out,\n };\n}\n\n/**\n * A coercing and/or overwrite string (`z.coerce.string()`, `.trim()`,\n * `.toLowerCase()`, ...): coerce first, then emit checks one statement at a time\n * in DECLARATION order, interleaved with rewrites, because a rewrite is visible\n * to every check after it — `z.string().trim().min(1)` rejects `\" \"` where\n * `z.string().min(1).trim()` accepts it. That ordering is exactly why the fast\n * path, which sorts checks cheapest-first and returns the input unchanged, has\n * to decline these.\n *\n * Only reached for a rewriting string; a non-coercing, check-only one never\n * enters the rebuild set and is validated in place by `passthrough`.\n */\nfunction buildString(ir: SchemaIR & { type: \"string\" }, input: string, g: BuildGen): Built | null {\n const value = local(g, \"bs\");\n let code =\n ir.coerce === true\n ? `try{${value}=String(${input});}catch(_){return ${g.fail};}`\n : `if(typeof ${input}!==\"string\")return ${g.fail};${value}=${input};`;\n for (const check of ir.checks) {\n switch (check.kind) {\n case \"overwrite_effect\":\n code += `${value}=${emitEffectFn(g.ctx, check.source)}(${value});`;\n break;\n case \"refine_effect\":\n code += `if(!${emitEffectCallable(g.ctx, check)}(${value}))return ${g.fail};`;\n break;\n case \"super_refine_effect\":\n // Rewrites through zod's payload; mutatesBeyondStrip already rejects it.\n return null;\n default: {\n const expr = fastStringCheck(check, value, g.ctx);\n if (expr === null) return null; // z.url(), unknown format\n code += `if(!(${expr}))return ${g.fail};`;\n }\n }\n }\n return { code, value };\n}\n\n/**\n * `z.stringbool()`: normalize once, select the declared truthy/falsy side, and\n * return the boolean directly. The ordinary Fast Path cannot host this codec\n * because its contract returns the original input by reference; the build path\n * is designed for exactly this kind of small output rewrite.\n */\nfunction buildStringBool(ir: StringBoolIR, input: string, g: BuildGen): Built {\n let code = `if(typeof ${input}!==\"string\")return ${g.fail};`;\n let normalized = input;\n if (!ir.caseSensitive) {\n normalized = local(g, \"bn\");\n code += `${normalized}=${input}.toLowerCase();`;\n }\n\n const out = local(g, \"bb\");\n if (stringBoolUsesInline(ir)) {\n const membership = (values: readonly string[]): string =>\n values.map((value) => `${normalized}===${escapeString(value)}`).join(\"||\");\n code +=\n `if(${membership(ir.truthy)}){${out}=true;}` +\n `else if(${membership(ir.falsy)}){${out}=false;}` +\n `else{return ${g.fail};}`;\n } else {\n const lookup = emitStringBoolMap(ir, g.ctx);\n code += `${out}=${lookup}.get(${normalized});if(${out}===undefined)return ${g.fail};`;\n }\n return { code, value: out };\n}\n\n/** Primitive nodes whose `coerce` flag rewrites their output before checks run. */\ntype CoercedPrimitiveIR = Extract<SchemaIR, { type: \"number\" | \"boolean\" | \"bigint\" | \"date\" }>;\n\n/**\n * Coerce once into a local, then reuse the ordinary Fast Path as the acceptance\n * predicate over the converted value. The build path only needs a verdict on\n * its hot pass; if it fails, the existing deferred slow walk reruns the original\n * coercing schema and produces Zod-identical issues.\n *\n * Number/BigInt/Date conversion can invoke user hooks and throw. Zod catches\n * those throws and reports invalid_type, so the sentinel branch does the same\n * without allocating an issue. Boolean never invokes conversion hooks.\n */\nfunction buildCoercedPrimitive(ir: CoercedPrimitiveIR, input: string, g: BuildGen): Built | null {\n if (ir.coerce !== true) return null;\n const value = local(g, \"bc\");\n let conversion: string;\n switch (ir.type) {\n case \"number\":\n conversion = `Number(${input})`;\n break;\n case \"boolean\":\n conversion = `Boolean(${input})`;\n break;\n case \"bigint\":\n conversion = `BigInt(${input})`;\n break;\n case \"date\":\n conversion = `new Date(${input})`;\n break;\n }\n\n // A fresh shallow node is intentional: only the coerce flag changes. The\n // existing primitive generator remains the single source of truth for every\n // range, format, refine and finite/valid-date check.\n const predicate = generateFast(\n { ...ir, coerce: false },\n createFastGen(value, g.ctx, true, g.scope),\n );\n if (predicate === null) return null;\n\n const assign = `${value}=${conversion};`;\n const code = ir.type === \"boolean\" ? assign : `try{${assign}}catch(_){return ${g.fail};}`;\n return {\n code: code + (predicate === \"true\" ? \"\" : `if(!(${predicate}))return ${g.fail};`),\n value,\n };\n}\n\n/**\n * `.default(v)`: `undefined` yields the declared value without running the\n * inner schema, anything else parses normally — the same two branches\n * `slowDefault` emits, reading the value off the retained schema so a\n * reference-typed default keeps zod's identity (one shared object, not a copy).\n *\n * The substituted value is not validated, so it makes the fast path a PARTIAL\n * predicate (`fc(undefined)` is false where the schema accepts) — which is why\n * this records {@link CodeGenContext.buildSubstitutesValue}, on which\n * `generateValidator` withholds `.is()`.\n */\nfunction buildDefault(\n ir: SchemaIR & { type: \"default\" },\n input: string,\n g: BuildGen,\n): Built | null {\n const inner = build(ir.inner, input, g);\n if (inner === null) return null;\n // Every `default` node is in the rebuild set, so it is always BUILT and never\n // passed through — which makes this flag an exact record of whether the\n // finished pass substitutes a value.\n g.ctx.buildSubstitutesValue = true;\n const out = local(g, \"bq\");\n const value = defaultValueExpr(ir);\n // Zod re-applies the default when the inner returns undefined for a defined\n // input; only emitted when the inner can actually do that.\n const reapply = needsPostInnerDefault(ir) ? `if(${out}===undefined){${out}=${value};}` : \"\";\n return {\n code:\n `if(${input}===undefined){${out}=${value};}` +\n `else{${inner.code}${out}=${inner.value};${reapply}}`,\n value: out,\n };\n}\n\n/** `optional` / `nullable` around a rebuilding inner: pass the sentinel through. */\nfunction buildSentinel(\n innerIR: SchemaIR,\n input: string,\n g: BuildGen,\n test: string,\n sentinel: string,\n): Built | null {\n const inner = build(innerIR, input, g);\n if (inner === null) return null;\n const out = local(g, \"bw\");\n return {\n code: `if(${input}${test}){${out}=${sentinel};}else{${inner.code}${out}=${inner.value};}`,\n value: out,\n };\n}\n\n/** Allocate a `var` the hosted build function declares. */\nfunction local(g: BuildGen, prefix: string): string {\n const name = emitTemp(g.ctx, prefix);\n g.scope.temps.push(name);\n return name;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA+FA,SAAS,WAAW,MAAuC;CACzD,MAAM,0BAAU,IAAI,IAAsB,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;CACrD,MAAM,QAAoB,CAAC;CAC3B,MAAM,uBAAO,IAAI,IAAc;CAC/B,MAAM,WAAW,SAAyB;EACxC,IA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
+
case "recursionTarget":
|
|
341
|
+
case "zodDelegate": return hasMutation(ir.inner);
|
|
341
342
|
case "union":
|
|
342
343
|
case "discriminatedUnion": return ir.options.some(hasMutation);
|
|
343
344
|
case "intersection": return hasMutation(ir.left) || hasMutation(ir.right);
|
|
@@ -399,7 +400,8 @@ function rejectsUndefined(ir) {
|
|
|
399
400
|
case "intersection": return rejectsUndefined(ir.left) || rejectsUndefined(ir.right);
|
|
400
401
|
case "nullable":
|
|
401
402
|
case "readonly":
|
|
402
|
-
case "recursionTarget":
|
|
403
|
+
case "recursionTarget":
|
|
404
|
+
case "zodDelegate": return rejectsUndefined(ir.inner);
|
|
403
405
|
default: return false;
|
|
404
406
|
}
|
|
405
407
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","names":[],"sources":["../../../src/core/codegen/context.ts"],"sourcesContent":["import type { BigIntCheckIR, CheckIR, DateCheckIR, SchemaIR, SetCheckIR } from \"../types.js\";\nimport type { SharedSchemaPlan } from \"./dedupe.js\";\nimport {\n fastTestSource,\n lookupWellKnownRegex,\n wellKnownRegexSourceName,\n} from \"./well-known-regex.js\";\n\n/** Codegen output mode. \"inline\" emits self-contained code (CLI .compiled.ts). \"lean\" emits references to imports from \"virtual:zod-compiler/runtime\" (unplugin). */\nexport type CodegenMode = \"inline\" | \"lean\";\n\nexport interface CodeGenResult {\n code: string;\n functionDef: string;\n /** Number of fallback schemas referenced by __rf[N] in the generated code. 0 = no fallbacks. */\n refCount: number;\n /**\n * Helper names referenced by this schema in lean mode (e.g. \"__zcTS\", \"__zcReEmail\").\n * Used by the unplugin transform to construct the `import { ... } from \"virtual:zod-compiler/runtime\"` line.\n * Always empty in inline mode.\n */\n usedHelpers: Set<string>;\n /**\n * Name of the hosted fast-check boolean function in the preamble (null when\n * the schema has no Fast Path). generateIIFE passes it to __zcMkv so parse()\n * and parseAsync() can return valid input without allocating an\n * intermediate SafeParseResult.\n */\n fastFnName: string | null;\n /**\n * True when `fastFnName` is a TOTAL predicate: `fc(input) === true` iff the\n * schema accepts `input` (mutation-free schemas, where a fast-check failure\n * can never become a slow-path success). generateIIFE installs it as the\n * zero-allocation `.is()` guard. False for partial fast paths\n * (default/catch — `fc` only shortcuts present-and-valid input, so a `false`\n * result does NOT imply rejection) and for schemas with no fast path, such as\n * coercion; `.is()` then derives from `safeParse(input).success`.\n */\n fastTotal: boolean;\n /**\n * Hosted predicate installed as `.is()`, when it differs from `fastFnName`.\n * A schema that rebuilds its output has no by-reference shortcut (so\n * `fastFnName` is null) yet still has an exact acceptance predicate, because\n * stripping reshapes the payload and never the verdict.\n */\n isFnName?: string | null;\n /**\n * Compact mode only: the `__rf[N]` index this validator delegates its cold\n * error path to (the schema itself, captured as a fresh root RefEntry). When\n * set, the pipeline appends a `{ schema, accessPath: \"\" }` entry at this index\n * so `generateIIFE` materializes `__rf[N]` as the original Zod schema. Absent\n * for every non-compact (fully compiled) validator.\n */\n rootDelegateRefIndex?: number;\n}\n\n/** Hosted-validator names for one recursion target (see CodeGenContext.recTargets). */\nexport interface RecTargetGen {\n /** True for the root target (refId 0) — reuses the schema's own functions. */\n isRoot: boolean;\n /**\n * safeParse-shaped slow validator name: `safeParse_<name>` for the root,\n * `__rsp_N` for a non-root target. `slowRecursiveRef` calls this.\n */\n slowName: string;\n /**\n * Boolean fast-check name (`__fcr_N`). Allocated lazily for the root (mirrors\n * recFastName), eagerly for non-root targets. Absent until the fast path\n * reaches a ref to this target.\n */\n fastName?: string;\n /** Inner IR hosted as the standalone validator body (non-root targets only). */\n inner?: SchemaIR;\n}\n\n/** Shared mutable state for code generation. Fast and slow paths share the same instance. */\nexport interface CodeGenContext {\n preamble: string[];\n counter: number;\n fnName: string;\n /** Deduplicates regex patterns: same pattern string → same preamble variable name. */\n regexCache: Map<string, string>;\n /** Codegen output mode. */\n mode: CodegenMode;\n /** Names of helpers from \"virtual:zod-compiler/runtime\" referenced in this schema (lean mode only). */\n usedHelpers: Set<string>;\n /**\n * Name of the fast-path boolean helper for the ROOT recursion target\n * (refId 0), allocated on first fastRecursiveRef visit. generateValidator\n * wraps the root fast expression as `function <name>(input){return <expr>;}`\n * so recursive refs can call it. undefined = root has no recursion on the\n * fast path.\n */\n recFastName?: string;\n /**\n * Hosted-validator name table for recursion targets, keyed by refId. Entry 0\n * is the root (the schema's own `safeParse_<name>` / `recFastName`); entries\n * ≥ 1 are non-root targets hosted as standalone `__rsp_N` (slow) / `__fcr_N`\n * (fast) helpers. `recursiveRef`/`recursionTarget` generators look up the\n * call target here. Undefined when not generating a full validator (e.g. unit\n * tests calling a single generator) — treated as root-only.\n */\n recTargets?: Map<number, RecTargetGen>;\n /** Dedup cache for hosted zero-capture effect functions: source text → preamble var. */\n effectFnCache?: Map<string, string>;\n /** Dedup cache for constant preamble declarations: initializer text → preamble var. */\n valueCache?: Map<string, string>;\n /** Name of the build path's FAIL sentinel, declared once per validator. */\n buildFailName?: string;\n /** Hosted build-function name per recursion target refId, so back-edges resolve. */\n buildRecNames?: Map<number, string>;\n /**\n * Set by the build path when it emitted a `.default()` substitution. Such a\n * schema ACCEPTS an input its fast expression rejects — `fastDefault` demands a\n * present value, since the fast path's contract is `data === input` and a\n * substituted default is not the input — so the expression is no longer an\n * exact acceptance predicate and must not be installed as `.is()`. Stripping,\n * by contrast, reshapes only the payload, which is why a build-path schema\n * otherwise still hands its predicate over.\n */\n buildSubstitutesValue?: boolean;\n /** Memo for estimateFastCost (size-gated fast-check extraction). Lazily created. */\n fastSizeCache?: WeakMap<SchemaIR, number>;\n /** Memo for estimateRuntimeCost (cheapest-first check ordering). Lazily created. */\n fastRuntimeCostCache?: WeakMap<SchemaIR, number>;\n /**\n * File-level shared slow-walk plan. Set only when generating a mutation-free\n * schema (so shared walks stay on the deferred cold path); the slow-path\n * visit() consults it to replace a repeated sub-IR with a `__zcSw_N` call.\n */\n sharedSchemas?: SharedSchemaPlan;\n}\n\n// ─── Slow Path context ────────────────────────────────────────────────────────\n\n/** Context object for slow-path (error-collecting) generator functions. */\nexport interface SlowGen {\n readonly input: string;\n readonly output: string;\n readonly path: string;\n readonly issues: string;\n readonly ctx: CodeGenContext;\n /**\n * Schema-level static error message of the node being generated\n * (z.string({ error: \"...\" })). Default message for issues this node emits\n * when the individual check has no message of its own. Set by generateSlow()\n * from ir.typeMessage; never inherited by child nodes.\n */\n readonly typeMsg?: string | undefined;\n\n /**\n * Name of a boolean variable that this node sets to `true` when it aborts in\n * the zod sense (`payload.aborted`) — currently only a pipe/codec whose `in`\n * step fails (zod's `handlePipeResult` sets `left.aborted = true`). A `union`\n * allocates one per option and reads it during pruning so a pipe option whose\n * `in` failed counts as aborted even when its only issue is a non-aborting\n * `custom`/check-level code. Undefined when the node is not inside an\n * abort-tracking option, in which case the abort is a no-op.\n *\n * Unlike input/output/path/issues, this is NOT inherited by `visit()`: it is\n * cleared at every boundary unless a node explicitly forwards it (the\n * pass-through wrappers optional/nullable/readonly do), mirroring how zod\n * propagates `payload.aborted` through transparent wrappers but not across\n * container boundaries.\n */\n readonly aborted?: string | undefined;\n\n /**\n * Recursively generate validation for a child IR node.\n * input/output/path/issues are inherited from parent unless overridden;\n * `aborted` is the exception — it is only set when explicitly passed (see the\n * `aborted` field doc), so it never leaks into container children.\n * Union generators use `{ issues }` to redirect child errors to temporary arrays.\n * Container generators use `{ input, output, path }` for element traversal.\n */\n visit(\n ir: SchemaIR,\n overrides?: {\n input?: string;\n output?: string;\n path?: string;\n issues?: string;\n // `| undefined` (unlike the others): pass-through wrappers forward\n // `g.aborted` verbatim, which is undefined outside an abort-tracking option.\n aborted?: string | undefined;\n },\n ): string;\n\n /** Generate a unique temp variable name: `__${prefix}_${counter++}` */\n temp(prefix: string): string;\n\n /** Add a regex to preamble and return the variable name. */\n regex(prefix: string, pattern: string, flags?: string): string;\n\n /** Add a Set to preamble and return the variable name. */\n set(prefix: string, values: readonly unknown[]): string;\n}\n\n/** Slow-path generator function signature — registered in slowRegistry. */\nexport type SlowGenerator<T extends SchemaIR = SchemaIR> = (ir: T, g: SlowGen) => string;\n\n// ─── Fast Path context ────────────────────────────────────────────────────────\n\n/**\n * Per-emitted-function size accumulator for size-gated fast-check extraction.\n * Shared by every node inlined into the same function; a fresh instance starts\n * each hosted helper (and the root). See fast-size.ts / generateFast.\n */\nexport interface FastScope {\n used: number;\n /**\n * `var` temps that the function this scope is assembling must declare, in\n * allocation order. Populated by {@link FastGen.local}; every site that\n * materializes a function body from a fresh scope emits\n * {@link declareFastTemps} at the top of that body.\n *\n * Function-scoped (never module-scoped) is load-bearing: a recursive\n * validator re-enters itself while an outer frame still holds a live temp,\n * and each invocation needs its own binding.\n */\n temps: string[];\n}\n\n/** `var a,b;` declaration for a scope's temps, or \"\" when it allocated none. */\nexport function declareFastTemps(scope: FastScope): string {\n return scope.temps.length > 0 ? `var ${scope.temps.join(\",\")};` : \"\";\n}\n\n/**\n * Fast check for a wrapper that compares its input against a sentinel and\n * otherwise delegates to an inner schema — `optional` (`===undefined`),\n * `nullable` (`===null`) and `default` (`!==undefined`).\n *\n * Written naively these read the input TWICE: once for the sentinel test and\n * again inside the inner check (which may itself read it several more times —\n * `typeof x===\"string\"&&x.length>=3&&x.length<=20`). V8's load elimination\n * removes the repeats only while the access is monomorphic; on the polymorphic\n * and megamorphic call sites real payloads produce (an array of objects with\n * differing key order, anything out of `JSON.parse`) every repeat is a fresh\n * megamorphic lookup. Binding the value to a local once is worth 1.1-1.7x on\n * the whole object check when the optional key is present, and is neutral when\n * it is absent.\n *\n * Only hoisted when the input is a property access; a bare local (an array\n * element variable, a record value) is already a single load, so it keeps the\n * shorter form and byte-identical output.\n */\nexport function fastSentinelWrapper(\n g: FastGen,\n innerIR: SchemaIR,\n sentinel: string,\n joiner: \"&&\" | \"||\",\n): string | null {\n if (!isPropertyAccess(g.input)) {\n const inner = g.visit(innerIR);\n return inner === null ? null : `(${g.input}${sentinel}${joiner}(${inner}))`;\n }\n const value = g.local(\"w\");\n const inner = g.visit(innerIR, { input: value });\n if (inner === null) return null;\n return `((${value}=${g.input})${sentinel}${joiner}(${inner}))`;\n}\n\n/** True for an expression that performs a property load (`x[\"a\"]`, `x.a`, `x[0][1]`). */\nfunction isPropertyAccess(expr: string): boolean {\n return expr.includes(\"[\") || expr.includes(\".\");\n}\n\n/** Context object for fast-path (boolean expression) generator functions. */\nexport interface FastGen {\n readonly input: string;\n readonly ctx: CodeGenContext;\n\n /**\n * Whether the CURRENT node may be hoisted into its own boolean helper when it\n * (with the already-emitted siblings) would overflow the function size cap.\n * False for the root and for a helper's own top node — those are already their\n * own function — but their children are extractable. See generateFast.\n */\n readonly extractable: boolean;\n\n /** Accumulated size (≈ chars) of the function currently being assembled. */\n readonly scope: FastScope;\n\n /**\n * Set on the gen for a discriminated-union option only: the discriminator\n * key. Signals `fastObject` to omit its type-guard and skip re-checking that\n * property (the switch already matched its value). Never propagated to child\n * nodes — nested objects keep their own guard.\n */\n readonly discSkipKey?: string | undefined;\n\n /**\n * Recursively generate fast-check expression for a child IR node.\n * Returns null if any child is ineligible for fast path.\n */\n visit(ir: SchemaIR, overrides?: { input?: string; discSkipKey?: string }): string | null;\n\n /**\n * A FastGen for emitting a SEPARATE function body (a hand-built preamble\n * helper such as a discriminated-union switch or an array-element loop). It\n * carries a FRESH size accumulator, so the helper's own content is size-gated\n * against the cap independently of the caller — without this, a helper's body\n * accrues to the caller's scope while the helper itself grows unbounded.\n */\n scoped(input: string): FastGen;\n\n /** Generate a unique temp variable name. */\n temp(prefix: string): string;\n\n /**\n * Allocate a unique name AND record it on this scope so the enclosing\n * emitted function declares it as a `var` (see {@link FastScope.temps}).\n * Use for a value bound inside an expression — `(t=x[\"k\"])===undefined` —\n * where `temp()` alone would leave the name undeclared.\n */\n local(prefix: string): string;\n\n /** Add a regex to preamble and return the variable name. */\n regex(prefix: string, pattern: string, flags?: string): string;\n}\n\n/** Fast-path generator function signature — registered in fastRegistry. */\nexport type FastGenerator<T extends SchemaIR = SchemaIR> = (ir: T, g: FastGen) => string | null;\n\n// ─── Shared emit helpers (used by both slow-path and fast-path factories) ────\n\n/** Allocate a fresh `__${prefix}_${n}` identifier and bump the shared counter. */\nexport function emitTemp(ctx: CodeGenContext, prefix: string): string {\n return `__${prefix}_${ctx.counter++}`;\n}\n\n/**\n * Host a zero-capture effect function (refine predicate, transform,\n * overwrite) in the preamble and return its variable name. The inline\n * `(${source})(x)` form evaluates the function expression — allocating a\n * function object — on EVERY parse at every effect site, including inside\n * the \"zero-allocation\" fast chain. V8's escape analysis erases that in\n * optimized frames, but interpreter/baseline/deopt frames pay it, and the\n * full source text re-parses as bytecode at each site. Zero-capture sources\n * reference only their own parameters and safe globals by construction, so\n * a single preamble binding is semantically identical. Deduped per schema\n * by source text.\n */\nexport function emitEffectFn(ctx: CodeGenContext, source: string): string {\n ctx.effectFnCache ??= new Map();\n const cached = ctx.effectFnCache.get(source);\n if (cached !== undefined) return cached;\n const name = `__ef_${ctx.counter++}`;\n ctx.preamble.push(`var ${name}=(${source});`);\n ctx.effectFnCache.set(source, name);\n return name;\n}\n\n/**\n * Callable expression for a user callback — a refine predicate or a transform.\n *\n * A zero-capture callback is hosted from its source text; one that CAPTURES\n * outer variables is called by reference through `__rf[N]` — the user's own\n * function object, reached from the schema — instead of costing the schema its\n * compiled path. The reference is aliased into a preamble binding rather than\n * re-read per call, for the same reason call-invoked helpers are (a per-call\n * array element load is not a foldable callee).\n */\nexport function emitEffectCallable(\n ctx: CodeGenContext,\n effect: { refIndex?: number | undefined; source?: string | undefined },\n): string {\n if (effect.refIndex !== undefined) return emitConstant(ctx, \"rfn\", `__rf[${effect.refIndex}]`);\n if (effect.source === undefined) {\n throw new Error(\"effect has neither inlineable source nor a reference index\");\n }\n return emitEffectFn(ctx, effect.source);\n}\n\n/**\n * Pristine fallback delegate: declare `var __rfp_N=__rf[N].safeParse.bind(__rf[N]);`\n * in the preamble and return the variable name. Generated code must NEVER read\n * `__rf[N].safeParse` at parse time: `__zcMkv` installs the compiled safeParse as\n * an OWN property on the original schema object, and whenever `__rf[N]` is that\n * same object the read resolves to the compiled delegate itself — infinite\n * recursion (RangeError on every parse). The fallback entry and the __zcMkv\n * target ARE the same object in compile mode (schemaExpr is the compile()\n * argument identifier) and the CLI emitter ((__src_X as any).schema); in\n * autoDiscover mode they are two textually identical constructions that any\n * downstream CSE/dedup transform (babel-plugin-zod-hoist in a field incident)\n * collapses back into one. Capturing at IIFE evaluation — before the trailing\n * `return __zcMkv(...)` mutates anything — pins zod's own implementation; the\n * worst case under cross-validator merges is delegating to an equivalent\n * compiled validator (whose own delegates were captured even earlier), never\n * a cycle.\n */\nexport function emitRfDelegate(ctx: CodeGenContext, refIndex: number): string {\n const name = `__rfp_${refIndex}`;\n const decl = `var ${name}=__rf[${refIndex}].safeParse.bind(__rf[${refIndex}]);`;\n if (!ctx.preamble.includes(decl)) {\n ctx.preamble.push(decl);\n }\n return name;\n}\n\n/**\n * Resolve a regex pattern to a runtime variable name.\n * Lean mode short-circuits well-known patterns to virtual-module names so the\n * bundler can dedup across files; everything else is cached + declared in the\n * per-IIFE preamble exactly once per pattern.\n */\nexport function emitRegex(\n ctx: CodeGenContext,\n prefix: string,\n pattern: string,\n flags?: string,\n): string {\n if (ctx.mode === \"lean\" && !flags) {\n const wellKnown = lookupWellKnownRegex(pattern);\n if (wellKnown !== null) {\n ctx.usedHelpers.add(wellKnown);\n return wellKnown;\n }\n }\n const cacheKey = flags ? `${flags}\\u0000${pattern}` : pattern;\n const cached = ctx.regexCache.get(cacheKey);\n if (cached) return cached;\n const name = `__re_${prefix}_${ctx.counter++}`;\n const flagsArg = flags ? `,${escapeString(flags)}` : \"\";\n // Flag-less patterns may carry a faster behavior-equivalent rewrite (a\n // well-known table entry, repeat unrolling, or both); the regex OBJECT uses\n // it while issue sites keep reporting the original pattern (see slowString).\n const testSource = flags ? null : fastTestSource(pattern);\n ctx.preamble.push(`var ${name}=new RegExp(${escapeString(testSource ?? pattern)}${flagsArg});`);\n ctx.regexCache.set(cacheKey, name);\n return name;\n}\n\n/**\n * Resolve the ORIGINAL `/source/flags` pattern string of a regex for issue\n * reporting. Only needed when emitRegex swapped in a faster equivalent test\n * pattern (the runtime regex's toString() would leak the rewrite). Lean mode\n * references the shared `<name>Src` virtual export so the original pattern\n * stays a single bundle-wide string; inline mode declares it once per IIFE.\n */\nexport function emitRegexSourceString(ctx: CodeGenContext, pattern: string): string {\n if (ctx.mode === \"lean\") {\n const srcName = wellKnownRegexSourceName(pattern);\n if (srcName !== null) {\n ctx.usedHelpers.add(srcName);\n return srcName;\n }\n }\n const cacheKey = `src\\u0000${pattern}`;\n const cached = ctx.regexCache.get(cacheKey);\n if (cached) return cached;\n const name = `__res_${ctx.counter++}`;\n ctx.preamble.push(`var ${name}=${escapeString(`/${pattern}/`)};`);\n ctx.regexCache.set(cacheKey, name);\n return name;\n}\n\n/**\n * Declare a constant value in the preamble and return its variable name,\n * reusing an earlier declaration of the SAME initializer.\n *\n * Value tables are reached from both halves of a validator — an enum's `Set`\n * from its fast check and again from its slow walk, a strict shape's key table\n * likewise — and repeat across sibling properties that share a value list. One\n * declaration per USE emitted the payload two or four times: measured 17% of a\n * 20-value enum schema's generated bytes, 16% for an object with two identical\n * enums. Keyed by initializer text, so only identical payloads collapse.\n */\nexport function emitConstant(ctx: CodeGenContext, prefix: string, initializer: string): string {\n ctx.valueCache ??= new Map();\n const cached = ctx.valueCache.get(initializer);\n if (cached !== undefined) return cached;\n const name = `__${prefix}_${ctx.counter++}`;\n ctx.preamble.push(`var ${name}=${initializer};`);\n ctx.valueCache.set(initializer, name);\n return name;\n}\n\n/** Declare a `new Set([...])` in the preamble and return its variable name. */\nexport function emitSet(ctx: CodeGenContext, prefix: string, values: readonly unknown[]): string {\n return emitConstant(ctx, `set_${prefix}`, `new Set(${JSON.stringify([...values])})`);\n}\n\n/**\n * Shape-key count at or below which the unknown-key pass compares with an\n * inline `===` chain rather than a hashed lookup.\n *\n * This is deliberately NOT {@link ENUM_INLINE_THRESHOLD}: the two look alike but\n * are different workloads. An enum compares schema literals against arbitrary\n * INPUT strings, which may be long, share prefixes, and are not necessarily\n * internalized — so a hashed set earns its keep quickly. A shape-key test\n * compares them against keys arriving from `for-in`, i.e. the object's own\n * internalized key strings, so every arm of the chain is a pointer compare that\n * V8 predicts perfectly, while `table[k]` / `set.has(k)` pays a string hash and\n * probe per key.\n *\n * Measured over a strict object's for-in pass (JSON-parsed input, 8 rotated\n * shapes), `===` chain vs the previous `{k:1}` table: 3.7x at 6 keys, 3.8x at\n * 10, 3.1x at 20, 3.1x at 48 — the chain still leads at 64 (283 ns vs 690) and\n * only loses past ~96, where `Set.has` (not the table, which never wins at any\n * size) takes over. 64 sits below that crossover and above any realistic shape.\n */\nexport const KEY_MEMBERSHIP_INLINE_THRESHOLD = 64;\n\n/**\n * Boolean membership test for one key variable against a fixed key list.\n * Empty list recognizes nothing.\n *\n * `Set.has` is the large-shape fallback rather than a `{key:1}` object table:\n * the table is also `__proto__`-hostile (an own `__proto__` key cannot be set\n * by an object literal, so that key would silently read as unknown), which the\n * Set has no trouble with.\n */\nexport function keyMembershipTest(\n ctx: CodeGenContext,\n keys: readonly string[],\n keyVar: string,\n): string {\n if (keys.length === 0) return \"false\";\n if (keys.length <= KEY_MEMBERSHIP_INLINE_THRESHOLD) {\n return keys.map((k) => `${keyVar}===${escapeString(k)}`).join(\"||\");\n }\n return `${emitSet(ctx, \"ks\", keys)}.has(${keyVar})`;\n}\n\n/**\n * Enum values at or below this count use inline === checks instead of Set.has().\n * Measured on V8: for ≤5 values, an === chain beats Set.has by up to ~3x with\n * realistic (distinct-prefix, JSON-parsed) values — V8 internalizes strings on\n * successful comparison, making subsequent arms pointer-equality — and is no\n * worse than Set.has even with adversarial shared-prefix values.\n */\nexport const ENUM_INLINE_THRESHOLD = 5;\n\nconst CHECK_PRIORITY: Record<string, number> = {\n // Cheapest: length/size comparisons (O(1))\n min_length: 10,\n max_length: 11,\n length_equals: 12,\n min_size: 13,\n max_size: 14,\n // Number format checks (comparison + bitwise)\n number_format: 15,\n // Range comparisons\n greater_than: 20,\n less_than: 21,\n bigint_greater_than: 20,\n bigint_less_than: 21,\n date_greater_than: 22,\n date_less_than: 23,\n // Modulo\n multiple_of: 30,\n bigint_multiple_of: 30,\n // String prefix/suffix (O(prefix/suffix length))\n starts_with: 40,\n ends_with: 41,\n // String search (O(n·m) worst case)\n includes: 42,\n // Regex (most expensive)\n string_format: 50,\n};\n\nexport function escapeString(s: string | number): string {\n return JSON.stringify(s);\n}\n\n/**\n * JS source for a primitive literal value (literal schemas, discriminator\n * case labels). JSON.stringify covers string/number/boolean/null; bigint\n * needs the `n` suffix (JSON.stringify throws and String(5n) renders a\n * number literal that never strict-equals a bigint); undefined isn't JSON.\n */\nexport function literalToJs(v: string | number | boolean | null | bigint | undefined): string {\n if (typeof v === \"bigint\") return `${v}n`;\n if (v === undefined) return \"undefined\";\n // JSON.stringify maps NaN/±Infinity to \"null\"; emit them as JS expressions so a\n // non-finite numeric literal round-trips (z.literal(Infinity) must compare\n // against Infinity, not null). String(NaN)=\"NaN\", String(Infinity)=\"Infinity\",\n // String(-Infinity)=\"-Infinity\" — all valid JS that evaluate to the value.\n if (typeof v === \"number\" && !Number.isFinite(v)) return String(v);\n return JSON.stringify(v);\n}\n\n/**\n * Helpers that generated code invokes through `Function.prototype.call`, and\n * which therefore must be aliased into a module-local binding in lean mode.\n *\n * V8 folds a local `const` callee into a constant and inlines straight through\n * `x.call(...)`; an IMPORTED binding is a cell it will not fold, so the same\n * expression stays a generic property load plus a generic call — measured 4.5x\n * (5 keys) to 6.5x (20 keys) slower on the record fast path, 35.9 ns vs 7.2 ns\n * for a 5-key record. Aliasing the import into the IIFE recovers all of it\n * (7.4 ns). A DIRECT call to an imported function (`__zcFsr(v,s)`) is not\n * penalized — measured identical — and neither is an imported RegExp receiver,\n * so only the `.call` sites are listed here.\n */\nconst CALL_INVOKED_HELPERS: ReadonlySet<string> = new Set([\"__zcHop\"]);\n\n/**\n * Reference a shared runtime helper (e.g. __zcFsr) from generated code.\n * Lean mode: registers it for the `virtual:zod-compiler/runtime` import.\n * Inline mode: declares it once in the per-IIFE preamble.\n */\nexport function emitRuntimeHelper(ctx: CodeGenContext, name: string, decl: string): string {\n if (ctx.mode === \"lean\") {\n ctx.usedHelpers.add(name);\n if (CALL_INVOKED_HELPERS.has(name)) return emitConstant(ctx, \"lh\", name);\n } else if (!ctx.preamble.includes(decl)) {\n ctx.preamble.push(decl);\n }\n return name;\n}\n\n/**\n * Extend a path expression with one or more scalar segment expressions\n * (escaped string literals, numeric literals, or loop-variable names).\n *\n * Path expressions are only ever composed by these helpers starting from the\n * `[]` root, so any path that looks like an array literal IS one — the new\n * segment is spliced in to keep issue paths a single array allocation\n * (`[\"data\",\"items\",__i_7]`) instead of an allocation per nesting level\n * (`[\"data\"].concat(\"items\").concat(__i_7)`). Opaque expressions fall back\n * to .concat().\n */\nexport function extendPath(parentPath: string, segExpr: string): string {\n if (parentPath === \"[]\") return `[${segExpr}]`;\n if (parentPath.startsWith(\"[\") && parentPath.endsWith(\"]\")) {\n return `${parentPath.slice(0, -1)},${segExpr}]`;\n }\n return `${parentPath}.concat(${segExpr})`;\n}\n\n/** Extend a path expression with a static string key. */\nexport function extendStaticPath(parentPath: string, key: string): string {\n return extendPath(parentPath, escapeString(key));\n}\n\n/** Extend a path expression with a numeric index. */\nexport function extendStaticPathIndex(parentPath: string, index: number): string {\n return extendPath(parentPath, String(index));\n}\n\n/**\n * A superRefine callback receives zod's payload, whose `value` is public,\n * typed, writable API ($RefinementCtx extends ParsePayload) — so any node\n * carrying one MAY rewrite its value and must be treated as mutating. Which\n * callbacks actually do is undecidable here; the emitted fast check settles it\n * at runtime by refusing when the value changed (see ZC_SR_OK_DECL), so a\n * non-mutating callback still exits through the fast path.\n */\nfunction hasSuperRefine(checks: readonly { kind: string }[] | undefined): boolean {\n return checks !== undefined && checks.some((c) => c.kind === \"super_refine_effect\");\n}\n\n/**\n * Check if a SchemaIR tree produces output that is not the input itself —\n * either value-mutating operations (coerce, default, catch, overwrite) that\n * write back to the input expression, or a strip object that rebuilds a fresh\n * object from its known keys. Used by container generators to decide whether to\n * clone (so the rebuilt/mutated value never writes through to the caller's\n * input), by generateValidator to keep such schemas off the by-reference fast\n * path, and by the shared-walk dedup + intersection extractor to exclude them.\n */\nexport function hasMutation(ir: SchemaIR): boolean {\n switch (ir.type) {\n case \"string\":\n // url checks trim (and optionally normalize) the value; overwrite\n // effects (.trim(), .toLowerCase()) rewrite it.\n return (\n ir.coerce === true ||\n hasSuperRefine(ir.checks) ||\n ir.checks.some(\n (c) =>\n c.kind === \"overwrite_effect\" || (c.kind === \"string_format\" && c.format === \"url\"),\n )\n );\n case \"number\":\n return ir.coerce === true || hasSuperRefine(ir.checks);\n case \"boolean\":\n case \"bigint\":\n case \"date\":\n return ir.coerce === true;\n case \"default\":\n case \"catch\":\n case \"effect\":\n case \"fallback\":\n case \"stringBool\":\n return true;\n case \"object\":\n // A strip object produces a FRESH output (only the declared keys), so it\n // mutates: parents must clone before it writes back, it never takes the\n // by-reference fast path, and intersections of strip objects delegate to\n // zod (see extractIntersection's hasMutation guard) — matching zod's\n // parse-both-sides-then-merge semantics instead of over-stripping.\n return (\n ir.stripUnknownKeys === true ||\n hasSuperRefine(ir.checks) ||\n (ir.catchall !== undefined && hasMutation(ir.catchall)) ||\n Object.values(ir.properties).some((p) => hasMutation(p))\n );\n case \"array\":\n return hasSuperRefine(ir.checks) || hasMutation(ir.element);\n case \"tuple\":\n return ir.items.some(hasMutation) || (ir.rest !== null && hasMutation(ir.rest));\n case \"record\":\n return hasMutation(ir.valueType);\n case \"optional\":\n case \"nullable\":\n case \"readonly\":\n case \"recursionTarget\":\n return hasMutation(ir.inner);\n case \"union\":\n case \"discriminatedUnion\":\n return ir.options.some(hasMutation);\n case \"intersection\":\n return hasMutation(ir.left) || hasMutation(ir.right);\n case \"pipe\":\n return hasMutation(ir.in) || hasMutation(ir.out);\n case \"set\":\n return hasMutation(ir.valueType);\n case \"map\":\n return hasMutation(ir.keyType) || hasMutation(ir.valueType);\n case \"file\":\n return false;\n default:\n return false;\n }\n}\n\n/**\n * Is a defaulted property's key guaranteed to appear in the stripped output?\n *\n * Distinct from {@link rejectsUndefined}, which asks whether `undefined` is\n * REJECTED — a `.default()` accepts it and yet still produces a defined value, so\n * only this question earns the key a slot in the output object literal. The two\n * answers coincide everywhere else.\n *\n * Sound for both branches of a default: the substituted value is defined\n * (`alwaysDefined`, checked against the schema at extraction time), and the inner\n * branch runs only when `input[key] !== undefined`, which implies `key in input`\n * — so zod's presence test keeps the key whatever the inner produced.\n */\nexport function outputAlwaysDefined(ir: SchemaIR): boolean {\n return ir.type === \"default\" ? ir.alwaysDefined === true : rejectsUndefined(ir);\n}\n\n/**\n * Does this schema reject `undefined` outright?\n *\n * Read as \"can this slot be ABSENT from the input\" by the tuple build, whose\n * output length depends on it — zod marks a defaulted or optional item\n * `optin: \"optional\"` and accepts a shorter array. Conservative: anything that\n * might accept, produce, or default to `undefined` answers false.\n */\nexport function rejectsUndefined(ir: SchemaIR): boolean {\n switch (ir.type) {\n // Coercion turns undefined into a value (`String(undefined)`), so a\n // coercing primitive is NOT a rejector.\n case \"string\":\n case \"number\":\n case \"boolean\":\n case \"bigint\":\n case \"date\":\n return ir.coerce !== true;\n case \"symbol\":\n case \"null\":\n case \"nan\":\n case \"never\":\n case \"enum\":\n case \"object\":\n case \"array\":\n case \"tuple\":\n case \"record\":\n case \"set\":\n case \"map\":\n case \"file\":\n case \"templateLiteral\":\n case \"discriminatedUnion\":\n case \"stringBool\":\n return true;\n case \"literal\":\n return !ir.values.includes(undefined);\n case \"union\":\n return ir.options.every(rejectsUndefined);\n case \"intersection\":\n return rejectsUndefined(ir.left) || rejectsUndefined(ir.right);\n case \"nullable\":\n case \"readonly\":\n case \"recursionTarget\":\n return rejectsUndefined(ir.inner);\n default:\n // optional / any / unknown / undefined / void / default / catch /\n // fallback / effect / pipe / recursiveRef — each can yield undefined,\n // or is opaque enough that we must not assume otherwise.\n return false;\n }\n}\n\n/**\n * Sort comparator for CheckIR: cheapest/most-discriminating checks first.\n * Used by fast-path generators after filtering out refine_effect entries.\n */\nexport function checkPriority(\n a: CheckIR | BigIntCheckIR | DateCheckIR | SetCheckIR,\n b: CheckIR | BigIntCheckIR | DateCheckIR | SetCheckIR,\n): number {\n return (CHECK_PRIORITY[a.kind] ?? 99) - (CHECK_PRIORITY[b.kind] ?? 99);\n}\n"],"mappings":";;;AAgOA,SAAgB,iBAAiB,OAA0B;CACzD,OAAO,MAAM,MAAM,SAAS,IAAI,OAAO,MAAM,MAAM,KAAK,GAAG,EAAE,KAAK;AACpE;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,oBACd,GACA,SACA,UACA,QACe;CACf,IAAI,CAAC,iBAAiB,EAAE,KAAK,GAAG;EAC9B,MAAM,QAAQ,EAAE,MAAM,OAAO;EAC7B,OAAO,UAAU,OAAO,OAAO,IAAI,EAAE,QAAQ,WAAW,OAAO,GAAG,MAAM;CAC1E;CACA,MAAM,QAAQ,EAAE,MAAM,GAAG;CACzB,MAAM,QAAQ,EAAE,MAAM,SAAS,EAAE,OAAO,MAAM,CAAC;CAC/C,IAAI,UAAU,MAAM,OAAO;CAC3B,OAAO,KAAK,MAAM,GAAG,EAAE,MAAM,GAAG,WAAW,OAAO,GAAG,MAAM;AAC7D;;AAGA,SAAS,iBAAiB,MAAuB;CAC/C,OAAO,KAAK,SAAS,GAAG,KAAK,KAAK,SAAS,GAAG;AAChD;;AA8DA,SAAgB,SAAS,KAAqB,QAAwB;CACpE,OAAO,KAAK,OAAO,GAAG,IAAI;AAC5B;;;;;;;;;;;;;AAcA,SAAgB,aAAa,KAAqB,QAAwB;CACxE,IAAI,kCAAkB,IAAI,IAAI;CAC9B,MAAM,SAAS,IAAI,cAAc,IAAI,MAAM;CAC3C,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,MAAM,OAAO,QAAQ,IAAI;CACzB,IAAI,SAAS,KAAK,OAAO,KAAK,IAAI,OAAO,GAAG;CAC5C,IAAI,cAA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AO;CACX;AACF;;;;;;;;;;;;;;AAeA,SAAgB,oBAAoB,IAAuB;CACzD,OAAO,GAAG,SAAS,YAAY,GAAG,kBAAkB,OAAO,iBAAiB,EAAE;AAChF;;;;;;;;;AAUA,SAAgB,iBAAiB,IAAuB;CACtD,QAAQ,GAAG,MAAX;EAGE,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,QACH,OAAO,GAAG,WAAW;EACvB,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,cACH,OAAO;EACT,KAAK,WACH,OAAO,CAAC,GAAG,OAAO,SAAS,KAAA,CAAS;EACtC,KAAK,SACH,OAAO,GAAG,QAAQ,MAAM,gBAAgB;EAC1C,KAAK,gBACH,OAAO,iBAAiB,GAAG,IAAI,KAAK,iBAAiB,GAAG,KAAK;EAC/D,KAAK;EACL,KAAK;EACL,KAAK,mBACH,OAAO,iBAAiB,GAAG,KAAK;EAClC,SAIE,OAAO;CACX;AACF;;;;;AAMA,SAAgB,cACd,GACA,GACQ;CACR,QAAQ,eAAe,EAAE,SAAS,OAAO,eAAe,EAAE,SAAS;AACrE"}
|
|
1
|
+
{"version":3,"file":"context.js","names":[],"sources":["../../../src/core/codegen/context.ts"],"sourcesContent":["import type { BigIntCheckIR, CheckIR, DateCheckIR, SchemaIR, SetCheckIR } from \"../types.js\";\nimport type { SharedSchemaPlan } from \"./dedupe.js\";\nimport {\n fastTestSource,\n lookupWellKnownRegex,\n wellKnownRegexSourceName,\n} from \"./well-known-regex.js\";\n\n/** Codegen output mode. \"inline\" emits self-contained code (CLI .compiled.ts). \"lean\" emits references to imports from \"virtual:zod-compiler/runtime\" (unplugin). */\nexport type CodegenMode = \"inline\" | \"lean\";\n\nexport interface CodeGenResult {\n code: string;\n functionDef: string;\n /** Number of fallback schemas referenced by __rf[N] in the generated code. 0 = no fallbacks. */\n refCount: number;\n /**\n * Helper names referenced by this schema in lean mode (e.g. \"__zcTS\", \"__zcReEmail\").\n * Used by the unplugin transform to construct the `import { ... } from \"virtual:zod-compiler/runtime\"` line.\n * Always empty in inline mode.\n */\n usedHelpers: Set<string>;\n /**\n * Name of the hosted fast-check boolean function in the preamble (null when\n * the schema has no Fast Path). generateIIFE passes it to __zcMkv so parse()\n * and parseAsync() can return valid input without allocating an\n * intermediate SafeParseResult.\n */\n fastFnName: string | null;\n /**\n * True when `fastFnName` is a TOTAL predicate: `fc(input) === true` iff the\n * schema accepts `input` (mutation-free schemas, where a fast-check failure\n * can never become a slow-path success). generateIIFE installs it as the\n * zero-allocation `.is()` guard. False for partial fast paths\n * (default/catch — `fc` only shortcuts present-and-valid input, so a `false`\n * result does NOT imply rejection) and for schemas with no fast path, such as\n * coercion; `.is()` then derives from `safeParse(input).success`.\n */\n fastTotal: boolean;\n /**\n * Hosted predicate installed as `.is()`, when it differs from `fastFnName`.\n * A schema that rebuilds its output has no by-reference shortcut (so\n * `fastFnName` is null) yet still has an exact acceptance predicate, because\n * stripping reshapes the payload and never the verdict.\n */\n isFnName?: string | null;\n /**\n * Compact mode only: the `__rf[N]` index this validator delegates its cold\n * error path to (the schema itself, captured as a fresh root RefEntry). When\n * set, the pipeline appends a `{ schema, accessPath: \"\" }` entry at this index\n * so `generateIIFE` materializes `__rf[N]` as the original Zod schema. Absent\n * for every non-compact (fully compiled) validator.\n */\n rootDelegateRefIndex?: number;\n}\n\n/** Hosted-validator names for one recursion target (see CodeGenContext.recTargets). */\nexport interface RecTargetGen {\n /** True for the root target (refId 0) — reuses the schema's own functions. */\n isRoot: boolean;\n /**\n * safeParse-shaped slow validator name: `safeParse_<name>` for the root,\n * `__rsp_N` for a non-root target. `slowRecursiveRef` calls this.\n */\n slowName: string;\n /**\n * Boolean fast-check name (`__fcr_N`). Allocated lazily for the root (mirrors\n * recFastName), eagerly for non-root targets. Absent until the fast path\n * reaches a ref to this target.\n */\n fastName?: string;\n /** Inner IR hosted as the standalone validator body (non-root targets only). */\n inner?: SchemaIR;\n}\n\n/** Shared mutable state for code generation. Fast and slow paths share the same instance. */\nexport interface CodeGenContext {\n preamble: string[];\n counter: number;\n fnName: string;\n /** Deduplicates regex patterns: same pattern string → same preamble variable name. */\n regexCache: Map<string, string>;\n /** Codegen output mode. */\n mode: CodegenMode;\n /** Names of helpers from \"virtual:zod-compiler/runtime\" referenced in this schema (lean mode only). */\n usedHelpers: Set<string>;\n /**\n * Name of the fast-path boolean helper for the ROOT recursion target\n * (refId 0), allocated on first fastRecursiveRef visit. generateValidator\n * wraps the root fast expression as `function <name>(input){return <expr>;}`\n * so recursive refs can call it. undefined = root has no recursion on the\n * fast path.\n */\n recFastName?: string;\n /**\n * Hosted-validator name table for recursion targets, keyed by refId. Entry 0\n * is the root (the schema's own `safeParse_<name>` / `recFastName`); entries\n * ≥ 1 are non-root targets hosted as standalone `__rsp_N` (slow) / `__fcr_N`\n * (fast) helpers. `recursiveRef`/`recursionTarget` generators look up the\n * call target here. Undefined when not generating a full validator (e.g. unit\n * tests calling a single generator) — treated as root-only.\n */\n recTargets?: Map<number, RecTargetGen>;\n /** Dedup cache for hosted zero-capture effect functions: source text → preamble var. */\n effectFnCache?: Map<string, string>;\n /** Dedup cache for constant preamble declarations: initializer text → preamble var. */\n valueCache?: Map<string, string>;\n /** Name of the build path's FAIL sentinel, declared once per validator. */\n buildFailName?: string;\n /** Hosted build-function name per recursion target refId, so back-edges resolve. */\n buildRecNames?: Map<number, string>;\n /**\n * Set by the build path when it emitted a `.default()` substitution. Such a\n * schema ACCEPTS an input its fast expression rejects — `fastDefault` demands a\n * present value, since the fast path's contract is `data === input` and a\n * substituted default is not the input — so the expression is no longer an\n * exact acceptance predicate and must not be installed as `.is()`. Stripping,\n * by contrast, reshapes only the payload, which is why a build-path schema\n * otherwise still hands its predicate over.\n */\n buildSubstitutesValue?: boolean;\n /** Memo for estimateFastCost (size-gated fast-check extraction). Lazily created. */\n fastSizeCache?: WeakMap<SchemaIR, number>;\n /** Memo for estimateRuntimeCost (cheapest-first check ordering). Lazily created. */\n fastRuntimeCostCache?: WeakMap<SchemaIR, number>;\n /**\n * File-level shared slow-walk plan. Set only when generating a mutation-free\n * schema (so shared walks stay on the deferred cold path); the slow-path\n * visit() consults it to replace a repeated sub-IR with a `__zcSw_N` call.\n */\n sharedSchemas?: SharedSchemaPlan;\n}\n\n// ─── Slow Path context ────────────────────────────────────────────────────────\n\n/** Context object for slow-path (error-collecting) generator functions. */\nexport interface SlowGen {\n readonly input: string;\n readonly output: string;\n readonly path: string;\n readonly issues: string;\n readonly ctx: CodeGenContext;\n /**\n * Schema-level static error message of the node being generated\n * (z.string({ error: \"...\" })). Default message for issues this node emits\n * when the individual check has no message of its own. Set by generateSlow()\n * from ir.typeMessage; never inherited by child nodes.\n */\n readonly typeMsg?: string | undefined;\n\n /**\n * Name of a boolean variable that this node sets to `true` when it aborts in\n * the zod sense (`payload.aborted`) — currently only a pipe/codec whose `in`\n * step fails (zod's `handlePipeResult` sets `left.aborted = true`). A `union`\n * allocates one per option and reads it during pruning so a pipe option whose\n * `in` failed counts as aborted even when its only issue is a non-aborting\n * `custom`/check-level code. Undefined when the node is not inside an\n * abort-tracking option, in which case the abort is a no-op.\n *\n * Unlike input/output/path/issues, this is NOT inherited by `visit()`: it is\n * cleared at every boundary unless a node explicitly forwards it (the\n * pass-through wrappers optional/nullable/readonly do), mirroring how zod\n * propagates `payload.aborted` through transparent wrappers but not across\n * container boundaries.\n */\n readonly aborted?: string | undefined;\n\n /**\n * Recursively generate validation for a child IR node.\n * input/output/path/issues are inherited from parent unless overridden;\n * `aborted` is the exception — it is only set when explicitly passed (see the\n * `aborted` field doc), so it never leaks into container children.\n * Union generators use `{ issues }` to redirect child errors to temporary arrays.\n * Container generators use `{ input, output, path }` for element traversal.\n */\n visit(\n ir: SchemaIR,\n overrides?: {\n input?: string;\n output?: string;\n path?: string;\n issues?: string;\n // `| undefined` (unlike the others): pass-through wrappers forward\n // `g.aborted` verbatim, which is undefined outside an abort-tracking option.\n aborted?: string | undefined;\n },\n ): string;\n\n /** Generate a unique temp variable name: `__${prefix}_${counter++}` */\n temp(prefix: string): string;\n\n /** Add a regex to preamble and return the variable name. */\n regex(prefix: string, pattern: string, flags?: string): string;\n\n /** Add a Set to preamble and return the variable name. */\n set(prefix: string, values: readonly unknown[]): string;\n}\n\n/** Slow-path generator function signature — registered in slowRegistry. */\nexport type SlowGenerator<T extends SchemaIR = SchemaIR> = (ir: T, g: SlowGen) => string;\n\n// ─── Fast Path context ────────────────────────────────────────────────────────\n\n/**\n * Per-emitted-function size accumulator for size-gated fast-check extraction.\n * Shared by every node inlined into the same function; a fresh instance starts\n * each hosted helper (and the root). See fast-size.ts / generateFast.\n */\nexport interface FastScope {\n used: number;\n /**\n * `var` temps that the function this scope is assembling must declare, in\n * allocation order. Populated by {@link FastGen.local}; every site that\n * materializes a function body from a fresh scope emits\n * {@link declareFastTemps} at the top of that body.\n *\n * Function-scoped (never module-scoped) is load-bearing: a recursive\n * validator re-enters itself while an outer frame still holds a live temp,\n * and each invocation needs its own binding.\n */\n temps: string[];\n}\n\n/** `var a,b;` declaration for a scope's temps, or \"\" when it allocated none. */\nexport function declareFastTemps(scope: FastScope): string {\n return scope.temps.length > 0 ? `var ${scope.temps.join(\",\")};` : \"\";\n}\n\n/**\n * Fast check for a wrapper that compares its input against a sentinel and\n * otherwise delegates to an inner schema — `optional` (`===undefined`),\n * `nullable` (`===null`) and `default` (`!==undefined`).\n *\n * Written naively these read the input TWICE: once for the sentinel test and\n * again inside the inner check (which may itself read it several more times —\n * `typeof x===\"string\"&&x.length>=3&&x.length<=20`). V8's load elimination\n * removes the repeats only while the access is monomorphic; on the polymorphic\n * and megamorphic call sites real payloads produce (an array of objects with\n * differing key order, anything out of `JSON.parse`) every repeat is a fresh\n * megamorphic lookup. Binding the value to a local once is worth 1.1-1.7x on\n * the whole object check when the optional key is present, and is neutral when\n * it is absent.\n *\n * Only hoisted when the input is a property access; a bare local (an array\n * element variable, a record value) is already a single load, so it keeps the\n * shorter form and byte-identical output.\n */\nexport function fastSentinelWrapper(\n g: FastGen,\n innerIR: SchemaIR,\n sentinel: string,\n joiner: \"&&\" | \"||\",\n): string | null {\n if (!isPropertyAccess(g.input)) {\n const inner = g.visit(innerIR);\n return inner === null ? null : `(${g.input}${sentinel}${joiner}(${inner}))`;\n }\n const value = g.local(\"w\");\n const inner = g.visit(innerIR, { input: value });\n if (inner === null) return null;\n return `((${value}=${g.input})${sentinel}${joiner}(${inner}))`;\n}\n\n/** True for an expression that performs a property load (`x[\"a\"]`, `x.a`, `x[0][1]`). */\nfunction isPropertyAccess(expr: string): boolean {\n return expr.includes(\"[\") || expr.includes(\".\");\n}\n\n/** Context object for fast-path (boolean expression) generator functions. */\nexport interface FastGen {\n readonly input: string;\n readonly ctx: CodeGenContext;\n\n /**\n * Whether the CURRENT node may be hoisted into its own boolean helper when it\n * (with the already-emitted siblings) would overflow the function size cap.\n * False for the root and for a helper's own top node — those are already their\n * own function — but their children are extractable. See generateFast.\n */\n readonly extractable: boolean;\n\n /** Accumulated size (≈ chars) of the function currently being assembled. */\n readonly scope: FastScope;\n\n /**\n * Set on the gen for a discriminated-union option only: the discriminator\n * key. Signals `fastObject` to omit its type-guard and skip re-checking that\n * property (the switch already matched its value). Never propagated to child\n * nodes — nested objects keep their own guard.\n */\n readonly discSkipKey?: string | undefined;\n\n /**\n * Recursively generate fast-check expression for a child IR node.\n * Returns null if any child is ineligible for fast path.\n */\n visit(ir: SchemaIR, overrides?: { input?: string; discSkipKey?: string }): string | null;\n\n /**\n * A FastGen for emitting a SEPARATE function body (a hand-built preamble\n * helper such as a discriminated-union switch or an array-element loop). It\n * carries a FRESH size accumulator, so the helper's own content is size-gated\n * against the cap independently of the caller — without this, a helper's body\n * accrues to the caller's scope while the helper itself grows unbounded.\n */\n scoped(input: string): FastGen;\n\n /** Generate a unique temp variable name. */\n temp(prefix: string): string;\n\n /**\n * Allocate a unique name AND record it on this scope so the enclosing\n * emitted function declares it as a `var` (see {@link FastScope.temps}).\n * Use for a value bound inside an expression — `(t=x[\"k\"])===undefined` —\n * where `temp()` alone would leave the name undeclared.\n */\n local(prefix: string): string;\n\n /** Add a regex to preamble and return the variable name. */\n regex(prefix: string, pattern: string, flags?: string): string;\n}\n\n/** Fast-path generator function signature — registered in fastRegistry. */\nexport type FastGenerator<T extends SchemaIR = SchemaIR> = (ir: T, g: FastGen) => string | null;\n\n// ─── Shared emit helpers (used by both slow-path and fast-path factories) ────\n\n/** Allocate a fresh `__${prefix}_${n}` identifier and bump the shared counter. */\nexport function emitTemp(ctx: CodeGenContext, prefix: string): string {\n return `__${prefix}_${ctx.counter++}`;\n}\n\n/**\n * Host a zero-capture effect function (refine predicate, transform,\n * overwrite) in the preamble and return its variable name. The inline\n * `(${source})(x)` form evaluates the function expression — allocating a\n * function object — on EVERY parse at every effect site, including inside\n * the \"zero-allocation\" fast chain. V8's escape analysis erases that in\n * optimized frames, but interpreter/baseline/deopt frames pay it, and the\n * full source text re-parses as bytecode at each site. Zero-capture sources\n * reference only their own parameters and safe globals by construction, so\n * a single preamble binding is semantically identical. Deduped per schema\n * by source text.\n */\nexport function emitEffectFn(ctx: CodeGenContext, source: string): string {\n ctx.effectFnCache ??= new Map();\n const cached = ctx.effectFnCache.get(source);\n if (cached !== undefined) return cached;\n const name = `__ef_${ctx.counter++}`;\n ctx.preamble.push(`var ${name}=(${source});`);\n ctx.effectFnCache.set(source, name);\n return name;\n}\n\n/**\n * Callable expression for a user callback — a refine predicate or a transform.\n *\n * A zero-capture callback is hosted from its source text; one that CAPTURES\n * outer variables is called by reference through `__rf[N]` — the user's own\n * function object, reached from the schema — instead of costing the schema its\n * compiled path. The reference is aliased into a preamble binding rather than\n * re-read per call, for the same reason call-invoked helpers are (a per-call\n * array element load is not a foldable callee).\n */\nexport function emitEffectCallable(\n ctx: CodeGenContext,\n effect: { refIndex?: number | undefined; source?: string | undefined },\n): string {\n if (effect.refIndex !== undefined) return emitConstant(ctx, \"rfn\", `__rf[${effect.refIndex}]`);\n if (effect.source === undefined) {\n throw new Error(\"effect has neither inlineable source nor a reference index\");\n }\n return emitEffectFn(ctx, effect.source);\n}\n\n/**\n * Pristine fallback delegate: declare `var __rfp_N=__rf[N].safeParse.bind(__rf[N]);`\n * in the preamble and return the variable name. Generated code must NEVER read\n * `__rf[N].safeParse` at parse time: `__zcMkv` installs the compiled safeParse as\n * an OWN property on the original schema object, and whenever `__rf[N]` is that\n * same object the read resolves to the compiled delegate itself — infinite\n * recursion (RangeError on every parse). The fallback entry and the __zcMkv\n * target ARE the same object in compile mode (schemaExpr is the compile()\n * argument identifier) and the CLI emitter ((__src_X as any).schema); in\n * autoDiscover mode they are two textually identical constructions that any\n * downstream CSE/dedup transform (babel-plugin-zod-hoist in a field incident)\n * collapses back into one. Capturing at IIFE evaluation — before the trailing\n * `return __zcMkv(...)` mutates anything — pins zod's own implementation; the\n * worst case under cross-validator merges is delegating to an equivalent\n * compiled validator (whose own delegates were captured even earlier), never\n * a cycle.\n */\nexport function emitRfDelegate(ctx: CodeGenContext, refIndex: number): string {\n const name = `__rfp_${refIndex}`;\n const decl = `var ${name}=__rf[${refIndex}].safeParse.bind(__rf[${refIndex}]);`;\n if (!ctx.preamble.includes(decl)) {\n ctx.preamble.push(decl);\n }\n return name;\n}\n\n/**\n * Resolve a regex pattern to a runtime variable name.\n * Lean mode short-circuits well-known patterns to virtual-module names so the\n * bundler can dedup across files; everything else is cached + declared in the\n * per-IIFE preamble exactly once per pattern.\n */\nexport function emitRegex(\n ctx: CodeGenContext,\n prefix: string,\n pattern: string,\n flags?: string,\n): string {\n if (ctx.mode === \"lean\" && !flags) {\n const wellKnown = lookupWellKnownRegex(pattern);\n if (wellKnown !== null) {\n ctx.usedHelpers.add(wellKnown);\n return wellKnown;\n }\n }\n const cacheKey = flags ? `${flags}\\u0000${pattern}` : pattern;\n const cached = ctx.regexCache.get(cacheKey);\n if (cached) return cached;\n const name = `__re_${prefix}_${ctx.counter++}`;\n const flagsArg = flags ? `,${escapeString(flags)}` : \"\";\n // Flag-less patterns may carry a faster behavior-equivalent rewrite (a\n // well-known table entry, repeat unrolling, or both); the regex OBJECT uses\n // it while issue sites keep reporting the original pattern (see slowString).\n const testSource = flags ? null : fastTestSource(pattern);\n ctx.preamble.push(`var ${name}=new RegExp(${escapeString(testSource ?? pattern)}${flagsArg});`);\n ctx.regexCache.set(cacheKey, name);\n return name;\n}\n\n/**\n * Resolve the ORIGINAL `/source/flags` pattern string of a regex for issue\n * reporting. Only needed when emitRegex swapped in a faster equivalent test\n * pattern (the runtime regex's toString() would leak the rewrite). Lean mode\n * references the shared `<name>Src` virtual export so the original pattern\n * stays a single bundle-wide string; inline mode declares it once per IIFE.\n */\nexport function emitRegexSourceString(ctx: CodeGenContext, pattern: string): string {\n if (ctx.mode === \"lean\") {\n const srcName = wellKnownRegexSourceName(pattern);\n if (srcName !== null) {\n ctx.usedHelpers.add(srcName);\n return srcName;\n }\n }\n const cacheKey = `src\\u0000${pattern}`;\n const cached = ctx.regexCache.get(cacheKey);\n if (cached) return cached;\n const name = `__res_${ctx.counter++}`;\n ctx.preamble.push(`var ${name}=${escapeString(`/${pattern}/`)};`);\n ctx.regexCache.set(cacheKey, name);\n return name;\n}\n\n/**\n * Declare a constant value in the preamble and return its variable name,\n * reusing an earlier declaration of the SAME initializer.\n *\n * Value tables are reached from both halves of a validator — an enum's `Set`\n * from its fast check and again from its slow walk, a strict shape's key table\n * likewise — and repeat across sibling properties that share a value list. One\n * declaration per USE emitted the payload two or four times: measured 17% of a\n * 20-value enum schema's generated bytes, 16% for an object with two identical\n * enums. Keyed by initializer text, so only identical payloads collapse.\n */\nexport function emitConstant(ctx: CodeGenContext, prefix: string, initializer: string): string {\n ctx.valueCache ??= new Map();\n const cached = ctx.valueCache.get(initializer);\n if (cached !== undefined) return cached;\n const name = `__${prefix}_${ctx.counter++}`;\n ctx.preamble.push(`var ${name}=${initializer};`);\n ctx.valueCache.set(initializer, name);\n return name;\n}\n\n/** Declare a `new Set([...])` in the preamble and return its variable name. */\nexport function emitSet(ctx: CodeGenContext, prefix: string, values: readonly unknown[]): string {\n return emitConstant(ctx, `set_${prefix}`, `new Set(${JSON.stringify([...values])})`);\n}\n\n/**\n * Shape-key count at or below which the unknown-key pass compares with an\n * inline `===` chain rather than a hashed lookup.\n *\n * This is deliberately NOT {@link ENUM_INLINE_THRESHOLD}: the two look alike but\n * are different workloads. An enum compares schema literals against arbitrary\n * INPUT strings, which may be long, share prefixes, and are not necessarily\n * internalized — so a hashed set earns its keep quickly. A shape-key test\n * compares them against keys arriving from `for-in`, i.e. the object's own\n * internalized key strings, so every arm of the chain is a pointer compare that\n * V8 predicts perfectly, while `table[k]` / `set.has(k)` pays a string hash and\n * probe per key.\n *\n * Measured over a strict object's for-in pass (JSON-parsed input, 8 rotated\n * shapes), `===` chain vs the previous `{k:1}` table: 3.7x at 6 keys, 3.8x at\n * 10, 3.1x at 20, 3.1x at 48 — the chain still leads at 64 (283 ns vs 690) and\n * only loses past ~96, where `Set.has` (not the table, which never wins at any\n * size) takes over. 64 sits below that crossover and above any realistic shape.\n */\nexport const KEY_MEMBERSHIP_INLINE_THRESHOLD = 64;\n\n/**\n * Boolean membership test for one key variable against a fixed key list.\n * Empty list recognizes nothing.\n *\n * `Set.has` is the large-shape fallback rather than a `{key:1}` object table:\n * the table is also `__proto__`-hostile (an own `__proto__` key cannot be set\n * by an object literal, so that key would silently read as unknown), which the\n * Set has no trouble with.\n */\nexport function keyMembershipTest(\n ctx: CodeGenContext,\n keys: readonly string[],\n keyVar: string,\n): string {\n if (keys.length === 0) return \"false\";\n if (keys.length <= KEY_MEMBERSHIP_INLINE_THRESHOLD) {\n return keys.map((k) => `${keyVar}===${escapeString(k)}`).join(\"||\");\n }\n return `${emitSet(ctx, \"ks\", keys)}.has(${keyVar})`;\n}\n\n/**\n * Enum values at or below this count use inline === checks instead of Set.has().\n * Measured on V8: for ≤5 values, an === chain beats Set.has by up to ~3x with\n * realistic (distinct-prefix, JSON-parsed) values — V8 internalizes strings on\n * successful comparison, making subsequent arms pointer-equality — and is no\n * worse than Set.has even with adversarial shared-prefix values.\n */\nexport const ENUM_INLINE_THRESHOLD = 5;\n\nconst CHECK_PRIORITY: Record<string, number> = {\n // Cheapest: length/size comparisons (O(1))\n min_length: 10,\n max_length: 11,\n length_equals: 12,\n min_size: 13,\n max_size: 14,\n // Number format checks (comparison + bitwise)\n number_format: 15,\n // Range comparisons\n greater_than: 20,\n less_than: 21,\n bigint_greater_than: 20,\n bigint_less_than: 21,\n date_greater_than: 22,\n date_less_than: 23,\n // Modulo\n multiple_of: 30,\n bigint_multiple_of: 30,\n // String prefix/suffix (O(prefix/suffix length))\n starts_with: 40,\n ends_with: 41,\n // String search (O(n·m) worst case)\n includes: 42,\n // Regex (most expensive)\n string_format: 50,\n};\n\nexport function escapeString(s: string | number): string {\n return JSON.stringify(s);\n}\n\n/**\n * JS source for a primitive literal value (literal schemas, discriminator\n * case labels). JSON.stringify covers string/number/boolean/null; bigint\n * needs the `n` suffix (JSON.stringify throws and String(5n) renders a\n * number literal that never strict-equals a bigint); undefined isn't JSON.\n */\nexport function literalToJs(v: string | number | boolean | null | bigint | undefined): string {\n if (typeof v === \"bigint\") return `${v}n`;\n if (v === undefined) return \"undefined\";\n // JSON.stringify maps NaN/±Infinity to \"null\"; emit them as JS expressions so a\n // non-finite numeric literal round-trips (z.literal(Infinity) must compare\n // against Infinity, not null). String(NaN)=\"NaN\", String(Infinity)=\"Infinity\",\n // String(-Infinity)=\"-Infinity\" — all valid JS that evaluate to the value.\n if (typeof v === \"number\" && !Number.isFinite(v)) return String(v);\n return JSON.stringify(v);\n}\n\n/**\n * Helpers that generated code invokes through `Function.prototype.call`, and\n * which therefore must be aliased into a module-local binding in lean mode.\n *\n * V8 folds a local `const` callee into a constant and inlines straight through\n * `x.call(...)`; an IMPORTED binding is a cell it will not fold, so the same\n * expression stays a generic property load plus a generic call — measured 4.5x\n * (5 keys) to 6.5x (20 keys) slower on the record fast path, 35.9 ns vs 7.2 ns\n * for a 5-key record. Aliasing the import into the IIFE recovers all of it\n * (7.4 ns). A DIRECT call to an imported function (`__zcFsr(v,s)`) is not\n * penalized — measured identical — and neither is an imported RegExp receiver,\n * so only the `.call` sites are listed here.\n */\nconst CALL_INVOKED_HELPERS: ReadonlySet<string> = new Set([\"__zcHop\"]);\n\n/**\n * Reference a shared runtime helper (e.g. __zcFsr) from generated code.\n * Lean mode: registers it for the `virtual:zod-compiler/runtime` import.\n * Inline mode: declares it once in the per-IIFE preamble.\n */\nexport function emitRuntimeHelper(ctx: CodeGenContext, name: string, decl: string): string {\n if (ctx.mode === \"lean\") {\n ctx.usedHelpers.add(name);\n if (CALL_INVOKED_HELPERS.has(name)) return emitConstant(ctx, \"lh\", name);\n } else if (!ctx.preamble.includes(decl)) {\n ctx.preamble.push(decl);\n }\n return name;\n}\n\n/**\n * Extend a path expression with one or more scalar segment expressions\n * (escaped string literals, numeric literals, or loop-variable names).\n *\n * Path expressions are only ever composed by these helpers starting from the\n * `[]` root, so any path that looks like an array literal IS one — the new\n * segment is spliced in to keep issue paths a single array allocation\n * (`[\"data\",\"items\",__i_7]`) instead of an allocation per nesting level\n * (`[\"data\"].concat(\"items\").concat(__i_7)`). Opaque expressions fall back\n * to .concat().\n */\nexport function extendPath(parentPath: string, segExpr: string): string {\n if (parentPath === \"[]\") return `[${segExpr}]`;\n if (parentPath.startsWith(\"[\") && parentPath.endsWith(\"]\")) {\n return `${parentPath.slice(0, -1)},${segExpr}]`;\n }\n return `${parentPath}.concat(${segExpr})`;\n}\n\n/** Extend a path expression with a static string key. */\nexport function extendStaticPath(parentPath: string, key: string): string {\n return extendPath(parentPath, escapeString(key));\n}\n\n/** Extend a path expression with a numeric index. */\nexport function extendStaticPathIndex(parentPath: string, index: number): string {\n return extendPath(parentPath, String(index));\n}\n\n/**\n * A superRefine callback receives zod's payload, whose `value` is public,\n * typed, writable API ($RefinementCtx extends ParsePayload) — so any node\n * carrying one MAY rewrite its value and must be treated as mutating. Which\n * callbacks actually do is undecidable here; the emitted fast check settles it\n * at runtime by refusing when the value changed (see ZC_SR_OK_DECL), so a\n * non-mutating callback still exits through the fast path.\n */\nfunction hasSuperRefine(checks: readonly { kind: string }[] | undefined): boolean {\n return checks !== undefined && checks.some((c) => c.kind === \"super_refine_effect\");\n}\n\n/**\n * Check if a SchemaIR tree produces output that is not the input itself —\n * either value-mutating operations (coerce, default, catch, overwrite) that\n * write back to the input expression, or a strip object that rebuilds a fresh\n * object from its known keys. Used by container generators to decide whether to\n * clone (so the rebuilt/mutated value never writes through to the caller's\n * input), by generateValidator to keep such schemas off the by-reference fast\n * path, and by the shared-walk dedup + intersection extractor to exclude them.\n */\nexport function hasMutation(ir: SchemaIR): boolean {\n switch (ir.type) {\n case \"string\":\n // url checks trim (and optionally normalize) the value; overwrite\n // effects (.trim(), .toLowerCase()) rewrite it.\n return (\n ir.coerce === true ||\n hasSuperRefine(ir.checks) ||\n ir.checks.some(\n (c) =>\n c.kind === \"overwrite_effect\" || (c.kind === \"string_format\" && c.format === \"url\"),\n )\n );\n case \"number\":\n return ir.coerce === true || hasSuperRefine(ir.checks);\n case \"boolean\":\n case \"bigint\":\n case \"date\":\n return ir.coerce === true;\n case \"default\":\n case \"catch\":\n case \"effect\":\n case \"fallback\":\n case \"stringBool\":\n return true;\n case \"object\":\n // A strip object produces a FRESH output (only the declared keys), so it\n // mutates: parents must clone before it writes back, it never takes the\n // by-reference fast path, and intersections of strip objects delegate to\n // zod (see extractIntersection's hasMutation guard) — matching zod's\n // parse-both-sides-then-merge semantics instead of over-stripping.\n return (\n ir.stripUnknownKeys === true ||\n hasSuperRefine(ir.checks) ||\n (ir.catchall !== undefined && hasMutation(ir.catchall)) ||\n Object.values(ir.properties).some((p) => hasMutation(p))\n );\n case \"array\":\n return hasSuperRefine(ir.checks) || hasMutation(ir.element);\n case \"tuple\":\n return ir.items.some(hasMutation) || (ir.rest !== null && hasMutation(ir.rest));\n case \"record\":\n return hasMutation(ir.valueType);\n case \"optional\":\n case \"nullable\":\n case \"readonly\":\n case \"recursionTarget\":\n case \"zodDelegate\":\n return hasMutation(ir.inner);\n case \"union\":\n case \"discriminatedUnion\":\n return ir.options.some(hasMutation);\n case \"intersection\":\n return hasMutation(ir.left) || hasMutation(ir.right);\n case \"pipe\":\n return hasMutation(ir.in) || hasMutation(ir.out);\n case \"set\":\n return hasMutation(ir.valueType);\n case \"map\":\n return hasMutation(ir.keyType) || hasMutation(ir.valueType);\n case \"file\":\n return false;\n default:\n return false;\n }\n}\n\n/**\n * Is a defaulted property's key guaranteed to appear in the stripped output?\n *\n * Distinct from {@link rejectsUndefined}, which asks whether `undefined` is\n * REJECTED — a `.default()` accepts it and yet still produces a defined value, so\n * only this question earns the key a slot in the output object literal. The two\n * answers coincide everywhere else.\n *\n * Sound for both branches of a default: the substituted value is defined\n * (`alwaysDefined`, checked against the schema at extraction time), and the inner\n * branch runs only when `input[key] !== undefined`, which implies `key in input`\n * — so zod's presence test keeps the key whatever the inner produced.\n */\nexport function outputAlwaysDefined(ir: SchemaIR): boolean {\n return ir.type === \"default\" ? ir.alwaysDefined === true : rejectsUndefined(ir);\n}\n\n/**\n * Does this schema reject `undefined` outright?\n *\n * Read as \"can this slot be ABSENT from the input\" by the tuple build, whose\n * output length depends on it — zod marks a defaulted or optional item\n * `optin: \"optional\"` and accepts a shorter array. Conservative: anything that\n * might accept, produce, or default to `undefined` answers false.\n */\nexport function rejectsUndefined(ir: SchemaIR): boolean {\n switch (ir.type) {\n // Coercion turns undefined into a value (`String(undefined)`), so a\n // coercing primitive is NOT a rejector.\n case \"string\":\n case \"number\":\n case \"boolean\":\n case \"bigint\":\n case \"date\":\n return ir.coerce !== true;\n case \"symbol\":\n case \"null\":\n case \"nan\":\n case \"never\":\n case \"enum\":\n case \"object\":\n case \"array\":\n case \"tuple\":\n case \"record\":\n case \"set\":\n case \"map\":\n case \"file\":\n case \"templateLiteral\":\n case \"discriminatedUnion\":\n case \"stringBool\":\n return true;\n case \"literal\":\n return !ir.values.includes(undefined);\n case \"union\":\n return ir.options.every(rejectsUndefined);\n case \"intersection\":\n return rejectsUndefined(ir.left) || rejectsUndefined(ir.right);\n case \"nullable\":\n case \"readonly\":\n case \"recursionTarget\":\n case \"zodDelegate\":\n return rejectsUndefined(ir.inner);\n default:\n // optional / any / unknown / undefined / void / default / catch /\n // fallback / effect / pipe / recursiveRef — each can yield undefined,\n // or is opaque enough that we must not assume otherwise.\n return false;\n }\n}\n\n/**\n * Sort comparator for CheckIR: cheapest/most-discriminating checks first.\n * Used by fast-path generators after filtering out refine_effect entries.\n */\nexport function checkPriority(\n a: CheckIR | BigIntCheckIR | DateCheckIR | SetCheckIR,\n b: CheckIR | BigIntCheckIR | DateCheckIR | SetCheckIR,\n): number {\n return (CHECK_PRIORITY[a.kind] ?? 99) - (CHECK_PRIORITY[b.kind] ?? 99);\n}\n"],"mappings":";;;AAgOA,SAAgB,iBAAiB,OAA0B;CACzD,OAAO,MAAM,MAAM,SAAS,IAAI,OAAO,MAAM,MAAM,KAAK,GAAG,EAAE,KAAK;AACpE;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,oBACd,GACA,SACA,UACA,QACe;CACf,IAAI,CAAC,iBAAiB,EAAE,KAAK,GAAG;EAC9B,MAAM,QAAQ,EAAE,MAAM,OAAO;EAC7B,OAAO,UAAU,OAAO,OAAO,IAAI,EAAE,QAAQ,WAAW,OAAO,GAAG,MAAM;CAC1E;CACA,MAAM,QAAQ,EAAE,MAAM,GAAG;CACzB,MAAM,QAAQ,EAAE,MAAM,SAAS,EAAE,OAAO,MAAM,CAAC;CAC/C,IAAI,UAAU,MAAM,OAAO;CAC3B,OAAO,KAAK,MAAM,GAAG,EAAE,MAAM,GAAG,WAAW,OAAO,GAAG,MAAM;AAC7D;;AAGA,SAAS,iBAAiB,MAAuB;CAC/C,OAAO,KAAK,SAAS,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,8 @@ function referencesExportRefs(ir) {
|
|
|
77
77
|
case "default":
|
|
78
78
|
case "catch":
|
|
79
79
|
case "fallback": return true;
|
|
80
|
+
case "custom": return true;
|
|
81
|
+
case "zodDelegate": return true;
|
|
80
82
|
case "effect":
|
|
81
83
|
if (ir.refIndex !== void 0) return true;
|
|
82
84
|
break;
|
|
@@ -120,7 +122,8 @@ function childSchemas(ir) {
|
|
|
120
122
|
case "catch": return [ir.inner];
|
|
121
123
|
case "pipe": return [ir.in, ir.out];
|
|
122
124
|
case "effect":
|
|
123
|
-
case "recursionTarget":
|
|
125
|
+
case "recursionTarget":
|
|
126
|
+
case "zodDelegate": return [ir.inner];
|
|
124
127
|
default: return [];
|
|
125
128
|
}
|
|
126
129
|
}
|