zod-compiler 2.0.3 → 2.0.4
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/dist/core/codegen/context.d.ts +2 -0
- package/dist/core/codegen/context.d.ts.map +1 -1
- package/dist/core/codegen/context.js.map +1 -1
- package/dist/core/codegen/index.js +1 -0
- package/dist/core/codegen/index.js.map +1 -1
- package/dist/core/codegen/schemas/recursive-ref.d.ts.map +1 -1
- package/dist/core/codegen/schemas/recursive-ref.js +1 -0
- package/dist/core/codegen/schemas/recursive-ref.js.map +1 -1
- package/package.json +1 -1
|
@@ -108,6 +108,8 @@ interface CodeGenContext {
|
|
|
108
108
|
* fast path.
|
|
109
109
|
*/
|
|
110
110
|
recFastName?: string;
|
|
111
|
+
/** The root fast pass aborted, so its recursive helper names have no declarations. */
|
|
112
|
+
fastRecursionDisabled?: boolean;
|
|
111
113
|
/**
|
|
112
114
|
* Hosted-validator name table for recursion targets, keyed by refId. Entry 0
|
|
113
115
|
* is the root (the schema's own `safeParse_<name>` / `recFastName`); entries
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.d.ts","names":[],"sources":["../../../src/core/codegen/context.ts"],"mappings":";;;;KAgBY;;;;;KAMA;;;;;;;;;;;;;;;;UAiBK;WACN,MAAM;WACN;WACA;;UAGM;EACf;EACA;;EAEA;;;;;;EAMA,aAAa;;;;;;;EAOb;;;;;;;;;;EAUA;;;;;;;EAOA;;;;;;;EAOA;;;UAIe;;EAEf;;;;;EAKA;;;;;;EAMA;;EAEA,QAAQ;;;UAIO;EACf;EACA;EACA;;EAEA,YAAY;;EAEZ,MAAM;;EAEN,aAAa;;;;;;;;EAQb;;;;;;;;;EASA,aAAa,YAAY;;EAEzB,gBAAgB;;EAEhB,aAAa;;EAEb,eAAe,UAAU;;EAEzB,sBAAsB;;EAEtB;;EAEA,gBAAgB;;EAEhB,gBAAgB,QAAQ;;EAExB,uBAAuB,QAAQ;;;;;;EAM/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BAAkB,KAAK,gBAAgB,cAAc;;;;;;;;;;;;iBAqBrD,WAAW,oBAAoB;;iBAS/B,iBAAiB,oBAAoB;;iBAKrC,sBAAsB,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA0C1C,wBAAwB,IAAI;EAAa;;;;;;;;;;;iBAmBzC,gBAAgB,IAAI;iBAepB,YAAY,IAAI;;;;;;;;;;;;;;iBAuFhB,oBAAoB,IAAI;;;;;;;;;;iBAaxB,iBAAiB,IAAI;;;;;iBAiDrB,cACd,GAAG,UAAU,gBAAgB,cAAc,YAC3C,GAAG,UAAU,gBAAgB,cAAc"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","names":[],"sources":["../../../src/core/codegen/context.ts"],"sourcesContent":["import type {\n BigIntCheckIR,\n CheckIR,\n DateCheckIR,\n LiteralValue,\n SchemaIR,\n SetCheckIR,\n} 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\n/**\n * Kind of a poolable constant. Decides the shared identifier's prefix, so a\n * module-scope pool stays readable (`__zcSet_0`, …) rather than opaque.\n */\nexport type ConstantKind = \"Bf\" | \"Rx\" | \"Set\";\n\n/**\n * A poolable constant declaration emitted while generating one validator.\n *\n * Reported to the file pipeline, which pools initializers used by two or more\n * validators into a single module-scope declaration. Only value constants\n * qualify: they are allocated once at module init and read identically from\n * anywhere, so hoisting one out of a validator changes neither its identity nor\n * the hot path.\n *\n * Generated FAST-PATH functions are deliberately not poolable, even when two\n * validators emit byte-identical ones: sharing a function merges its call sites\n * onto a single feedback vector, which is exactly the polymorphism the fast\n * path is inlined to avoid. Cold slow walks are a different bargain and are\n * shared — by their own mechanism, `__zcSw_N` (see dedupe.ts).\n */\nexport interface GeneratedConstant {\n readonly kind: ConstantKind;\n readonly name: string;\n readonly initializer: string;\n}\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: this validator reads {@link RETAINED_SCHEMA_VAR}\n * directly, so `generateIIFE` must bind it even when the schema has no\n * fallback refs of its own. Absent for every non-compact (fully compiled)\n * validator.\n */\n usesRetainedSchema?: boolean;\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 /** Reports poolable constants so the file pipeline can share exact duplicates across validators. */\n onConstant?: ((constant: GeneratedConstant) => void) | undefined;\n /** Exact initializer → file-level name, populated by the pipeline's second codegen pass. */\n sharedConstantNames?: ReadonlyMap<string, string> | undefined;\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 /** 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 * Generate an ACCEPTANCE predicate rather than a by-reference one. The two\n * differ at exactly one node: `.default()`. The by-reference form demands a\n * present value, because its contract is `data === input` and a substituted\n * default is not the input; the acceptance form accepts `undefined`, because\n * the schema does. Set by generateValidator for a schema that rebuilds its\n * output — there the expression can never stand in for the payload and is\n * only ever read as a verdict, by `.is()` — and inherited by every child and\n * hosted helper, so a default anywhere in the tree is treated the same way.\n */\n readonly acceptance?: boolean | 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 * A retained schema's `_zod` internals, aliased into the preamble for the\n * sub-schema delegate that runs it through `_zod.run` (see\n * ZC_RUN_DELEGATE_DECL). Bound once per IIFE like `__rfp_N`, so the per-parse\n * call is a property load on a constant rather than an `__rf[N]` element read.\n * Unlike `safeParse`, `_zod` is never replaced by `__zcMkv`, so here the alias\n * is a cost saving, not a cycle guard.\n */\nexport function emitRfZod(ctx: CodeGenContext, refIndex: number): string {\n const name = `__rfz_${refIndex}`;\n const decl = `var ${name}=__rf[${refIndex}]._zod;`;\n if (!ctx.preamble.includes(decl)) {\n ctx.preamble.push(decl);\n }\n return name;\n}\n\n/**\n * Identifier `generateIIFE` binds the retained Zod schema to, once per export.\n *\n * Compact delegation reaches the schema through this binding rather than\n * through `__rf[]`. Routing it through the array meant every compact validator\n * — the common case being one with no fallback refs at all — declared a\n * one-element `var __rf=[__zs];` whose only reads were `__rf[0]`, i.e. an array\n * allocation per compiled schema at module init to alias a binding that was\n * already in scope. Naming the schema directly also keeps the reference a\n * foldable constant instead of an element load (the same reason\n * {@link emitEffectCallable} aliases its `__rf[N]` into a preamble binding).\n */\nexport const RETAINED_SCHEMA_VAR = \"__zs\";\n\n/**\n * Capture the retained schema's pristine `safeParse` without allocating a bound\n * function. Declared in the preamble, which `generateIIFE` places after the\n * `__zs` binding and before the trailing `__zcMkv` call — so the capture is\n * zod's own implementation, never the compiled delegate that call installs\n * (see {@link emitRfDelegate} for the recursion this avoids).\n */\nexport function emitRetainedMethod(ctx: CodeGenContext): string {\n const name = \"__rfm_z\";\n const decl = `var ${name}=${RETAINED_SCHEMA_VAR}.safeParse;`;\n if (!ctx.preamble.includes(decl)) {\n ctx.preamble.push(decl);\n }\n return name;\n}\n\n/**\n * Is a RegExp built with these flags safe to share between validators?\n *\n * `g` and `y` make the object STATEFUL: `.test()` advances `lastIndex` and the\n * next call resumes from there. Generated code is already correct about this —\n * every flagged site emits a `lastIndex=0` reset first (see `lastIndexReset` in\n * schemas/string.ts, the only generator that passes flags through) — so pooling\n * them would in fact work today.\n *\n * They are held back anyway, because the pool changes what a future lapse\n * costs. A missing reset on a validator-local regex misbehaves inside one\n * export, deterministically. On a pooled one it misbehaves across exports, and\n * only in the order the module happens to evaluate them. Flagged patterns are\n * rare enough that the sharing is not worth buying that failure mode. Every\n * other flag (`i`, `m`, `s`, `u`, `v`, `d`) is pure configuration and pools like\n * any other constant.\n */\nfunction isPoolableRegex(flags: string | undefined): boolean {\n return flags === undefined || !/[gy]/.test(flags);\n}\n\n/**\n * Resolve a regex pattern to a runtime variable name.\n *\n * Three layers, widest first. Lean mode short-circuits well-known patterns to\n * virtual-module names, deduping them across the whole bundle. What is left is\n * pooled at FILE level when two or more validators build the identical RegExp —\n * the same bargain Sets get, and a larger one in practice: a repeated enum is\n * one `new Set([...])`, while a repeated `z.iso.datetime()` or shared\n * `.regex()` is a several-hundred-byte pattern plus a RegExp construction per\n * validator at module init. Anything still unique is cached and 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 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 const initializer = `new RegExp(${escapeString(testSource ?? pattern)}${flagsArg})`;\n const localPrefix = `re_${prefix}`;\n const name = isPoolableRegex(flags)\n ? emitPooledConstant(ctx, \"Rx\", localPrefix, initializer)\n : emitConstant(ctx, localPrefix, initializer);\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/**\n * Declare a poolable constant in the preamble and return its variable name —\n * unless the file pipeline has already decided to hoist this exact initializer\n * to module scope, in which case the shared name is returned and nothing is\n * declared locally.\n *\n * The pipeline learns which initializers repeat by running codegen once and\n * collecting what was reported here, so every poolable constant must route\n * through this function rather than calling {@link emitConstant} directly.\n */\nexport function emitPooledConstant(\n ctx: CodeGenContext,\n kind: ConstantKind,\n localPrefix: string,\n initializer: string,\n): string {\n const sharedName = ctx.sharedConstantNames?.get(initializer);\n if (sharedName !== undefined) return sharedName;\n const name = emitConstant(ctx, localPrefix, initializer);\n ctx.onConstant?.({ kind, name, initializer });\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 const initializer = `new Set(${JSON.stringify([...values])})`;\n return emitPooledConstant(ctx, \"Set\", `set_${prefix}`, initializer);\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/** The {@link LiteralValue}s that {@link literalToJs} can spell. */\nexport type SourceFormLiteral = string | number | boolean | null | bigint | undefined;\n\n/**\n * Can {@link literalToJs} render this value as JS source that strict-equals it?\n *\n * Total by construction — it NAMES the value kinds that have a source form\n * rather than excluding the ones that don't, so every reference value falls out\n * on the false side. That matters because `literalToJs` used to end in a bare\n * `JSON.stringify`, which does not fail loudly on the values it cannot spell:\n * for a symbol it RETURNS `undefined` (the value, not a string), so\n * `z.literal(sym)` compiled to the comparison `x===undefined` — rejecting the\n * symbol it was built from and accepting `undefined`. An object is mis-rendered\n * the other way: `{}` stringifies to `\"{}\"`, and `x==={}` is never true, so the\n * very object the schema was built from was rejected. Both take the runtime\n * membership path instead (see the literal generator).\n */\nexport function hasSourceForm(v: LiteralValue): v is SourceFormLiteral {\n if (v === null) return true;\n const t = typeof v;\n return t === \"string\" || t === \"number\" || t === \"boolean\" || t === \"bigint\" || t === \"undefined\";\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 *\n * The parameter type is deliberately NARROWER than {@link LiteralValue}: every\n * caller must first prove its value is spellable with {@link hasSourceForm}.\n */\nexport function literalToJs(v: SourceFormLiteral): 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 */\n/**\n * Can this tuple's output differ from a SHORT input it accepts?\n *\n * $ZodTuple runs every item even when the input is shorter, and\n * `handleTupleResults` writes each result back (`final.value[i] = r.value`)\n * unless the slot is at or past `optoutStart` and on the \"optional\" rung of\n * `optin` — that one ends the output where the input ended. Every other absent\n * slot lands in the output: below `optoutStart` as whatever the item made of\n * `undefined` (an own `undefined` for `z.string().optional()`, \"c\" for\n * `.catch(\"c\")`), at or past it as a substituted value (a \"defaulted\" item).\n * `z.tuple([z.string(), z.number().default(1)])` therefore answers `[\"x\"]` with\n * `[\"x\", 1]`, length 2, and `z.tuple([z.any()]).rest(z.number())` answers `[]`\n * with `[undefined]`. So the tuple is a mutating node — its output is not its\n * input — exactly when some slot that CAN be absent is not a truncating one.\n * Without a rest element only slots from `optStart` on can be absent (a shorter\n * input is `too_small`); with one, any slot can.\n */\nexport function tupleRewritesShortInput(ir: SchemaIR & { type: \"tuple\" }): boolean {\n const len = ir.items.length;\n const optoutStart = ir.optoutStart ?? len;\n const optionalIn = ir.optionalIn ?? [];\n for (let i = ir.rest === null ? ir.optStart : 0; i < len; i++) {\n if (i < optoutStart || !optionalIn.includes(i)) return true;\n }\n return false;\n}\n\n/**\n * Does this node hand back a container that could still carry an own\n * `__proto__` zod would have stripped?\n *\n * True for the shapes whose output IS their input: a LOOSE or CATCHALL object\n * (a stripping one rebuilds from the declared keys, and `parsedProperties`\n * already drops the key) and any record. See {@link ZC_PROTO_SCRUB_DECL} for\n * what zod does and why the difference matters.\n */\nexport function needsProtoScrub(ir: SchemaIR): boolean {\n // Every record: the walk skips `__proto__` but the container is handed back.\n if (ir.type === \"record\") return true;\n if (ir.type !== \"object\") return false;\n // A STRIPPING object rebuilds from the declared keys and `parsedProperties`\n // drops `__proto__`, so its output can never carry one.\n if (ir.stripUnknownKeys === true) return false;\n // A STRICT object reports an undeclared `__proto__` as an unrecognized key\n // and fails, so the only way one reaches its output is by being DECLARED —\n // which zod's shape loop strips while still counting the name as recognized.\n if (ir.strict === true) return Object.hasOwn(ir.properties, \"__proto__\");\n // Loose or catchall: an undeclared `__proto__` rides through untouched.\n return true;\n}\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 (\n ir.items.some(hasMutation) ||\n (ir.rest !== null && hasMutation(ir.rest)) ||\n tupleRewritesShortInput(ir)\n );\n case \"record\":\n return hasMutation(ir.valueType);\n // A freezing readonly produces a value that is not its input, exactly as a\n // strip object does — so it must never take a by-reference shortcut.\n case \"readonly\":\n return ir.freeze === true || hasMutation(ir.inner);\n case \"optional\":\n case \"nullable\":\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 \"does an absent key already fail on its own\" by the object extractor,\n * which otherwise has to report the absence itself (zod's `nonoptional`\n * issue), and as \"is a fixed-length rebuild exact\" by the tuple build.\n * Conservative: anything that might accept, produce, or default to `undefined`\n * 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":";;;AA2PA,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;;AA0EA,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,G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AAe,EAAE,SAAS;AACrE"}
|
|
1
|
+
{"version":3,"file":"context.js","names":[],"sources":["../../../src/core/codegen/context.ts"],"sourcesContent":["import type {\n BigIntCheckIR,\n CheckIR,\n DateCheckIR,\n LiteralValue,\n SchemaIR,\n SetCheckIR,\n} 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\n/**\n * Kind of a poolable constant. Decides the shared identifier's prefix, so a\n * module-scope pool stays readable (`__zcSet_0`, …) rather than opaque.\n */\nexport type ConstantKind = \"Bf\" | \"Rx\" | \"Set\";\n\n/**\n * A poolable constant declaration emitted while generating one validator.\n *\n * Reported to the file pipeline, which pools initializers used by two or more\n * validators into a single module-scope declaration. Only value constants\n * qualify: they are allocated once at module init and read identically from\n * anywhere, so hoisting one out of a validator changes neither its identity nor\n * the hot path.\n *\n * Generated FAST-PATH functions are deliberately not poolable, even when two\n * validators emit byte-identical ones: sharing a function merges its call sites\n * onto a single feedback vector, which is exactly the polymorphism the fast\n * path is inlined to avoid. Cold slow walks are a different bargain and are\n * shared — by their own mechanism, `__zcSw_N` (see dedupe.ts).\n */\nexport interface GeneratedConstant {\n readonly kind: ConstantKind;\n readonly name: string;\n readonly initializer: string;\n}\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: this validator reads {@link RETAINED_SCHEMA_VAR}\n * directly, so `generateIIFE` must bind it even when the schema has no\n * fallback refs of its own. Absent for every non-compact (fully compiled)\n * validator.\n */\n usesRetainedSchema?: boolean;\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 /** The root fast pass aborted, so its recursive helper names have no declarations. */\n fastRecursionDisabled?: boolean;\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 /** Reports poolable constants so the file pipeline can share exact duplicates across validators. */\n onConstant?: ((constant: GeneratedConstant) => void) | undefined;\n /** Exact initializer → file-level name, populated by the pipeline's second codegen pass. */\n sharedConstantNames?: ReadonlyMap<string, string> | undefined;\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 /** 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 * Generate an ACCEPTANCE predicate rather than a by-reference one. The two\n * differ at exactly one node: `.default()`. The by-reference form demands a\n * present value, because its contract is `data === input` and a substituted\n * default is not the input; the acceptance form accepts `undefined`, because\n * the schema does. Set by generateValidator for a schema that rebuilds its\n * output — there the expression can never stand in for the payload and is\n * only ever read as a verdict, by `.is()` — and inherited by every child and\n * hosted helper, so a default anywhere in the tree is treated the same way.\n */\n readonly acceptance?: boolean | 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 * A retained schema's `_zod` internals, aliased into the preamble for the\n * sub-schema delegate that runs it through `_zod.run` (see\n * ZC_RUN_DELEGATE_DECL). Bound once per IIFE like `__rfp_N`, so the per-parse\n * call is a property load on a constant rather than an `__rf[N]` element read.\n * Unlike `safeParse`, `_zod` is never replaced by `__zcMkv`, so here the alias\n * is a cost saving, not a cycle guard.\n */\nexport function emitRfZod(ctx: CodeGenContext, refIndex: number): string {\n const name = `__rfz_${refIndex}`;\n const decl = `var ${name}=__rf[${refIndex}]._zod;`;\n if (!ctx.preamble.includes(decl)) {\n ctx.preamble.push(decl);\n }\n return name;\n}\n\n/**\n * Identifier `generateIIFE` binds the retained Zod schema to, once per export.\n *\n * Compact delegation reaches the schema through this binding rather than\n * through `__rf[]`. Routing it through the array meant every compact validator\n * — the common case being one with no fallback refs at all — declared a\n * one-element `var __rf=[__zs];` whose only reads were `__rf[0]`, i.e. an array\n * allocation per compiled schema at module init to alias a binding that was\n * already in scope. Naming the schema directly also keeps the reference a\n * foldable constant instead of an element load (the same reason\n * {@link emitEffectCallable} aliases its `__rf[N]` into a preamble binding).\n */\nexport const RETAINED_SCHEMA_VAR = \"__zs\";\n\n/**\n * Capture the retained schema's pristine `safeParse` without allocating a bound\n * function. Declared in the preamble, which `generateIIFE` places after the\n * `__zs` binding and before the trailing `__zcMkv` call — so the capture is\n * zod's own implementation, never the compiled delegate that call installs\n * (see {@link emitRfDelegate} for the recursion this avoids).\n */\nexport function emitRetainedMethod(ctx: CodeGenContext): string {\n const name = \"__rfm_z\";\n const decl = `var ${name}=${RETAINED_SCHEMA_VAR}.safeParse;`;\n if (!ctx.preamble.includes(decl)) {\n ctx.preamble.push(decl);\n }\n return name;\n}\n\n/**\n * Is a RegExp built with these flags safe to share between validators?\n *\n * `g` and `y` make the object STATEFUL: `.test()` advances `lastIndex` and the\n * next call resumes from there. Generated code is already correct about this —\n * every flagged site emits a `lastIndex=0` reset first (see `lastIndexReset` in\n * schemas/string.ts, the only generator that passes flags through) — so pooling\n * them would in fact work today.\n *\n * They are held back anyway, because the pool changes what a future lapse\n * costs. A missing reset on a validator-local regex misbehaves inside one\n * export, deterministically. On a pooled one it misbehaves across exports, and\n * only in the order the module happens to evaluate them. Flagged patterns are\n * rare enough that the sharing is not worth buying that failure mode. Every\n * other flag (`i`, `m`, `s`, `u`, `v`, `d`) is pure configuration and pools like\n * any other constant.\n */\nfunction isPoolableRegex(flags: string | undefined): boolean {\n return flags === undefined || !/[gy]/.test(flags);\n}\n\n/**\n * Resolve a regex pattern to a runtime variable name.\n *\n * Three layers, widest first. Lean mode short-circuits well-known patterns to\n * virtual-module names, deduping them across the whole bundle. What is left is\n * pooled at FILE level when two or more validators build the identical RegExp —\n * the same bargain Sets get, and a larger one in practice: a repeated enum is\n * one `new Set([...])`, while a repeated `z.iso.datetime()` or shared\n * `.regex()` is a several-hundred-byte pattern plus a RegExp construction per\n * validator at module init. Anything still unique is cached and 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 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 const initializer = `new RegExp(${escapeString(testSource ?? pattern)}${flagsArg})`;\n const localPrefix = `re_${prefix}`;\n const name = isPoolableRegex(flags)\n ? emitPooledConstant(ctx, \"Rx\", localPrefix, initializer)\n : emitConstant(ctx, localPrefix, initializer);\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/**\n * Declare a poolable constant in the preamble and return its variable name —\n * unless the file pipeline has already decided to hoist this exact initializer\n * to module scope, in which case the shared name is returned and nothing is\n * declared locally.\n *\n * The pipeline learns which initializers repeat by running codegen once and\n * collecting what was reported here, so every poolable constant must route\n * through this function rather than calling {@link emitConstant} directly.\n */\nexport function emitPooledConstant(\n ctx: CodeGenContext,\n kind: ConstantKind,\n localPrefix: string,\n initializer: string,\n): string {\n const sharedName = ctx.sharedConstantNames?.get(initializer);\n if (sharedName !== undefined) return sharedName;\n const name = emitConstant(ctx, localPrefix, initializer);\n ctx.onConstant?.({ kind, name, initializer });\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 const initializer = `new Set(${JSON.stringify([...values])})`;\n return emitPooledConstant(ctx, \"Set\", `set_${prefix}`, initializer);\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/** The {@link LiteralValue}s that {@link literalToJs} can spell. */\nexport type SourceFormLiteral = string | number | boolean | null | bigint | undefined;\n\n/**\n * Can {@link literalToJs} render this value as JS source that strict-equals it?\n *\n * Total by construction — it NAMES the value kinds that have a source form\n * rather than excluding the ones that don't, so every reference value falls out\n * on the false side. That matters because `literalToJs` used to end in a bare\n * `JSON.stringify`, which does not fail loudly on the values it cannot spell:\n * for a symbol it RETURNS `undefined` (the value, not a string), so\n * `z.literal(sym)` compiled to the comparison `x===undefined` — rejecting the\n * symbol it was built from and accepting `undefined`. An object is mis-rendered\n * the other way: `{}` stringifies to `\"{}\"`, and `x==={}` is never true, so the\n * very object the schema was built from was rejected. Both take the runtime\n * membership path instead (see the literal generator).\n */\nexport function hasSourceForm(v: LiteralValue): v is SourceFormLiteral {\n if (v === null) return true;\n const t = typeof v;\n return t === \"string\" || t === \"number\" || t === \"boolean\" || t === \"bigint\" || t === \"undefined\";\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 *\n * The parameter type is deliberately NARROWER than {@link LiteralValue}: every\n * caller must first prove its value is spellable with {@link hasSourceForm}.\n */\nexport function literalToJs(v: SourceFormLiteral): 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 */\n/**\n * Can this tuple's output differ from a SHORT input it accepts?\n *\n * $ZodTuple runs every item even when the input is shorter, and\n * `handleTupleResults` writes each result back (`final.value[i] = r.value`)\n * unless the slot is at or past `optoutStart` and on the \"optional\" rung of\n * `optin` — that one ends the output where the input ended. Every other absent\n * slot lands in the output: below `optoutStart` as whatever the item made of\n * `undefined` (an own `undefined` for `z.string().optional()`, \"c\" for\n * `.catch(\"c\")`), at or past it as a substituted value (a \"defaulted\" item).\n * `z.tuple([z.string(), z.number().default(1)])` therefore answers `[\"x\"]` with\n * `[\"x\", 1]`, length 2, and `z.tuple([z.any()]).rest(z.number())` answers `[]`\n * with `[undefined]`. So the tuple is a mutating node — its output is not its\n * input — exactly when some slot that CAN be absent is not a truncating one.\n * Without a rest element only slots from `optStart` on can be absent (a shorter\n * input is `too_small`); with one, any slot can.\n */\nexport function tupleRewritesShortInput(ir: SchemaIR & { type: \"tuple\" }): boolean {\n const len = ir.items.length;\n const optoutStart = ir.optoutStart ?? len;\n const optionalIn = ir.optionalIn ?? [];\n for (let i = ir.rest === null ? ir.optStart : 0; i < len; i++) {\n if (i < optoutStart || !optionalIn.includes(i)) return true;\n }\n return false;\n}\n\n/**\n * Does this node hand back a container that could still carry an own\n * `__proto__` zod would have stripped?\n *\n * True for the shapes whose output IS their input: a LOOSE or CATCHALL object\n * (a stripping one rebuilds from the declared keys, and `parsedProperties`\n * already drops the key) and any record. See {@link ZC_PROTO_SCRUB_DECL} for\n * what zod does and why the difference matters.\n */\nexport function needsProtoScrub(ir: SchemaIR): boolean {\n // Every record: the walk skips `__proto__` but the container is handed back.\n if (ir.type === \"record\") return true;\n if (ir.type !== \"object\") return false;\n // A STRIPPING object rebuilds from the declared keys and `parsedProperties`\n // drops `__proto__`, so its output can never carry one.\n if (ir.stripUnknownKeys === true) return false;\n // A STRICT object reports an undeclared `__proto__` as an unrecognized key\n // and fails, so the only way one reaches its output is by being DECLARED —\n // which zod's shape loop strips while still counting the name as recognized.\n if (ir.strict === true) return Object.hasOwn(ir.properties, \"__proto__\");\n // Loose or catchall: an undeclared `__proto__` rides through untouched.\n return true;\n}\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 (\n ir.items.some(hasMutation) ||\n (ir.rest !== null && hasMutation(ir.rest)) ||\n tupleRewritesShortInput(ir)\n );\n case \"record\":\n return hasMutation(ir.valueType);\n // A freezing readonly produces a value that is not its input, exactly as a\n // strip object does — so it must never take a by-reference shortcut.\n case \"readonly\":\n return ir.freeze === true || hasMutation(ir.inner);\n case \"optional\":\n case \"nullable\":\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 \"does an absent key already fail on its own\" by the object extractor,\n * which otherwise has to report the absence itself (zod's `nonoptional`\n * issue), and as \"is a fixed-length rebuild exact\" by the tuple build.\n * Conservative: anything that might accept, produce, or default to `undefined`\n * 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":";;;AA6PA,SAAgB,iBAAiB,OAA0B;CACzD,OAAO,MAAM,MAAM,SAAS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ACjC,KAAK,OACH,OAAO,YAAY,GAAG,OAAO,KAAK,YAAY,GAAG,SAAS;EAC5D,KAAK,QACH,OAAO;EACT,SACE,OAAO;CACX;AACF;;;;;;;;;;;;;;AAeA,SAAgB,oBAAoB,IAAuB;CACzD,OAAO,GAAG,SAAS,YAAY,GAAG,kBAAkB,OAAO,iBAAiB,EAAE;AAChF;;;;;;;;;;AAWA,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;EACL,KAAK,eACH,OAAO,iBAAiB,GAAG,KAAK;EAClC,SAIE,OAAO;CACX;AACF;;;;;AAMA,SAAgB,cACd,GACA,GACQ;CACR,QAAQ,eAAe,EAAE,SAAS,OAAO,eAAe,EAAE,SAAS;AACrE"}
|
|
@@ -69,6 +69,7 @@ function generateValidator(ir, name, options) {
|
|
|
69
69
|
ctx.preamble.push(`function ${t.fastName}(input){${declareFastTemps(targetGen.scope)}return ${body};}`);
|
|
70
70
|
}
|
|
71
71
|
if (fastExpr === null) {
|
|
72
|
+
ctx.fastRecursionDisabled = true;
|
|
72
73
|
ctx.preamble.length = fastPreambleLen;
|
|
73
74
|
ctx.regexCache = fastRegexCache;
|
|
74
75
|
if (fastEffectCache === void 0) delete ctx.effectFnCache;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/core/codegen/index.ts"],"sourcesContent":["import type { SchemaIR } from \"../types.js\";\nimport type {\n CodeGenContext,\n CodeGenResult,\n CodegenMode,\n GeneratedConstant,\n RecTargetGen,\n} from \"./context.js\";\nimport {\n fastResultIsInput,\n generateBuild,\n nestedNeedsProtoScrub,\n rebuildsOutput,\n} from \"./build-path.js\";\nimport {\n declareFastTemps,\n emitRetainedMethod,\n emitRfDelegate,\n emitRuntimeHelper,\n hasMutation,\n needsProtoScrub,\n RETAINED_SCHEMA_VAR,\n} from \"./context.js\";\nimport type { SharedSchemaPlan } from \"./dedupe.js\";\nimport { ZC_PROTO_SCRUB_DECL } from \"./issue-decls.js\";\nimport { createFastGen, generateFast } from \"./fast-path.js\";\nimport { createSlowGen, generateSlow } from \"./slow-path.js\";\n\nexport type { CodeGenResult } from \"./context.js\";\n\nexport interface GenerateValidatorOptions {\n refCount?: number;\n /** Codegen output mode. Defaults to \"inline\". */\n mode?: CodegenMode;\n /**\n * File-level shared slow-walk plan (schema deduplication). Applied only to\n * mutation-free schemas, so shared walks stay on the deferred cold path.\n */\n sharedSchemas?: SharedSchemaPlan | undefined;\n /**\n * Compact mode (`output: \"compact\"`). Drop the compiled slow walk for\n * mutation-free schemas with a TOTAL fast path and delegate the cold error\n * path to the retained Zod schema (`__zcFinZ`). The fast (hot) path is\n * unchanged; only the bulky error-collecting walk — 64–77% of generated\n * bytes — is replaced by a few bytes of zod delegation. See\n * {@link CodeGenResult.usesRetainedSchema}.\n */\n compact?: boolean | undefined;\n /** Internal file-pipeline hook for pooling exact constant initializers across validators. */\n onConstant?: ((constant: GeneratedConstant) => void) | undefined;\n /** Internal exact-initializer plan used by the file pipeline's final generation pass. */\n sharedConstantNames?: ReadonlyMap<string, string> | undefined;\n}\n\n/**\n * Generate optimized validation code from SchemaIR.\n *\n * - `code`: preamble declarations (Sets, RegExps, etc.) — deterministic for the same IR\n * - `functionDef`: full function expression string referencing preamble vars via closure\n * - `usedHelpers`: helper names from \"virtual:zod-compiler/runtime\" referenced (lean mode only)\n *\n * Usage: `new Function(code + \"\\nreturn \" + functionDef + \";\")()`\n */\nexport function generateValidator(\n ir: SchemaIR,\n name: string,\n options?: GenerateValidatorOptions,\n): CodeGenResult {\n const fnName = `safeParse_${name}`;\n const mode: CodegenMode = options?.mode ?? \"inline\";\n const ctx: CodeGenContext = {\n preamble: [],\n counter: 0,\n fnName,\n regexCache: new Map(),\n mode,\n usedHelpers: new Set(),\n onConstant: options?.onConstant,\n sharedConstantNames: options?.sharedConstantNames,\n };\n\n // Slow-walk sharing. The plan already excludes any shape that would reach for\n // this export's `__rf[]`, and a shared walk returns its parsed value, so a\n // rewriting shape (a stripping object above all) delivers its result through\n // the call. Nothing left to gate on here.\n if (options?.sharedSchemas !== undefined) {\n ctx.sharedSchemas = options.sharedSchemas;\n }\n\n // Root-level fallback: the whole schema delegates to Zod, so zod's own\n // safeParse result IS the result. Returning it directly skips the issue\n // copy loop (which would force zod's eager ZodError construction), the\n // pointless [].concat(path) rewrites, and the __zcFin re-wrap. Delegation\n // goes through the pre-mutation capture (emitRfDelegate) — here __rf[0]\n // and the __zcMkv target are routinely the SAME object.\n if (ir.type === \"fallback\" && ir.refIndex !== undefined) {\n const delegate = emitRfDelegate(ctx, ir.refIndex);\n return {\n code: [\"/* zod-compiler */\", ...ctx.preamble].join(\"\\n\"),\n functionDef: `function ${fnName}(input){return ${delegate}(input);}`,\n refCount: options?.refCount ?? 0,\n usedHelpers: ctx.usedHelpers,\n fastFnName: null,\n fastTotal: false,\n };\n }\n\n // Recursion-target table. The root (refId 0) reuses the schema's own\n // `safeParse_<name>` / hosted fast-check, so it needs no separate helper and\n // its fast name is allocated lazily during the walk (recFastName). Non-root\n // targets — recursive sub-schemas nested in a larger root, multiple distinct\n // recursive shapes, mutual recursion — are each hosted as a standalone\n // `__rsp_N` (slow) / `__fcr_N` (fast) validator the cycle calls by name.\n // Common directly-self-recursive schemas have no non-root targets, so this\n // leaves their generated output byte-identical.\n const nonRootTargets = collectRecursionTargets(ir);\n ctx.recTargets = new Map<number, RecTargetGen>([[0, { isRoot: true, slowName: fnName }]]);\n for (const [refId, inner] of nonRootTargets) {\n ctx.recTargets.set(refId, {\n isRoot: false,\n inner,\n slowName: `__rsp_${ctx.counter++}`,\n fastName: `__fcr_${ctx.counter++}`,\n });\n }\n const hasNonRootTargets = nonRootTargets.size > 0;\n\n // Fast Path: generate a boolean expression for eligible schemas.\n //\n // generateFast mutates ctx as it walks (extracted __fo_ helpers + regex/effect\n // decls pushed to the preamble, a recursive __fcr_ name reserved, dedup caches\n // populated). The walk is all-or-nothing: a later fast-ineligible node makes it\n // return null AFTER those side effects already landed. Without a rollback the\n // discarded fast path leaves dead __fo_ helpers in the output — and, when one\n // referenced the recursive __fcr_ host that the `fastExpr !== null` branch below\n // never emits, a dangling reference to an undefined identifier. Snapshot the\n // mutable state and restore it on abort so the slow path re-declares from clean.\n const fastPreambleLen = ctx.preamble.length;\n const fastRegexCache = new Map(ctx.regexCache);\n const fastEffectCache = ctx.effectFnCache && new Map(ctx.effectFnCache);\n const fastValueCache = ctx.valueCache && new Map(ctx.valueCache);\n const fastRecName = ctx.recFastName;\n // A schema that rebuilds its output never takes a by-reference shortcut:\n // `fastResultIsInput` withholds `data: input` and the published `fc` alike,\n // so its root expression is only ever consumed as a VERDICT — by `.is()`. It\n // is therefore generated as an acceptance predicate (see FastGen.acceptance),\n // which differs from the by-reference form only at `.default()` nodes and is\n // what lets a defaulted schema keep a zero-allocation `.is()`.\n const acceptance = rebuildsOutput(ir);\n const fg = createFastGen(\"input\", ctx, false, undefined, undefined, acceptance);\n let fastExpr = generateFast(ir, fg);\n if (fastExpr !== null && hasNonRootTargets) {\n // Host each non-root recursion target as a boolean fast-check helper. A\n // single fast-ineligible target (e.g. one whose recursive shape contains a\n // fallback) disables the WHOLE fast path: the root expression already emits\n // calls to these names, so a missing body would dangle. The shared\n // rollback below then restores clean state for the slow-only path.\n for (const t of ctx.recTargets.values()) {\n if (t.isRoot) continue;\n const targetGen = createFastGen(\"input\", ctx, false, undefined, undefined, acceptance);\n const body = generateFast(t.inner as SchemaIR, targetGen);\n if (body === null) {\n fastExpr = null;\n break;\n }\n ctx.preamble.push(\n `function ${t.fastName}(input){${declareFastTemps(targetGen.scope)}return ${body};}`,\n );\n }\n }\n if (fastExpr === null) {\n ctx.preamble.length = fastPreambleLen;\n ctx.regexCache = fastRegexCache;\n if (fastEffectCache === undefined) delete ctx.effectFnCache;\n else ctx.effectFnCache = fastEffectCache;\n // Value declarations the abandoned walk emitted are truncated above, so\n // their cache entries would name identifiers that no longer exist.\n if (fastValueCache === undefined) delete ctx.valueCache;\n else ctx.valueCache = fastValueCache;\n if (fastRecName === undefined) delete ctx.recFastName;\n else ctx.recFastName = fastRecName;\n }\n\n // Host the fast expression in a named boolean helper. Self-recursive\n // schemas need it so recursive refs can call it; every other eligible\n // schema benefits too: __zcMkv wires it into parse()/parseAsync(), whose\n // success paths then return the input directly — no intermediate\n // SafeParseResult allocation (the safeParse function body is far past\n // V8's inlining budget, so escape analysis never removes it).\n let fastFnName: string | null = null;\n if (fastExpr !== null && fastExpr !== \"true\") {\n fastFnName = ctx.recFastName ?? `__fc_${ctx.counter++}`;\n ctx.preamble.push(\n `function ${fastFnName}(input){${declareFastTemps(fg.scope)}return ${fastExpr};}`,\n );\n fastExpr = `${fastFnName}(input)`;\n }\n\n // Build Path: one pass that validates and assembles rewritten output, bailing\n // on the first failure (see build-path). Null unless every mutation in the\n // schema is modelled — so this emits nothing for the mutation-free schemas\n // the compact branch takes.\n const buildFnName = generateBuild(ir, ctx);\n\n // A zodDelegate with a rebuilding inner exists only to accelerate that\n // build. If an unmodelled descendant made the all-or-nothing build decline,\n // preserve the old root-fallback shape instead of wrapping the same pristine\n // Zod call in an issues array/copy/finalizer. This keeps unsupported object\n // intersections neutral rather than making compilation slower than Zod.\n if (ir.type === \"zodDelegate\" && rebuildsOutput(ir.inner) && buildFnName === null) {\n ctx.preamble.length = 0;\n ctx.usedHelpers.clear();\n ctx.regexCache.clear();\n ctx.effectFnCache?.clear();\n ctx.valueCache?.clear();\n const delegate = emitRfDelegate(ctx, ir.refIndex);\n return {\n code: [\"/* zod-compiler */\", ...ctx.preamble].join(\"\\n\"),\n functionDef: `function ${fnName}(input){return ${delegate}(input);}`,\n refCount: options?.refCount ?? 0,\n usedHelpers: ctx.usedHelpers,\n fastFnName: null,\n fastTotal: false,\n };\n }\n\n // `.is()` for a build-path schema is the fast expression — stripping reshapes\n // the payload, never the verdict, and a `.default()` is covered too: the build\n // path is only ever taken by a rebuilding schema, whose expression was\n // generated in acceptance mode (`acceptance` above) and so accepts the absent\n // value the substitution stands in for.\n const buildIsFnName = fastFnName;\n\n const baseRefCount = options?.refCount ?? 0;\n\n // Compact mode: a mutation-free schema with a TOTAL fast path needs no\n // compiled slow walk — its only purpose is reproducing zod's issues on\n // failure, and the original zod schema (retained in `output: \"compact\"`) does\n // that exactly. Emit the fast check and, on failure, delegate to a fresh root\n // RefEntry (the schema itself) via the pristine safeParse method capture, then\n // wrap it in the lazy `__zcFinZ` failure. Drops 64–77% of generated bytes\n // with zero hot-path cost (fc and `.is()` are unchanged) and zod-identical\n // errors. Excluded: schemas with non-root recursion targets (mutual/nested\n // recursion still hosts standalone slow validators) and any non-total fast\n // path (mutation/default/catch/fallback) — those keep the compiled path.\n if (\n options?.compact === true &&\n fastExpr !== null &&\n fastExpr !== \"true\" &&\n !hasMutation(ir) &&\n // `data: input` verbatim, with no compiled walk to fall back on — so a\n // schema whose output needs an own `__proto__` removed cannot use it.\n !needsProtoScrub(ir) &&\n !nestedNeedsProtoScrub(ir) &&\n !hasNonRootTargets\n ) {\n const delegate = emitRetainedMethod(ctx);\n ctx.usedHelpers.add(\"__zcFinZ\");\n return {\n code: [\"/* zod-compiler */\", ...ctx.preamble].join(\"\\n\"),\n functionDef: [\n `function ${fnName}(input){`,\n `if(${fastExpr}){return{success:true,data:input};}`,\n `return __zcFinZ(${delegate},${RETAINED_SCHEMA_VAR},input);`,\n `}`,\n ].join(\"\\n\"),\n refCount: baseRefCount,\n usedHelpers: ctx.usedHelpers,\n fastFnName,\n // Mutation-free total fast path: fc(input) ⟺ accepts(input), so `.is()`\n // installs fc directly (compact never weakens the guard).\n fastTotal: true,\n usesRetainedSchema: true,\n };\n }\n\n // Compact + Build Path: same bargain for a schema with modelled rewrites. The\n // build pass still has to run (it produces the payload, which zod's schema\n // would only reproduce by parsing again), but the compiled issue walk is what\n // compact drops, and delegating that to the retained zod schema costs a few\n // bytes.\n if (\n options?.compact === true &&\n buildFnName !== null &&\n ctx.buildFailName !== undefined &&\n !hasNonRootTargets\n ) {\n const delegate = emitRetainedMethod(ctx);\n ctx.usedHelpers.add(\"__zcFinZ\");\n const built = `__bd_${ctx.counter++}`;\n return {\n code: [\"/* zod-compiler */\", ...ctx.preamble].join(\"\\n\"),\n functionDef: [\n `function ${fnName}(input){`,\n `var ${built}=${buildFnName}(input);`,\n `if(${built}!==${ctx.buildFailName}){return{success:true,data:${built}};}`,\n `return __zcFinZ(${delegate},${RETAINED_SCHEMA_VAR},input);`,\n `}`,\n ].join(\"\\n\"),\n refCount: baseRefCount,\n usedHelpers: ctx.usedHelpers,\n fastFnName: null,\n fastTotal: false,\n isFnName: buildIsFnName,\n usesRetainedSchema: true,\n };\n }\n\n // Host each non-root recursion target as a safeParse-shaped slow validator,\n // mirroring the root's eager body: collect issues, return success+data or a\n // deferred-error result. Always emitted (the slow path always exists); the\n // recursion call sites read `.success` / `.error.issues` / `.data`. Hoisted\n // function declarations, so their order relative to the root is irrelevant.\n if (hasNonRootTargets) {\n for (const t of ctx.recTargets.values()) {\n if (t.isRoot) continue;\n const body = generateSlow(t.inner as SchemaIR, createSlowGen(\"_d\", \"_d\", \"[]\", \"_e\", ctx));\n ctx.usedHelpers.add(\"__zcFin\");\n ctx.preamble.push(\n `function ${t.slowName}(input){var _e=[];\\nvar _d=input;\\n${body}\\n` +\n `if(_e.length===0){return{success:true,data:_d};}\\nreturn __zcFin(_e,_d);}`,\n );\n }\n }\n\n const sg = createSlowGen(\"_d\", \"_d\", \"[]\", \"_e\", ctx);\n // When the root schema's own shape is shared (it recurs as a sub-schema of\n // another export, or as a duplicate root), its slow walk delegates to the\n // shared function instead of emitting a second full copy. The fast path is\n // still generated inline above — only the cold walk is shared.\n const rootRef = ctx.sharedSchemas?.refFor(ir);\n const slowCode = rootRef !== undefined ? `_d=${rootRef.name}(_d,[],_e);` : generateSlow(ir, sg);\n\n const buildCode = (): string => [\"/* zod-compiler */\", ...ctx.preamble].join(\"\\n\");\n\n const functionDefParts = [`function ${fnName}(input){`];\n\n // Build Path: every mutation is modelled, so one pass can validate and\n // assemble the output together and bail on the first failure, leaving the\n // issue-producing walk deferred behind `.error` (see build-path).\n // The fast check stays out of `safeParse` entirely — running it first would\n // read every property twice — but it is still an EXACT acceptance predicate\n // (stripping reshapes the output, never the verdict), so `.is()` installs it.\n if (buildFnName !== null && ctx.buildFailName !== undefined) {\n ctx.usedHelpers.add(\"__zcFinD\");\n const built = `__bd_${ctx.counter++}`;\n // A self-recursive walk calls this validator BY NAME (slowRecursiveRef),\n // and that binding exists only inside the named function expression — so\n // there the walk stays a per-call closure. Everything else hosts it in the\n // preamble, keeping safeParse to three statements. Mirrors the same split\n // in the mutation-free branch below.\n const recursive = slowCode.includes(fnName);\n let deferred: string;\n if (recursive) {\n deferred = `__zcFinD(function(input){var _e=[];\\nvar _d=input;\\n${slowCode}\\nreturn _e;},input)`;\n } else {\n const walkName = `__sw_${ctx.counter++}`;\n ctx.preamble.push(\n `function ${walkName}(input){var _e=[];\\nvar _d=input;\\n${slowCode}\\nreturn _e;}`,\n );\n deferred = `__zcFinD(${walkName},input)`;\n }\n return {\n code: buildCode(),\n functionDef: [\n `function ${fnName}(input){`,\n `var ${built}=${buildFnName}(input);`,\n `if(${built}!==${ctx.buildFailName}){return{success:true,data:${built}};}`,\n `return ${deferred};`,\n `}`,\n ].join(\"\\n\"),\n refCount: options?.refCount ?? 0,\n usedHelpers: ctx.usedHelpers,\n // No by-reference shortcut: `data` is the freshly built object, so\n // parse() must go through safeParse rather than returning its input.\n fastFnName: null,\n // `fastTotal` qualifies `fastFnName`, which is null here; the predicate\n // travels in `isFnName` instead.\n fastTotal: false,\n isFnName: buildIsFnName,\n };\n }\n\n if (fastExpr === \"true\") {\n // Schema always succeeds (any/unknown) — skip slow path entirely\n functionDefParts.push(`return{success:true,data:input};`);\n functionDefParts.push(`}`);\n return {\n code: buildCode(),\n functionDef: functionDefParts.join(\"\\n\"),\n refCount: options?.refCount ?? 0,\n usedHelpers: ctx.usedHelpers,\n fastFnName: null,\n // any/unknown always succeed; `.is()` derives `true` from the fn fallback.\n fastTotal: false,\n };\n }\n\n if (fastExpr !== null && !hasMutation(ir) && !nestedNeedsProtoScrub(ir)) {\n // The by-reference shortcut hands back the input verbatim, which a loose or\n // catchall object — or a record — must not do while it still carries an own\n // `__proto__` (see ZC_PROTO_SCRUB_DECL). The fast check itself stays a pure\n // predicate, so `fc(input) ⟺ zod accepts` still holds and the deferred error\n // path below is untouched; only the value handed back is filtered. The cost\n // is one `hasOwnProperty` per successful parse of those shapes.\n const fastData = needsProtoScrub(ir)\n ? `${emitRuntimeHelper(ctx, \"__zcPs\", ZC_PROTO_SCRUB_DECL)}(input)`\n : \"input\";\n // Mutation-free schemas with a fast path: a fast-check failure can never\n // become a slow-path success (both are generated from the same checks —\n // unlike default/catch schemas, whose partial fast path requires value\n // presence while the slow path SUCCEEDS by applying the fallback).\n // The slow path's only output is therefore the issues array, observable\n // solely through `.error` — defer the whole re-walk into the cached\n // accessor (__zcFinD): a failed safeParse whose `.error` is never read\n // costs the fast check alone.\n //\n // The walk is HOSTED as a named preamble function rather than a per-call\n // closure, for two measured reasons: (1) a failed safeParse no longer\n // allocates a closure environment + function object before the deferral\n // even starts; (2) the safeParse body shrinks to two statements, putting\n // it within V8's inlining budget — callers in hot loops get the\n // success-path result object escape-analyzed away entirely, which the\n // old shape (slow walk inlined into the body) made impossible.\n ctx.usedHelpers.add(\"__zcFinD\");\n if (slowCode.includes(fnName)) {\n // Self-recursive slow paths call the safeParse function by NAME\n // (slowRecursiveRef) — that binding exists only inside the named\n // function expression under the documented evaluation contract\n // (`new Function(code + \"return \" + functionDef)`), so the walk stays\n // a per-call closure for recursive schemas. Recursion is the rare\n // shape; everything else gets the hosted walk.\n functionDefParts.push(\n `if(${fastExpr}){return{success:true,data:${fastData}};}`,\n `return __zcFinD(function(input){`,\n `var _e=[];`,\n `var _d=input;`,\n slowCode,\n `return _e;`,\n `},input);`,\n `}`,\n );\n } else {\n const walkName = `__sw_${ctx.counter++}`;\n ctx.preamble.push(\n `function ${walkName}(input){var _e=[];\\nvar _d=input;\\n${slowCode}\\nreturn _e;}`,\n );\n functionDefParts.push(\n `if(${fastExpr}){return{success:true,data:${fastData}};}`,\n `return __zcFinD(${walkName},input);`,\n `}`,\n );\n }\n return {\n code: buildCode(),\n functionDef: functionDefParts.join(\"\\n\"),\n refCount: options?.refCount ?? 0,\n usedHelpers: ctx.usedHelpers,\n // `fc` is a sound VERDICT here either way, but publishing it also promises\n // `parse()` may return the input — which a scrubbed output cannot (see\n // fastResultIsInput). `.is()` still gets the predicate through fastTotal.\n fastFnName: fastResultIsInput(ir) ? fastFnName : null,\n // Total predicate: mutation-free fast path, fc(input) ⟺ accepts(input).\n // generateIIFE installs fc directly as the zero-allocation `.is()`.\n fastTotal: true,\n };\n }\n\n if (fastExpr !== null && fastResultIsInput(ir)) {\n // Partial fast path (default/catch/... present-value shortcut): the slow\n // path must run eagerly — it can succeed where the fast check failed.\n //\n // Withheld when the schema rebuilds its output: there the fast check is a\n // sound VERDICT but says nothing about the payload, and `data:input` would\n // hand back the unstripped input. Such schemas reach here only when the\n // build path declined them, so the eager walk produces the output instead.\n functionDefParts.push(`if(${fastExpr}){return{success:true,data:input};}`);\n }\n\n // Success branch inlined at the call site instead of inside __zcFin: the\n // eager path (mutation schemas — coerce/default/trim/transform) returns\n // here on EVERY parse, and the inline literal keeps the hot exit free of a\n // cross-function call; __zcFin is reached only on failure.\n functionDefParts.push(\n `var _e=[];`,\n `var _d=input;`,\n slowCode,\n `if(_e.length===0){return{success:true,data:_d};}`,\n `return __zcFin(_e,_d);`,\n `}`,\n );\n\n const functionDef = functionDefParts.join(\"\\n\");\n\n return {\n code: buildCode(),\n functionDef,\n refCount: options?.refCount ?? 0,\n usedHelpers: ctx.usedHelpers,\n // `fc` carries a stronger contract than \"accepts\": `__zcMkv` returns the\n // INPUT from `parse()`/`parseAsync()`/`~standard` whenever it holds, so it\n // may only be published when a passing check implies `data === input`. A\n // rebuilding schema breaks that even though its safeParse is correct, and so\n // does a union whose options can rewrite — see `fastResultIsInput` for both.\n // Same guard as the `data: input` shortcut above, which is the other reader\n // of the same contract.\n fastFnName: fastResultIsInput(ir) ? fastFnName : null,\n // Partial fast path (default/catch) or none (including coercion): a false fc\n // result does not imply rejection, so `.is()` derives from\n // safeParse(input).success.\n fastTotal: false,\n };\n}\n\n/**\n * Find every non-root recursion target (a `recursionTarget` node, refId ≥ 1)\n * reachable from `root`, mapping refId → the inner IR to host as a standalone\n * validator. The root target (refId 0) is the schema's own function and is\n * never wrapped, so it never appears here. The same target may be wrapped at\n * several sites (a recursive schema reached from sibling positions); the first\n * inner wins — they are structurally identical extractions of one schema.\n */\nfunction collectRecursionTargets(root: SchemaIR): Map<number, SchemaIR> {\n const out = new Map<number, SchemaIR>();\n const seen = new Set<SchemaIR>();\n const walk = (ir: SchemaIR): void => {\n if (seen.has(ir)) return;\n seen.add(ir);\n if (ir.type === \"recursionTarget\" && !out.has(ir.refId)) {\n out.set(ir.refId, ir.inner);\n }\n for (const child of childIRs(ir)) walk(child);\n };\n walk(root);\n return out;\n}\n\n/** Direct child SchemaIR nodes, covering every node type (including the new wrapper). */\nfunction childIRs(ir: SchemaIR): readonly SchemaIR[] {\n switch (ir.type) {\n case \"object\":\n return 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"],"mappings":";;;;;;;;;;;;;;;AA+DA,SAAgB,kBACd,IACA,MACA,SACe;CACf,MAAM,SAAS,aAAa;CAC5B,MAAM,OAAoB,SAAS,QAAQ;CAC3C,MAAM,MAAsB;EAC1B,UAAU,CAAC;EACX,SAAS;EACT;EACA,4BAAY,IAAI,IAAI;EACpB;EACA,6BAAa,IAAI,IAAI;EACrB,YAAY,SAAS;EACrB,qBAAqB,SAAS;CAChC;CAMA,IAAI,SAAS,kBAAkB,KAAA,GAC7B,IAAI,gBAAgB,QAAQ;CAS9B,IAAI,GAAG,SAAS,cAAc,GAAG,aAAa,KAAA,GAAW;EACvD,MAAM,WAAW,eAAe,KAAK,GAAG,QAAQ;EAChD,OAAO;GACL,MAAM,CAAC,sBAAsB,GAAG,IAAI,QAAQ,CAAC,CAAC,KAAK,IAAI;GACvD,aAAa,YAAY,OAAO,iBAAiB,SAAS;GAC1D,UAAU,SAAS,YAAY;GAC/B,aAAa,IAAI;GACjB,YAAY;GACZ,WAAW;EACb;CACF;CAUA,MAAM,iBAAiB,wBAAwB,EAAE;CACjD,IAAI,6BAAa,IAAI,IAA0B,CAAC,CAAC,GAAG;EAAE,QAAQ;EAAM,UAAU;CAAO,CAAC,CAAC,CAAC;CACxF,KAAK,MAAM,CAAC,OAAO,UAAU,gBAC3B,IAAI,WAAW,IAAI,OAAO;EACxB,QAAQ;EACR;EACA,UAAU,SAAS,IAAI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CACZ;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/core/codegen/index.ts"],"sourcesContent":["import type { SchemaIR } from \"../types.js\";\nimport type {\n CodeGenContext,\n CodeGenResult,\n CodegenMode,\n GeneratedConstant,\n RecTargetGen,\n} from \"./context.js\";\nimport {\n fastResultIsInput,\n generateBuild,\n nestedNeedsProtoScrub,\n rebuildsOutput,\n} from \"./build-path.js\";\nimport {\n declareFastTemps,\n emitRetainedMethod,\n emitRfDelegate,\n emitRuntimeHelper,\n hasMutation,\n needsProtoScrub,\n RETAINED_SCHEMA_VAR,\n} from \"./context.js\";\nimport type { SharedSchemaPlan } from \"./dedupe.js\";\nimport { ZC_PROTO_SCRUB_DECL } from \"./issue-decls.js\";\nimport { createFastGen, generateFast } from \"./fast-path.js\";\nimport { createSlowGen, generateSlow } from \"./slow-path.js\";\n\nexport type { CodeGenResult } from \"./context.js\";\n\nexport interface GenerateValidatorOptions {\n refCount?: number;\n /** Codegen output mode. Defaults to \"inline\". */\n mode?: CodegenMode;\n /**\n * File-level shared slow-walk plan (schema deduplication). Applied only to\n * mutation-free schemas, so shared walks stay on the deferred cold path.\n */\n sharedSchemas?: SharedSchemaPlan | undefined;\n /**\n * Compact mode (`output: \"compact\"`). Drop the compiled slow walk for\n * mutation-free schemas with a TOTAL fast path and delegate the cold error\n * path to the retained Zod schema (`__zcFinZ`). The fast (hot) path is\n * unchanged; only the bulky error-collecting walk — 64–77% of generated\n * bytes — is replaced by a few bytes of zod delegation. See\n * {@link CodeGenResult.usesRetainedSchema}.\n */\n compact?: boolean | undefined;\n /** Internal file-pipeline hook for pooling exact constant initializers across validators. */\n onConstant?: ((constant: GeneratedConstant) => void) | undefined;\n /** Internal exact-initializer plan used by the file pipeline's final generation pass. */\n sharedConstantNames?: ReadonlyMap<string, string> | undefined;\n}\n\n/**\n * Generate optimized validation code from SchemaIR.\n *\n * - `code`: preamble declarations (Sets, RegExps, etc.) — deterministic for the same IR\n * - `functionDef`: full function expression string referencing preamble vars via closure\n * - `usedHelpers`: helper names from \"virtual:zod-compiler/runtime\" referenced (lean mode only)\n *\n * Usage: `new Function(code + \"\\nreturn \" + functionDef + \";\")()`\n */\nexport function generateValidator(\n ir: SchemaIR,\n name: string,\n options?: GenerateValidatorOptions,\n): CodeGenResult {\n const fnName = `safeParse_${name}`;\n const mode: CodegenMode = options?.mode ?? \"inline\";\n const ctx: CodeGenContext = {\n preamble: [],\n counter: 0,\n fnName,\n regexCache: new Map(),\n mode,\n usedHelpers: new Set(),\n onConstant: options?.onConstant,\n sharedConstantNames: options?.sharedConstantNames,\n };\n\n // Slow-walk sharing. The plan already excludes any shape that would reach for\n // this export's `__rf[]`, and a shared walk returns its parsed value, so a\n // rewriting shape (a stripping object above all) delivers its result through\n // the call. Nothing left to gate on here.\n if (options?.sharedSchemas !== undefined) {\n ctx.sharedSchemas = options.sharedSchemas;\n }\n\n // Root-level fallback: the whole schema delegates to Zod, so zod's own\n // safeParse result IS the result. Returning it directly skips the issue\n // copy loop (which would force zod's eager ZodError construction), the\n // pointless [].concat(path) rewrites, and the __zcFin re-wrap. Delegation\n // goes through the pre-mutation capture (emitRfDelegate) — here __rf[0]\n // and the __zcMkv target are routinely the SAME object.\n if (ir.type === \"fallback\" && ir.refIndex !== undefined) {\n const delegate = emitRfDelegate(ctx, ir.refIndex);\n return {\n code: [\"/* zod-compiler */\", ...ctx.preamble].join(\"\\n\"),\n functionDef: `function ${fnName}(input){return ${delegate}(input);}`,\n refCount: options?.refCount ?? 0,\n usedHelpers: ctx.usedHelpers,\n fastFnName: null,\n fastTotal: false,\n };\n }\n\n // Recursion-target table. The root (refId 0) reuses the schema's own\n // `safeParse_<name>` / hosted fast-check, so it needs no separate helper and\n // its fast name is allocated lazily during the walk (recFastName). Non-root\n // targets — recursive sub-schemas nested in a larger root, multiple distinct\n // recursive shapes, mutual recursion — are each hosted as a standalone\n // `__rsp_N` (slow) / `__fcr_N` (fast) validator the cycle calls by name.\n // Common directly-self-recursive schemas have no non-root targets, so this\n // leaves their generated output byte-identical.\n const nonRootTargets = collectRecursionTargets(ir);\n ctx.recTargets = new Map<number, RecTargetGen>([[0, { isRoot: true, slowName: fnName }]]);\n for (const [refId, inner] of nonRootTargets) {\n ctx.recTargets.set(refId, {\n isRoot: false,\n inner,\n slowName: `__rsp_${ctx.counter++}`,\n fastName: `__fcr_${ctx.counter++}`,\n });\n }\n const hasNonRootTargets = nonRootTargets.size > 0;\n\n // Fast Path: generate a boolean expression for eligible schemas.\n //\n // generateFast mutates ctx as it walks (extracted __fo_ helpers + regex/effect\n // decls pushed to the preamble, a recursive __fcr_ name reserved, dedup caches\n // populated). The walk is all-or-nothing: a later fast-ineligible node makes it\n // return null AFTER those side effects already landed. Without a rollback the\n // discarded fast path leaves dead __fo_ helpers in the output — and, when one\n // referenced the recursive __fcr_ host that the `fastExpr !== null` branch below\n // never emits, a dangling reference to an undefined identifier. Snapshot the\n // mutable state and restore it on abort so the slow path re-declares from clean.\n const fastPreambleLen = ctx.preamble.length;\n const fastRegexCache = new Map(ctx.regexCache);\n const fastEffectCache = ctx.effectFnCache && new Map(ctx.effectFnCache);\n const fastValueCache = ctx.valueCache && new Map(ctx.valueCache);\n const fastRecName = ctx.recFastName;\n // A schema that rebuilds its output never takes a by-reference shortcut:\n // `fastResultIsInput` withholds `data: input` and the published `fc` alike,\n // so its root expression is only ever consumed as a VERDICT — by `.is()`. It\n // is therefore generated as an acceptance predicate (see FastGen.acceptance),\n // which differs from the by-reference form only at `.default()` nodes and is\n // what lets a defaulted schema keep a zero-allocation `.is()`.\n const acceptance = rebuildsOutput(ir);\n const fg = createFastGen(\"input\", ctx, false, undefined, undefined, acceptance);\n let fastExpr = generateFast(ir, fg);\n if (fastExpr !== null && hasNonRootTargets) {\n // Host each non-root recursion target as a boolean fast-check helper. A\n // single fast-ineligible target (e.g. one whose recursive shape contains a\n // fallback) disables the WHOLE fast path: the root expression already emits\n // calls to these names, so a missing body would dangle. The shared\n // rollback below then restores clean state for the slow-only path.\n for (const t of ctx.recTargets.values()) {\n if (t.isRoot) continue;\n const targetGen = createFastGen(\"input\", ctx, false, undefined, undefined, acceptance);\n const body = generateFast(t.inner as SchemaIR, targetGen);\n if (body === null) {\n fastExpr = null;\n break;\n }\n ctx.preamble.push(\n `function ${t.fastName}(input){${declareFastTemps(targetGen.scope)}return ${body};}`,\n );\n }\n }\n if (fastExpr === null) {\n // The build pass also invokes generateFast for passthrough subtrees. Its\n // recursive calls must decline once this rollback removes their hosts;\n // the pre-allocated names in recTargets alone do not prove they exist.\n ctx.fastRecursionDisabled = true;\n ctx.preamble.length = fastPreambleLen;\n ctx.regexCache = fastRegexCache;\n if (fastEffectCache === undefined) delete ctx.effectFnCache;\n else ctx.effectFnCache = fastEffectCache;\n // Value declarations the abandoned walk emitted are truncated above, so\n // their cache entries would name identifiers that no longer exist.\n if (fastValueCache === undefined) delete ctx.valueCache;\n else ctx.valueCache = fastValueCache;\n if (fastRecName === undefined) delete ctx.recFastName;\n else ctx.recFastName = fastRecName;\n }\n\n // Host the fast expression in a named boolean helper. Self-recursive\n // schemas need it so recursive refs can call it; every other eligible\n // schema benefits too: __zcMkv wires it into parse()/parseAsync(), whose\n // success paths then return the input directly — no intermediate\n // SafeParseResult allocation (the safeParse function body is far past\n // V8's inlining budget, so escape analysis never removes it).\n let fastFnName: string | null = null;\n if (fastExpr !== null && fastExpr !== \"true\") {\n fastFnName = ctx.recFastName ?? `__fc_${ctx.counter++}`;\n ctx.preamble.push(\n `function ${fastFnName}(input){${declareFastTemps(fg.scope)}return ${fastExpr};}`,\n );\n fastExpr = `${fastFnName}(input)`;\n }\n\n // Build Path: one pass that validates and assembles rewritten output, bailing\n // on the first failure (see build-path). Null unless every mutation in the\n // schema is modelled — so this emits nothing for the mutation-free schemas\n // the compact branch takes.\n const buildFnName = generateBuild(ir, ctx);\n\n // A zodDelegate with a rebuilding inner exists only to accelerate that\n // build. If an unmodelled descendant made the all-or-nothing build decline,\n // preserve the old root-fallback shape instead of wrapping the same pristine\n // Zod call in an issues array/copy/finalizer. This keeps unsupported object\n // intersections neutral rather than making compilation slower than Zod.\n if (ir.type === \"zodDelegate\" && rebuildsOutput(ir.inner) && buildFnName === null) {\n ctx.preamble.length = 0;\n ctx.usedHelpers.clear();\n ctx.regexCache.clear();\n ctx.effectFnCache?.clear();\n ctx.valueCache?.clear();\n const delegate = emitRfDelegate(ctx, ir.refIndex);\n return {\n code: [\"/* zod-compiler */\", ...ctx.preamble].join(\"\\n\"),\n functionDef: `function ${fnName}(input){return ${delegate}(input);}`,\n refCount: options?.refCount ?? 0,\n usedHelpers: ctx.usedHelpers,\n fastFnName: null,\n fastTotal: false,\n };\n }\n\n // `.is()` for a build-path schema is the fast expression — stripping reshapes\n // the payload, never the verdict, and a `.default()` is covered too: the build\n // path is only ever taken by a rebuilding schema, whose expression was\n // generated in acceptance mode (`acceptance` above) and so accepts the absent\n // value the substitution stands in for.\n const buildIsFnName = fastFnName;\n\n const baseRefCount = options?.refCount ?? 0;\n\n // Compact mode: a mutation-free schema with a TOTAL fast path needs no\n // compiled slow walk — its only purpose is reproducing zod's issues on\n // failure, and the original zod schema (retained in `output: \"compact\"`) does\n // that exactly. Emit the fast check and, on failure, delegate to a fresh root\n // RefEntry (the schema itself) via the pristine safeParse method capture, then\n // wrap it in the lazy `__zcFinZ` failure. Drops 64–77% of generated bytes\n // with zero hot-path cost (fc and `.is()` are unchanged) and zod-identical\n // errors. Excluded: schemas with non-root recursion targets (mutual/nested\n // recursion still hosts standalone slow validators) and any non-total fast\n // path (mutation/default/catch/fallback) — those keep the compiled path.\n if (\n options?.compact === true &&\n fastExpr !== null &&\n fastExpr !== \"true\" &&\n !hasMutation(ir) &&\n // `data: input` verbatim, with no compiled walk to fall back on — so a\n // schema whose output needs an own `__proto__` removed cannot use it.\n !needsProtoScrub(ir) &&\n !nestedNeedsProtoScrub(ir) &&\n !hasNonRootTargets\n ) {\n const delegate = emitRetainedMethod(ctx);\n ctx.usedHelpers.add(\"__zcFinZ\");\n return {\n code: [\"/* zod-compiler */\", ...ctx.preamble].join(\"\\n\"),\n functionDef: [\n `function ${fnName}(input){`,\n `if(${fastExpr}){return{success:true,data:input};}`,\n `return __zcFinZ(${delegate},${RETAINED_SCHEMA_VAR},input);`,\n `}`,\n ].join(\"\\n\"),\n refCount: baseRefCount,\n usedHelpers: ctx.usedHelpers,\n fastFnName,\n // Mutation-free total fast path: fc(input) ⟺ accepts(input), so `.is()`\n // installs fc directly (compact never weakens the guard).\n fastTotal: true,\n usesRetainedSchema: true,\n };\n }\n\n // Compact + Build Path: same bargain for a schema with modelled rewrites. The\n // build pass still has to run (it produces the payload, which zod's schema\n // would only reproduce by parsing again), but the compiled issue walk is what\n // compact drops, and delegating that to the retained zod schema costs a few\n // bytes.\n if (\n options?.compact === true &&\n buildFnName !== null &&\n ctx.buildFailName !== undefined &&\n !hasNonRootTargets\n ) {\n const delegate = emitRetainedMethod(ctx);\n ctx.usedHelpers.add(\"__zcFinZ\");\n const built = `__bd_${ctx.counter++}`;\n return {\n code: [\"/* zod-compiler */\", ...ctx.preamble].join(\"\\n\"),\n functionDef: [\n `function ${fnName}(input){`,\n `var ${built}=${buildFnName}(input);`,\n `if(${built}!==${ctx.buildFailName}){return{success:true,data:${built}};}`,\n `return __zcFinZ(${delegate},${RETAINED_SCHEMA_VAR},input);`,\n `}`,\n ].join(\"\\n\"),\n refCount: baseRefCount,\n usedHelpers: ctx.usedHelpers,\n fastFnName: null,\n fastTotal: false,\n isFnName: buildIsFnName,\n usesRetainedSchema: true,\n };\n }\n\n // Host each non-root recursion target as a safeParse-shaped slow validator,\n // mirroring the root's eager body: collect issues, return success+data or a\n // deferred-error result. Always emitted (the slow path always exists); the\n // recursion call sites read `.success` / `.error.issues` / `.data`. Hoisted\n // function declarations, so their order relative to the root is irrelevant.\n if (hasNonRootTargets) {\n for (const t of ctx.recTargets.values()) {\n if (t.isRoot) continue;\n const body = generateSlow(t.inner as SchemaIR, createSlowGen(\"_d\", \"_d\", \"[]\", \"_e\", ctx));\n ctx.usedHelpers.add(\"__zcFin\");\n ctx.preamble.push(\n `function ${t.slowName}(input){var _e=[];\\nvar _d=input;\\n${body}\\n` +\n `if(_e.length===0){return{success:true,data:_d};}\\nreturn __zcFin(_e,_d);}`,\n );\n }\n }\n\n const sg = createSlowGen(\"_d\", \"_d\", \"[]\", \"_e\", ctx);\n // When the root schema's own shape is shared (it recurs as a sub-schema of\n // another export, or as a duplicate root), its slow walk delegates to the\n // shared function instead of emitting a second full copy. The fast path is\n // still generated inline above — only the cold walk is shared.\n const rootRef = ctx.sharedSchemas?.refFor(ir);\n const slowCode = rootRef !== undefined ? `_d=${rootRef.name}(_d,[],_e);` : generateSlow(ir, sg);\n\n const buildCode = (): string => [\"/* zod-compiler */\", ...ctx.preamble].join(\"\\n\");\n\n const functionDefParts = [`function ${fnName}(input){`];\n\n // Build Path: every mutation is modelled, so one pass can validate and\n // assemble the output together and bail on the first failure, leaving the\n // issue-producing walk deferred behind `.error` (see build-path).\n // The fast check stays out of `safeParse` entirely — running it first would\n // read every property twice — but it is still an EXACT acceptance predicate\n // (stripping reshapes the output, never the verdict), so `.is()` installs it.\n if (buildFnName !== null && ctx.buildFailName !== undefined) {\n ctx.usedHelpers.add(\"__zcFinD\");\n const built = `__bd_${ctx.counter++}`;\n // A self-recursive walk calls this validator BY NAME (slowRecursiveRef),\n // and that binding exists only inside the named function expression — so\n // there the walk stays a per-call closure. Everything else hosts it in the\n // preamble, keeping safeParse to three statements. Mirrors the same split\n // in the mutation-free branch below.\n const recursive = slowCode.includes(fnName);\n let deferred: string;\n if (recursive) {\n deferred = `__zcFinD(function(input){var _e=[];\\nvar _d=input;\\n${slowCode}\\nreturn _e;},input)`;\n } else {\n const walkName = `__sw_${ctx.counter++}`;\n ctx.preamble.push(\n `function ${walkName}(input){var _e=[];\\nvar _d=input;\\n${slowCode}\\nreturn _e;}`,\n );\n deferred = `__zcFinD(${walkName},input)`;\n }\n return {\n code: buildCode(),\n functionDef: [\n `function ${fnName}(input){`,\n `var ${built}=${buildFnName}(input);`,\n `if(${built}!==${ctx.buildFailName}){return{success:true,data:${built}};}`,\n `return ${deferred};`,\n `}`,\n ].join(\"\\n\"),\n refCount: options?.refCount ?? 0,\n usedHelpers: ctx.usedHelpers,\n // No by-reference shortcut: `data` is the freshly built object, so\n // parse() must go through safeParse rather than returning its input.\n fastFnName: null,\n // `fastTotal` qualifies `fastFnName`, which is null here; the predicate\n // travels in `isFnName` instead.\n fastTotal: false,\n isFnName: buildIsFnName,\n };\n }\n\n if (fastExpr === \"true\") {\n // Schema always succeeds (any/unknown) — skip slow path entirely\n functionDefParts.push(`return{success:true,data:input};`);\n functionDefParts.push(`}`);\n return {\n code: buildCode(),\n functionDef: functionDefParts.join(\"\\n\"),\n refCount: options?.refCount ?? 0,\n usedHelpers: ctx.usedHelpers,\n fastFnName: null,\n // any/unknown always succeed; `.is()` derives `true` from the fn fallback.\n fastTotal: false,\n };\n }\n\n if (fastExpr !== null && !hasMutation(ir) && !nestedNeedsProtoScrub(ir)) {\n // The by-reference shortcut hands back the input verbatim, which a loose or\n // catchall object — or a record — must not do while it still carries an own\n // `__proto__` (see ZC_PROTO_SCRUB_DECL). The fast check itself stays a pure\n // predicate, so `fc(input) ⟺ zod accepts` still holds and the deferred error\n // path below is untouched; only the value handed back is filtered. The cost\n // is one `hasOwnProperty` per successful parse of those shapes.\n const fastData = needsProtoScrub(ir)\n ? `${emitRuntimeHelper(ctx, \"__zcPs\", ZC_PROTO_SCRUB_DECL)}(input)`\n : \"input\";\n // Mutation-free schemas with a fast path: a fast-check failure can never\n // become a slow-path success (both are generated from the same checks —\n // unlike default/catch schemas, whose partial fast path requires value\n // presence while the slow path SUCCEEDS by applying the fallback).\n // The slow path's only output is therefore the issues array, observable\n // solely through `.error` — defer the whole re-walk into the cached\n // accessor (__zcFinD): a failed safeParse whose `.error` is never read\n // costs the fast check alone.\n //\n // The walk is HOSTED as a named preamble function rather than a per-call\n // closure, for two measured reasons: (1) a failed safeParse no longer\n // allocates a closure environment + function object before the deferral\n // even starts; (2) the safeParse body shrinks to two statements, putting\n // it within V8's inlining budget — callers in hot loops get the\n // success-path result object escape-analyzed away entirely, which the\n // old shape (slow walk inlined into the body) made impossible.\n ctx.usedHelpers.add(\"__zcFinD\");\n if (slowCode.includes(fnName)) {\n // Self-recursive slow paths call the safeParse function by NAME\n // (slowRecursiveRef) — that binding exists only inside the named\n // function expression under the documented evaluation contract\n // (`new Function(code + \"return \" + functionDef)`), so the walk stays\n // a per-call closure for recursive schemas. Recursion is the rare\n // shape; everything else gets the hosted walk.\n functionDefParts.push(\n `if(${fastExpr}){return{success:true,data:${fastData}};}`,\n `return __zcFinD(function(input){`,\n `var _e=[];`,\n `var _d=input;`,\n slowCode,\n `return _e;`,\n `},input);`,\n `}`,\n );\n } else {\n const walkName = `__sw_${ctx.counter++}`;\n ctx.preamble.push(\n `function ${walkName}(input){var _e=[];\\nvar _d=input;\\n${slowCode}\\nreturn _e;}`,\n );\n functionDefParts.push(\n `if(${fastExpr}){return{success:true,data:${fastData}};}`,\n `return __zcFinD(${walkName},input);`,\n `}`,\n );\n }\n return {\n code: buildCode(),\n functionDef: functionDefParts.join(\"\\n\"),\n refCount: options?.refCount ?? 0,\n usedHelpers: ctx.usedHelpers,\n // `fc` is a sound VERDICT here either way, but publishing it also promises\n // `parse()` may return the input — which a scrubbed output cannot (see\n // fastResultIsInput). `.is()` still gets the predicate through fastTotal.\n fastFnName: fastResultIsInput(ir) ? fastFnName : null,\n // Total predicate: mutation-free fast path, fc(input) ⟺ accepts(input).\n // generateIIFE installs fc directly as the zero-allocation `.is()`.\n fastTotal: true,\n };\n }\n\n if (fastExpr !== null && fastResultIsInput(ir)) {\n // Partial fast path (default/catch/... present-value shortcut): the slow\n // path must run eagerly — it can succeed where the fast check failed.\n //\n // Withheld when the schema rebuilds its output: there the fast check is a\n // sound VERDICT but says nothing about the payload, and `data:input` would\n // hand back the unstripped input. Such schemas reach here only when the\n // build path declined them, so the eager walk produces the output instead.\n functionDefParts.push(`if(${fastExpr}){return{success:true,data:input};}`);\n }\n\n // Success branch inlined at the call site instead of inside __zcFin: the\n // eager path (mutation schemas — coerce/default/trim/transform) returns\n // here on EVERY parse, and the inline literal keeps the hot exit free of a\n // cross-function call; __zcFin is reached only on failure.\n functionDefParts.push(\n `var _e=[];`,\n `var _d=input;`,\n slowCode,\n `if(_e.length===0){return{success:true,data:_d};}`,\n `return __zcFin(_e,_d);`,\n `}`,\n );\n\n const functionDef = functionDefParts.join(\"\\n\");\n\n return {\n code: buildCode(),\n functionDef,\n refCount: options?.refCount ?? 0,\n usedHelpers: ctx.usedHelpers,\n // `fc` carries a stronger contract than \"accepts\": `__zcMkv` returns the\n // INPUT from `parse()`/`parseAsync()`/`~standard` whenever it holds, so it\n // may only be published when a passing check implies `data === input`. A\n // rebuilding schema breaks that even though its safeParse is correct, and so\n // does a union whose options can rewrite — see `fastResultIsInput` for both.\n // Same guard as the `data: input` shortcut above, which is the other reader\n // of the same contract.\n fastFnName: fastResultIsInput(ir) ? fastFnName : null,\n // Partial fast path (default/catch) or none (including coercion): a false fc\n // result does not imply rejection, so `.is()` derives from\n // safeParse(input).success.\n fastTotal: false,\n };\n}\n\n/**\n * Find every non-root recursion target (a `recursionTarget` node, refId ≥ 1)\n * reachable from `root`, mapping refId → the inner IR to host as a standalone\n * validator. The root target (refId 0) is the schema's own function and is\n * never wrapped, so it never appears here. The same target may be wrapped at\n * several sites (a recursive schema reached from sibling positions); the first\n * inner wins — they are structurally identical extractions of one schema.\n */\nfunction collectRecursionTargets(root: SchemaIR): Map<number, SchemaIR> {\n const out = new Map<number, SchemaIR>();\n const seen = new Set<SchemaIR>();\n const walk = (ir: SchemaIR): void => {\n if (seen.has(ir)) return;\n seen.add(ir);\n if (ir.type === \"recursionTarget\" && !out.has(ir.refId)) {\n out.set(ir.refId, ir.inner);\n }\n for (const child of childIRs(ir)) walk(child);\n };\n walk(root);\n return out;\n}\n\n/** Direct child SchemaIR nodes, covering every node type (including the new wrapper). */\nfunction childIRs(ir: SchemaIR): readonly SchemaIR[] {\n switch (ir.type) {\n case \"object\":\n return 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"],"mappings":";;;;;;;;;;;;;;;AA+DA,SAAgB,kBACd,IACA,MACA,SACe;CACf,MAAM,SAAS,aAAa;CAC5B,MAAM,OAAoB,SAAS,QAAQ;CAC3C,MAAM,MAAsB;EAC1B,UAAU,CAAC;EACX,SAAS;EACT;EACA,4BAAY,IAAI,IAAI;EACpB;EACA,6BAAa,IAAI,IAAI;EACrB,YAAY,SAAS;EACrB,qBAAqB,SAAS;CAChC;CAMA,IAAI,SAAS,kBAAkB,KAAA,GAC7B,IAAI,gBAAgB,QAAQ;CAS9B,IAAI,GAAG,SAAS,cAAc,GAAG,aAAa,KAAA,GAAW;EACvD,MAAM,WAAW,eAAe,KAAK,GAAG,QAAQ;EAChD,OAAO;GACL,MAAM,CAAC,sBAAsB,GAAG,IAAI,QAAQ,CAAC,CAAC,KAAK,IAAI;GACvD,aAAa,YAAY,OAAO,iBAAiB,SAAS;GAC1D,UAAU,SAAS,YAAY;GAC/B,aAAa,IAAI;GACjB,YAAY;GACZ,WAAW;EACb;CACF;CAUA,MAAM,iBAAiB,wBAAwB,EAAE;CACjD,IAAI,6BAAa,IAAI,IAA0B,CAAC,CAAC,GAAG;EAAE,QAAQ;EAAM,UAAU;CAAO,CAAC,CAAC,CAAC;CACxF,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ACL,KAAK;EACL,KAAK,eACH,OAAO,CAAC,GAAG,KAAK;EAClB,KAAK,QACH,OAAO,CAAC,GAAG,IAAI,GAAG,GAAG;EACvB,SACE,OAAO,CAAC;CACZ;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recursive-ref.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/recursive-ref.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"recursive-ref.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/recursive-ref.ts"],"mappings":";;;iBA2DgB,iBAAiB,IAAI,gBAAgB,GAAG;iBAIxC,iBAAiB,IAAI,gBAAgB,GAAG;;;;;;iBASxC,oBAAoB,IAAI,mBAAmB,GAAG;iBAI9C,oBAAoB,IAAI,mBAAmB,GAAG"}
|
|
@@ -40,6 +40,7 @@ function slowRecursionCall(refId, g) {
|
|
|
40
40
|
*/
|
|
41
41
|
function fastRecursionCall(refId, g) {
|
|
42
42
|
const ctx = g.ctx;
|
|
43
|
+
if (ctx.fastRecursionDisabled) return null;
|
|
43
44
|
const t = ctx.recTargets?.get(refId ?? 0);
|
|
44
45
|
if (!t || t.isRoot) {
|
|
45
46
|
ctx.recFastName ??= `__fcr_${ctx.counter++}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recursive-ref.js","names":[],"sources":["../../../../src/core/codegen/schemas/recursive-ref.ts"],"sourcesContent":["import type { RecursionTargetIR, RecursiveRefIR } from \"../../types.js\";\nimport type { CodeGenContext, FastGen, SlowGen } from \"../context.js\";\nimport { emit } from \"../emit.js\";\n\n/**\n * Resolve the slow (safeParse-shaped) validator name for a recursion target.\n * refId 0 / no table ⇒ the root, which is the schema's own `safeParse_<name>`.\n */\nfunction slowTargetName(ctx: CodeGenContext, refId: number | undefined): string {\n const t = ctx.recTargets?.get(refId ?? 0);\n return t && !t.isRoot ? t.slowName : ctx.fnName;\n}\n\n/**\n * Emit a recursion call on the slow (issue-collecting) path: invoke the hosted\n * validator for the target shape, then either merge its issues with the current\n * path prefix or write back its (possibly mutated) data. Shared by both the\n * back-edge (`recursiveRef`) and the in-place target site (`recursionTarget`).\n */\nfunction slowRecursionCall(refId: number | undefined, g: SlowGen): string {\n const fn = slowTargetName(g.ctx, refId);\n const n = g.ctx.counter++;\n const rVar = `__rec_r${n}`;\n const iVar = `__rec_i${n}`;\n const jVar = `__rec_j${n}`;\n return `${emit`\n var ${rVar}=${fn}(${g.input});\n if(!${rVar}.success){\n var ${iVar}=${rVar}.error.issues;\n for(var ${jVar}=0;${jVar}<${iVar}.length;${jVar}++){\n ${g.issues}.push({...${iVar}[${jVar}],\n path:${g.path}.concat(${iVar}[${jVar}].path)});\n }\n }else{\n ${g.output}=${rVar}.data;\n }\n `}\\n`;\n}\n\n/**\n * Resolve the fast (boolean) validator name for a recursion target, allocating\n * the root's lazily (mirrors the historical single-target behavior). Returns a\n * call expression on the target's hosted fast-check.\n */\nfunction fastRecursionCall(refId: number | undefined, g: FastGen): string {\n const ctx = g.ctx;\n const t = ctx.recTargets?.get(refId ?? 0);\n if (!t || t.isRoot) {\n // Root recursion (refId 0, or a standalone generator call with no table):\n // the root fast expression is hosted under this name by generateValidator.\n ctx.recFastName ??= `__fcr_${ctx.counter++}`;\n if (t) t.fastName = ctx.recFastName;\n return `${ctx.recFastName}(${g.input})`;\n }\n // Non-root target: name pre-allocated by generateValidator before the walk.\n return `${t.fastName}(${g.input})`;\n}\n\nexport function slowRecursiveRef(ir: RecursiveRefIR, g: SlowGen): string {\n return slowRecursionCall(ir.refId, g);\n}\n\nexport function fastRecursiveRef(ir: RecursiveRefIR, g: FastGen): string | null {\n return fastRecursionCall(ir.refId, g);\n}\n\n/**\n * In-place site of a non-root recursion target (the recursive sub-schema where\n * it sits in the larger tree). Validating it = calling its hosted validator,\n * exactly like a back-edge, so both reuse the recursion-call emitters.\n */\nexport function slowRecursionTarget(ir: RecursionTargetIR, g: SlowGen): string {\n return slowRecursionCall(ir.refId, g);\n}\n\nexport function fastRecursionTarget(ir: RecursionTargetIR, g: FastGen): string | null {\n return fastRecursionCall(ir.refId, g);\n}\n"],"mappings":";;;;;;AAQA,SAAS,eAAe,KAAqB,OAAmC;CAC9E,MAAM,IAAI,IAAI,YAAY,IAAI,SAAS,CAAC;CACxC,OAAO,KAAK,CAAC,EAAE,SAAS,EAAE,WAAW,IAAI;AAC3C;;;;;;;AAQA,SAAS,kBAAkB,OAA2B,GAAoB;CACxE,MAAM,KAAK,eAAe,EAAE,KAAK,KAAK;CACtC,MAAM,IAAI,EAAE,IAAI;CAChB,MAAM,OAAO,UAAU;CACvB,MAAM,OAAO,UAAU;CACvB,MAAM,OAAO,UAAU;CACvB,OAAO,GAAG,IAAI;UACN,KAAK,GAAG,GAAG,GAAG,EAAE,MAAM;UACtB,KAAK;YACH,KAAK,GAAG,KAAK;gBACT,KAAK,KAAK,KAAK,GAAG,KAAK,UAAU,KAAK;UAC5C,EAAE,OAAO,YAAY,KAAK,GAAG,KAAK;iBAC3B,EAAE,KAAK,UAAU,KAAK,GAAG,KAAK;;;QAGvC,EAAE,OAAO,GAAG,KAAK;;IAErB;AACJ;;;;;;AAOA,SAAS,kBAAkB,OAA2B,
|
|
1
|
+
{"version":3,"file":"recursive-ref.js","names":[],"sources":["../../../../src/core/codegen/schemas/recursive-ref.ts"],"sourcesContent":["import type { RecursionTargetIR, RecursiveRefIR } from \"../../types.js\";\nimport type { CodeGenContext, FastGen, SlowGen } from \"../context.js\";\nimport { emit } from \"../emit.js\";\n\n/**\n * Resolve the slow (safeParse-shaped) validator name for a recursion target.\n * refId 0 / no table ⇒ the root, which is the schema's own `safeParse_<name>`.\n */\nfunction slowTargetName(ctx: CodeGenContext, refId: number | undefined): string {\n const t = ctx.recTargets?.get(refId ?? 0);\n return t && !t.isRoot ? t.slowName : ctx.fnName;\n}\n\n/**\n * Emit a recursion call on the slow (issue-collecting) path: invoke the hosted\n * validator for the target shape, then either merge its issues with the current\n * path prefix or write back its (possibly mutated) data. Shared by both the\n * back-edge (`recursiveRef`) and the in-place target site (`recursionTarget`).\n */\nfunction slowRecursionCall(refId: number | undefined, g: SlowGen): string {\n const fn = slowTargetName(g.ctx, refId);\n const n = g.ctx.counter++;\n const rVar = `__rec_r${n}`;\n const iVar = `__rec_i${n}`;\n const jVar = `__rec_j${n}`;\n return `${emit`\n var ${rVar}=${fn}(${g.input});\n if(!${rVar}.success){\n var ${iVar}=${rVar}.error.issues;\n for(var ${jVar}=0;${jVar}<${iVar}.length;${jVar}++){\n ${g.issues}.push({...${iVar}[${jVar}],\n path:${g.path}.concat(${iVar}[${jVar}].path)});\n }\n }else{\n ${g.output}=${rVar}.data;\n }\n `}\\n`;\n}\n\n/**\n * Resolve the fast (boolean) validator name for a recursion target, allocating\n * the root's lazily (mirrors the historical single-target behavior). Returns a\n * call expression on the target's hosted fast-check.\n */\nfunction fastRecursionCall(refId: number | undefined, g: FastGen): string | null {\n const ctx = g.ctx;\n if (ctx.fastRecursionDisabled) return null;\n const t = ctx.recTargets?.get(refId ?? 0);\n if (!t || t.isRoot) {\n // Root recursion (refId 0, or a standalone generator call with no table):\n // the root fast expression is hosted under this name by generateValidator.\n ctx.recFastName ??= `__fcr_${ctx.counter++}`;\n if (t) t.fastName = ctx.recFastName;\n return `${ctx.recFastName}(${g.input})`;\n }\n // Non-root target: name pre-allocated by generateValidator before the walk.\n return `${t.fastName}(${g.input})`;\n}\n\nexport function slowRecursiveRef(ir: RecursiveRefIR, g: SlowGen): string {\n return slowRecursionCall(ir.refId, g);\n}\n\nexport function fastRecursiveRef(ir: RecursiveRefIR, g: FastGen): string | null {\n return fastRecursionCall(ir.refId, g);\n}\n\n/**\n * In-place site of a non-root recursion target (the recursive sub-schema where\n * it sits in the larger tree). Validating it = calling its hosted validator,\n * exactly like a back-edge, so both reuse the recursion-call emitters.\n */\nexport function slowRecursionTarget(ir: RecursionTargetIR, g: SlowGen): string {\n return slowRecursionCall(ir.refId, g);\n}\n\nexport function fastRecursionTarget(ir: Recurs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