zod-compiler 1.23.3 → 1.23.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +23 -13
  2. package/dist/core/codegen/build-path.d.ts.map +1 -1
  3. package/dist/core/codegen/build-path.js +3 -1
  4. package/dist/core/codegen/build-path.js.map +1 -1
  5. package/dist/core/codegen/context.d.ts.map +1 -1
  6. package/dist/core/codegen/context.js +4 -2
  7. package/dist/core/codegen/context.js.map +1 -1
  8. package/dist/core/codegen/dedupe.js +4 -1
  9. package/dist/core/codegen/dedupe.js.map +1 -1
  10. package/dist/core/codegen/fast-path.d.ts.map +1 -1
  11. package/dist/core/codegen/fast-path.js +4 -0
  12. package/dist/core/codegen/fast-path.js.map +1 -1
  13. package/dist/core/codegen/fast-size.d.ts.map +1 -1
  14. package/dist/core/codegen/fast-size.js +4 -1
  15. package/dist/core/codegen/fast-size.js.map +1 -1
  16. package/dist/core/codegen/index.js +18 -1
  17. package/dist/core/codegen/index.js.map +1 -1
  18. package/dist/core/codegen/issue-decls.d.ts +7 -1
  19. package/dist/core/codegen/issue-decls.d.ts.map +1 -1
  20. package/dist/core/codegen/issue-decls.js +8 -1
  21. package/dist/core/codegen/issue-decls.js.map +1 -1
  22. package/dist/core/codegen/schemas/custom.d.ts +10 -0
  23. package/dist/core/codegen/schemas/custom.d.ts.map +1 -0
  24. package/dist/core/codegen/schemas/custom.js +17 -0
  25. package/dist/core/codegen/schemas/custom.js.map +1 -0
  26. package/dist/core/codegen/schemas/fallback.d.ts +3 -1
  27. package/dist/core/codegen/schemas/fallback.d.ts.map +1 -1
  28. package/dist/core/codegen/schemas/fallback.js +23 -20
  29. package/dist/core/codegen/schemas/fallback.js.map +1 -1
  30. package/dist/core/codegen/schemas/zod-delegate.d.ts +12 -0
  31. package/dist/core/codegen/schemas/zod-delegate.d.ts.map +1 -0
  32. package/dist/core/codegen/schemas/zod-delegate.js +14 -0
  33. package/dist/core/codegen/schemas/zod-delegate.js.map +1 -0
  34. package/dist/core/codegen/slow-path.d.ts.map +1 -1
  35. package/dist/core/codegen/slow-path.js +5 -1
  36. package/dist/core/codegen/slow-path.js.map +1 -1
  37. package/dist/core/diagnostic.d.ts.map +1 -1
  38. package/dist/core/diagnostic.js +3 -0
  39. package/dist/core/diagnostic.js.map +1 -1
  40. package/dist/core/extract/extractors/custom.d.ts +12 -0
  41. package/dist/core/extract/extractors/custom.d.ts.map +1 -0
  42. package/dist/core/extract/extractors/custom.js +35 -0
  43. package/dist/core/extract/extractors/custom.js.map +1 -0
  44. package/dist/core/extract/extractors/intersection.d.ts.map +1 -1
  45. package/dist/core/extract/extractors/intersection.js +32 -0
  46. package/dist/core/extract/extractors/intersection.js.map +1 -1
  47. package/dist/core/extract/registry.d.ts +2 -0
  48. package/dist/core/extract/registry.d.ts.map +1 -1
  49. package/dist/core/extract/registry.js +2 -0
  50. package/dist/core/extract/registry.js.map +1 -1
  51. package/dist/core/extract/types.d.ts +7 -1
  52. package/dist/core/extract/types.d.ts.map +1 -1
  53. package/dist/core/iife.d.ts +3 -4
  54. package/dist/core/iife.d.ts.map +1 -1
  55. package/dist/core/iife.js +3 -4
  56. package/dist/core/iife.js.map +1 -1
  57. package/dist/core/types.d.ts +28 -2
  58. package/dist/core/types.d.ts.map +1 -1
  59. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"dedupe.js","names":[],"sources":["../../../src/core/codegen/dedupe.ts"],"sourcesContent":["/**\n * File-level schema deduplication.\n *\n * When several schemas in one file share structurally identical sub-trees\n * (a reused `Address` object, a `{ id, name }` row, an exported schema that is\n * also embedded in another), the error-collecting \"slow walk\" for that shape\n * is generated ONCE as a shared `__zcSw_N(input, path, issues)` function and\n * every occurrence calls it instead of inlining a fresh copy.\n *\n * Two invariants keep this free of runtime cost and footguns:\n *\n * 1. **Slow walk only.** The fast path (the `&&` boolean chain that validates\n * valid input with zero allocations) is NEVER shared — it stays fully\n * inlined so the hot path is byte-for-byte what it was before. Only the\n * cold, bulky error walk (64–77% of generated bytes) is shared.\n *\n * 2. **No per-export references.** A shared body lives at MODULE scope, while\n * `__rf[]` — the array of retained Zod schemas and captured callbacks — is\n * declared inside each export's IIFE. So a shape may be shared only when\n * nothing in it resolves through `__rf`: no `default`, `catch`, `fallback`,\n * captured `transform`, or captured `refine`/`superRefine`. Zero-capture\n * callbacks are fine — they are hosted from source text into the shared\n * block's own preamble.\n *\n * Sharing used to additionally require the whole ROOT to be mutation-free, so\n * that a body which wrote nothing back could not lose an output value. That\n * excluded a genuine `z.object()` — it strips, so its walk PRODUCES a rebuilt\n * object — which, once `z.object()` began always stripping, meant the feature\n * stopped firing for essentially every real schema: a realistic module of four\n * schemas reusing two sub-shapes shared nothing and shipped 29.6 KB where the\n * `strictObject` spelling of the same thing shipped 16.7 KB.\n *\n * The write-back problem is solved directly instead: a shared walk RETURNS its\n * value and call sites assign it (`slot = __zcSw_N(slot, path, issues)`), so a\n * stripping object, a coercion or a `.trim()` delivers its rewritten value\n * through the call exactly as an inlined walk delivers it through `g.output`.\n */\n\nimport type { SchemaIR } from \"../types.js\";\nimport type { CodeGenContext, CodegenMode } from \"./context.js\";\nimport { createSlowGen, generateSlow } from \"./slow-path.js\";\n\n/** A shared slow-walk validator hosted at module scope. */\nexport interface SharedSchemaRef {\n /** Name of the `function __zcSw_N(input, path, issues)` declaration. */\n readonly name: string;\n}\n\nexport interface SharedSchemaPlan {\n /**\n * Shared ref for an IR node, or undefined when the node is not a shared\n * candidate. Keyed by structural identity (memoized), so repeated lookups\n * during codegen are O(1).\n */\n refFor(ir: SchemaIR): SharedSchemaRef | undefined;\n /** Module-scope declarations (shared preamble + `__zcSw_N` functions). `\"\"` when empty. */\n readonly code: string;\n /** Runtime helper names referenced by the shared block (lean mode). */\n readonly usedHelpers: Set<string>;\n readonly isEmpty: boolean;\n}\n\n/**\n * Minimum subtree weight (≈ node count, +1 per check) for a repeated shape to\n * be worth a shared function. Below this the call + dynamic-path overhead\n * outweighs the duplicated inline walk; ~4 admits a 3-field object or an\n * array-of-object while skipping bare primitives and thin wrappers.\n */\nconst MIN_SHARED_WEIGHT = 4;\n\n/** Leading marker of a shared block; used to skip re-injection on watch/HMR re-runs. */\nexport const SHARED_BLOCK_MARKER = \"/* zod-compiler shared */\";\n\nconst EMPTY_PLAN: SharedSchemaPlan = {\n refFor: () => undefined,\n code: \"\",\n usedHelpers: new Set(),\n isEmpty: true,\n};\n\n/**\n * Build the shared-schema plan for one file's root schemas. Returns\n * {@link EMPTY_PLAN} (a no-op) when nothing repeats — the common case, so files\n * without internal duplication pay only a single linear analysis pass.\n */\nexport function createSharedSchemaPlan(\n roots: readonly SchemaIR[],\n mode: CodegenMode,\n): SharedSchemaPlan {\n const keyMemo = new Map<SchemaIR, string>();\n const weightMemo = new Map<SchemaIR, number>();\n const stats = new Map<string, { ir: SchemaIR; count: number; weight: number }>();\n\n for (const root of roots) {\n collect(root, keyMemo, weightMemo, stats);\n }\n\n const selected = [...stats.values()]\n .filter(\n (c) =>\n c.count >= 2 &&\n c.weight >= MIN_SHARED_WEIGHT &&\n !containsRecursiveRef(c.ir) &&\n !referencesExportRefs(c.ir),\n )\n // Largest shapes first so the biggest wins get the lowest indices; tie-break\n // on the structural key for deterministic, reproducible output.\n .sort((a, b) => b.weight - a.weight || cmp(keyOf(a.ir, keyMemo), keyOf(b.ir, keyMemo)));\n\n if (selected.length === 0) return EMPTY_PLAN;\n\n const refs = new Map<string, SharedSchemaRef>();\n selected.forEach((c, i) => refs.set(keyOf(c.ir, keyMemo), { name: `__zcSw_${i}` }));\n\n const refFor = (ir: SchemaIR): SharedSchemaRef | undefined => refs.get(keyOf(ir, keyMemo));\n\n const ctx: CodeGenContext = {\n preamble: [],\n counter: 0,\n fnName: \"__zcShared\",\n regexCache: new Map(),\n mode,\n usedHelpers: new Set(),\n };\n // Generation consults the plan so a shared candidate nested inside another\n // shared candidate becomes a `__zcSw_*` call rather than a second inline copy.\n // Containment is strictly size-decreasing, so the shared functions form a DAG;\n // hoisted declarations make call order irrelevant.\n ctx.sharedSchemas = { refFor, code: \"\", usedHelpers: ctx.usedHelpers, isEmpty: false };\n\n const fns: string[] = [];\n for (const c of selected) {\n const ref = refs.get(keyOf(c.ir, keyMemo));\n if (ref === undefined) continue;\n // Generate the candidate's body INLINE (the root is passed to generateSlow,\n // not visit(), so it never replaces itself with a call); only its children\n // route through visit() and may resolve to other shared refs.\n const body = generateSlow(c.ir, createSlowGen(\"input\", \"input\", \"path\", \"_e\", ctx));\n // `input` is both the read and the write slot (createSlowGen above passes it\n // as input AND output), so a walk that rewrites — a stripping object, a\n // coercion, an overwrite check — leaves its result there. Returning it is\n // what lets the caller receive that value; a walk that rewrites nothing\n // returns its argument unchanged.\n fns.push(`function ${ref.name}(input,path,_e){\\n${body}\\nreturn input;\\n}`);\n }\n\n return {\n refFor,\n code: [SHARED_BLOCK_MARKER, ...ctx.preamble, ...fns].join(\"\\n\"),\n usedHelpers: ctx.usedHelpers,\n isEmpty: false,\n };\n}\n\n// A shared sub-schema is called as `slot = __zcSw_N(slot, path, issues)`: the\n// walk pushes directly into the caller's `issues` array (no result object, no\n// per-call issue copy) and returns the parsed value, which the call site assigns\n// back into the slot the inlined walk would have written. Call sites are emitted\n// by slow-path.ts (nested occurrences) and index.ts (a shared root), keyed off\n// `ref.name`.\n\n/**\n * Does the subtree resolve anything through the per-export `__rf[]` array —\n * a retained Zod schema (`default`, `catch`, `fallback`) or a captured callback\n * (`transform`, `refine`, `superRefine`)?\n *\n * Those names exist only inside an export's own IIFE, so a module-scope shared\n * body referencing them would be unbound. A zero-capture callback carries\n * `source` instead of `refIndex` and is hosted into the shared block's preamble,\n * so it does not disqualify a shape.\n */\nfunction referencesExportRefs(ir: SchemaIR): boolean {\n switch (ir.type) {\n case \"default\":\n case \"catch\":\n case \"fallback\":\n // `refIndex` is mandatory on these — the value/schema lives on the export.\n return true;\n case \"effect\":\n if (ir.refIndex !== undefined) return true;\n break;\n case \"string\":\n case \"number\":\n case \"object\":\n case \"array\":\n if (ir.checks?.some((c) => \"refIndex\" in c && c.refIndex !== undefined)) return true;\n break;\n default:\n break;\n }\n return childSchemas(ir).some(referencesExportRefs);\n}\n\n// ─── Candidate collection ────────────────────────────────────────────────────\n\nfunction collect(\n ir: SchemaIR,\n keyMemo: Map<SchemaIR, string>,\n weightMemo: Map<SchemaIR, number>,\n stats: Map<string, { ir: SchemaIR; count: number; weight: number }>,\n): void {\n const key = keyOf(ir, keyMemo);\n const existing = stats.get(key);\n if (existing) {\n existing.count++;\n } else {\n stats.set(key, { ir, count: 1, weight: weightOf(ir, weightMemo) });\n }\n for (const child of childSchemas(ir)) collect(child, keyMemo, weightMemo, stats);\n}\n\n/** Direct child SchemaIR nodes (the structural recursion shared by every pass). */\nfunction childSchemas(ir: SchemaIR): 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 return [ir.inner];\n case \"pipe\":\n return [ir.in, ir.out];\n case \"effect\":\n case \"recursionTarget\":\n return [ir.inner];\n default:\n return [];\n }\n}\n\n/** Subtree weight ≈ node count plus one per check; memoized for O(total) cost. */\nfunction weightOf(ir: SchemaIR, memo: Map<SchemaIR, number>): number {\n const hit = memo.get(ir);\n if (hit !== undefined) return hit;\n const checks = (ir as { checks?: readonly unknown[] }).checks;\n let weight = 1 + (Array.isArray(checks) ? checks.length : 0);\n for (const child of childSchemas(ir)) weight += weightOf(child, memo);\n memo.set(ir, weight);\n return weight;\n}\n\nfunction containsRecursiveRef(ir: SchemaIR): boolean {\n if (ir.type === \"recursiveRef\") return true;\n return childSchemas(ir).some(containsRecursiveRef);\n}\n\n// ─── Structural keys ─────────────────────────────────────────────────────────\n\n/**\n * Stable structural key for an IR node, memoized by node identity so each\n * subtree is serialized exactly once (the whole pass is O(total nodes), not\n * O(nodes × depth)). Two nodes share a key iff they are structurally identical\n * — including every check, literal value, and error message — so deduplicated\n * schemas produce byte-identical validation and issues.\n */\nfunction keyOf(ir: SchemaIR, memo: Map<SchemaIR, string>): string {\n const hit = memo.get(ir);\n if (hit !== undefined) return hit;\n const obj = ir as unknown as Record<string, unknown>;\n const key = `{${Object.keys(obj)\n .filter((k) => obj[k] !== undefined)\n .sort()\n .map((k) => `${k}:${encodeValue(obj[k], memo)}`)\n .join(\",\")}}`;\n memo.set(ir, key);\n return key;\n}\n\n/**\n * Encode any IR field value. A nested SchemaIR is detected by a string `type`\n * field (checks carry `kind`, union `cases` carry `value`/`option` — only real\n * schema nodes have `type`) and routed through {@link keyOf} for subtree\n * memoization; everything else is serialized in sorted-key order.\n */\nfunction encodeValue(value: unknown, memo: Map<SchemaIR, string>): string {\n if (typeof value === \"bigint\") return `#${value}`;\n if (value === null) return \"null\";\n // Non-finite numbers must stay distinct: JSON.stringify maps Infinity, -Infinity\n // and NaN all to \"null\", which would merge e.g. .min(Infinity) with .min(NaN).\n if (typeof value === \"number\" && !Number.isFinite(value)) return `n!${value}`;\n if (Array.isArray(value)) return `[${value.map((v) => encodeValue(v, memo)).join(\",\")}]`;\n if (typeof value === \"object\") {\n if (typeof (value as { type?: unknown }).type === \"string\") {\n return keyOf(value as SchemaIR, memo);\n }\n const obj = value as Record<string, unknown>;\n return `{${Object.keys(obj)\n .filter((k) => obj[k] !== undefined)\n .sort()\n .map((k) => `${k}:${encodeValue(obj[k], memo)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"undefined\";\n}\n\nfunction cmp(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n"],"mappings":";;;;;;;;AAoEA,MAAM,oBAAoB;;AAG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OAAO,IAAI;CAC1C,IAAI,UAAU,MAAM,OAAO;CAG3B,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,GAAG,OAAO,KAAK;CACtE,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,IAAI,MAAM,KAAK,MAAM,YAAY,GAAG,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;CACtF,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,OAAQ,MAA6B,SAAS,UAChD,OAAO,MAAM,OAAmB,IAAI;EAEtC,MAAM,MAAM;EACZ,OAAO,IAAI,OAAO,KAAK,GAAG,CAAC,CACxB,QAAQ,MAAM,IAAI,OAAO,KAAA,CAAS,CAAC,CACnC,KAAK,CAAC,CACN,KAAK,MAAM,GAAG,EAAE,GAAG,YAAY,IAAI,IAAI,IAAI,GAAG,CAAC,CAC/C,KAAK,GAAG,EAAE;CACf;CACA,OAAO,KAAK,UAAU,KAAK,KAAK;AAClC;AAEA,SAAS,IAAI,GAAW,GAAmB;CACzC,OAAO,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI;AAClC"}
1
+ {"version":3,"file":"dedupe.js","names":[],"sources":["../../../src/core/codegen/dedupe.ts"],"sourcesContent":["/**\n * File-level schema deduplication.\n *\n * When several schemas in one file share structurally identical sub-trees\n * (a reused `Address` object, a `{ id, name }` row, an exported schema that is\n * also embedded in another), the error-collecting \"slow walk\" for that shape\n * is generated ONCE as a shared `__zcSw_N(input, path, issues)` function and\n * every occurrence calls it instead of inlining a fresh copy.\n *\n * Two invariants keep this free of runtime cost and footguns:\n *\n * 1. **Slow walk only.** The fast path (the `&&` boolean chain that validates\n * valid input with zero allocations) is NEVER shared — it stays fully\n * inlined so the hot path is byte-for-byte what it was before. Only the\n * cold, bulky error walk (64–77% of generated bytes) is shared.\n *\n * 2. **No per-export references.** A shared body lives at MODULE scope, while\n * `__rf[]` — the array of retained Zod schemas and captured callbacks — is\n * declared inside each export's IIFE. So a shape may be shared only when\n * nothing in it resolves through `__rf`: no `default`, `catch`, `fallback`,\n * captured `transform`, or captured `refine`/`superRefine`. Zero-capture\n * callbacks are fine — they are hosted from source text into the shared\n * block's own preamble.\n *\n * Sharing used to additionally require the whole ROOT to be mutation-free, so\n * that a body which wrote nothing back could not lose an output value. That\n * excluded a genuine `z.object()` — it strips, so its walk PRODUCES a rebuilt\n * object — which, once `z.object()` began always stripping, meant the feature\n * stopped firing for essentially every real schema: a realistic module of four\n * schemas reusing two sub-shapes shared nothing and shipped 29.6 KB where the\n * `strictObject` spelling of the same thing shipped 16.7 KB.\n *\n * The write-back problem is solved directly instead: a shared walk RETURNS its\n * value and call sites assign it (`slot = __zcSw_N(slot, path, issues)`), so a\n * stripping object, a coercion or a `.trim()` delivers its rewritten value\n * through the call exactly as an inlined walk delivers it through `g.output`.\n */\n\nimport type { SchemaIR } from \"../types.js\";\nimport type { CodeGenContext, CodegenMode } from \"./context.js\";\nimport { createSlowGen, generateSlow } from \"./slow-path.js\";\n\n/** A shared slow-walk validator hosted at module scope. */\nexport interface SharedSchemaRef {\n /** Name of the `function __zcSw_N(input, path, issues)` declaration. */\n readonly name: string;\n}\n\nexport interface SharedSchemaPlan {\n /**\n * Shared ref for an IR node, or undefined when the node is not a shared\n * candidate. Keyed by structural identity (memoized), so repeated lookups\n * during codegen are O(1).\n */\n refFor(ir: SchemaIR): SharedSchemaRef | undefined;\n /** Module-scope declarations (shared preamble + `__zcSw_N` functions). `\"\"` when empty. */\n readonly code: string;\n /** Runtime helper names referenced by the shared block (lean mode). */\n readonly usedHelpers: Set<string>;\n readonly isEmpty: boolean;\n}\n\n/**\n * Minimum subtree weight (≈ node count, +1 per check) for a repeated shape to\n * be worth a shared function. Below this the call + dynamic-path overhead\n * outweighs the duplicated inline walk; ~4 admits a 3-field object or an\n * array-of-object while skipping bare primitives and thin wrappers.\n */\nconst MIN_SHARED_WEIGHT = 4;\n\n/** Leading marker of a shared block; used to skip re-injection on watch/HMR re-runs. */\nexport const SHARED_BLOCK_MARKER = \"/* zod-compiler shared */\";\n\nconst EMPTY_PLAN: SharedSchemaPlan = {\n refFor: () => undefined,\n code: \"\",\n usedHelpers: new Set(),\n isEmpty: true,\n};\n\n/**\n * Build the shared-schema plan for one file's root schemas. Returns\n * {@link EMPTY_PLAN} (a no-op) when nothing repeats — the common case, so files\n * without internal duplication pay only a single linear analysis pass.\n */\nexport function createSharedSchemaPlan(\n roots: readonly SchemaIR[],\n mode: CodegenMode,\n): SharedSchemaPlan {\n const keyMemo = new Map<SchemaIR, string>();\n const weightMemo = new Map<SchemaIR, number>();\n const stats = new Map<string, { ir: SchemaIR; count: number; weight: number }>();\n\n for (const root of roots) {\n collect(root, keyMemo, weightMemo, stats);\n }\n\n const selected = [...stats.values()]\n .filter(\n (c) =>\n c.count >= 2 &&\n c.weight >= MIN_SHARED_WEIGHT &&\n !containsRecursiveRef(c.ir) &&\n !referencesExportRefs(c.ir),\n )\n // Largest shapes first so the biggest wins get the lowest indices; tie-break\n // on the structural key for deterministic, reproducible output.\n .sort((a, b) => b.weight - a.weight || cmp(keyOf(a.ir, keyMemo), keyOf(b.ir, keyMemo)));\n\n if (selected.length === 0) return EMPTY_PLAN;\n\n const refs = new Map<string, SharedSchemaRef>();\n selected.forEach((c, i) => refs.set(keyOf(c.ir, keyMemo), { name: `__zcSw_${i}` }));\n\n const refFor = (ir: SchemaIR): SharedSchemaRef | undefined => refs.get(keyOf(ir, keyMemo));\n\n const ctx: CodeGenContext = {\n preamble: [],\n counter: 0,\n fnName: \"__zcShared\",\n regexCache: new Map(),\n mode,\n usedHelpers: new Set(),\n };\n // Generation consults the plan so a shared candidate nested inside another\n // shared candidate becomes a `__zcSw_*` call rather than a second inline copy.\n // Containment is strictly size-decreasing, so the shared functions form a DAG;\n // hoisted declarations make call order irrelevant.\n ctx.sharedSchemas = { refFor, code: \"\", usedHelpers: ctx.usedHelpers, isEmpty: false };\n\n const fns: string[] = [];\n for (const c of selected) {\n const ref = refs.get(keyOf(c.ir, keyMemo));\n if (ref === undefined) continue;\n // Generate the candidate's body INLINE (the root is passed to generateSlow,\n // not visit(), so it never replaces itself with a call); only its children\n // route through visit() and may resolve to other shared refs.\n const body = generateSlow(c.ir, createSlowGen(\"input\", \"input\", \"path\", \"_e\", ctx));\n // `input` is both the read and the write slot (createSlowGen above passes it\n // as input AND output), so a walk that rewrites — a stripping object, a\n // coercion, an overwrite check — leaves its result there. Returning it is\n // what lets the caller receive that value; a walk that rewrites nothing\n // returns its argument unchanged.\n fns.push(`function ${ref.name}(input,path,_e){\\n${body}\\nreturn input;\\n}`);\n }\n\n return {\n refFor,\n code: [SHARED_BLOCK_MARKER, ...ctx.preamble, ...fns].join(\"\\n\"),\n usedHelpers: ctx.usedHelpers,\n isEmpty: false,\n };\n}\n\n// A shared sub-schema is called as `slot = __zcSw_N(slot, path, issues)`: the\n// walk pushes directly into the caller's `issues` array (no result object, no\n// per-call issue copy) and returns the parsed value, which the call site assigns\n// back into the slot the inlined walk would have written. Call sites are emitted\n// by slow-path.ts (nested occurrences) and index.ts (a shared root), keyed off\n// `ref.name`.\n\n/**\n * Does the subtree resolve anything through the per-export `__rf[]` array —\n * a retained Zod schema (`default`, `catch`, `fallback`) or a captured callback\n * (`transform`, `refine`, `superRefine`)?\n *\n * Those names exist only inside an export's own IIFE, so a module-scope shared\n * body referencing them would be unbound. A zero-capture callback carries\n * `source` instead of `refIndex` and is hosted into the shared block's preamble,\n * so it does not disqualify a shape.\n */\nfunction referencesExportRefs(ir: SchemaIR): boolean {\n switch (ir.type) {\n case \"default\":\n case \"catch\":\n case \"fallback\":\n // `refIndex` is mandatory on these — the value/schema lives on the export.\n return true;\n case \"custom\":\n // Both the predicate and pristine error delegate live on the export.\n return true;\n case \"zodDelegate\":\n return true;\n case \"effect\":\n if (ir.refIndex !== undefined) return true;\n break;\n case \"string\":\n case \"number\":\n case \"object\":\n case \"array\":\n if (ir.checks?.some((c) => \"refIndex\" in c && c.refIndex !== undefined)) return true;\n break;\n default:\n break;\n }\n return childSchemas(ir).some(referencesExportRefs);\n}\n\n// ─── Candidate collection ────────────────────────────────────────────────────\n\nfunction collect(\n ir: SchemaIR,\n keyMemo: Map<SchemaIR, string>,\n weightMemo: Map<SchemaIR, number>,\n stats: Map<string, { ir: SchemaIR; count: number; weight: number }>,\n): void {\n const key = keyOf(ir, keyMemo);\n const existing = stats.get(key);\n if (existing) {\n existing.count++;\n } else {\n stats.set(key, { ir, count: 1, weight: weightOf(ir, weightMemo) });\n }\n for (const child of childSchemas(ir)) collect(child, keyMemo, weightMemo, stats);\n}\n\n/** Direct child SchemaIR nodes (the structural recursion shared by every pass). */\nfunction childSchemas(ir: SchemaIR): 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 return [ir.inner];\n case \"pipe\":\n return [ir.in, ir.out];\n case \"effect\":\n case \"recursionTarget\":\n case \"zodDelegate\":\n return [ir.inner];\n default:\n return [];\n }\n}\n\n/** Subtree weight ≈ node count plus one per check; memoized for O(total) cost. */\nfunction weightOf(ir: SchemaIR, memo: Map<SchemaIR, number>): number {\n const hit = memo.get(ir);\n if (hit !== undefined) return hit;\n const checks = (ir as { checks?: readonly unknown[] }).checks;\n let weight = 1 + (Array.isArray(checks) ? checks.length : 0);\n for (const child of childSchemas(ir)) weight += weightOf(child, memo);\n memo.set(ir, weight);\n return weight;\n}\n\nfunction containsRecursiveRef(ir: SchemaIR): boolean {\n if (ir.type === \"recursiveRef\") return true;\n return childSchemas(ir).some(containsRecursiveRef);\n}\n\n// ─── Structural keys ─────────────────────────────────────────────────────────\n\n/**\n * Stable structural key for an IR node, memoized by node identity so each\n * subtree is serialized exactly once (the whole pass is O(total nodes), not\n * O(nodes × depth)). Two nodes share a key iff they are structurally identical\n * — including every check, literal value, and error message — so deduplicated\n * schemas produce byte-identical validation and issues.\n */\nfunction keyOf(ir: SchemaIR, memo: Map<SchemaIR, string>): string {\n const hit = memo.get(ir);\n if (hit !== undefined) return hit;\n const obj = ir as unknown as Record<string, unknown>;\n const key = `{${Object.keys(obj)\n .filter((k) => obj[k] !== undefined)\n .sort()\n .map((k) => `${k}:${encodeValue(obj[k], memo)}`)\n .join(\",\")}}`;\n memo.set(ir, key);\n return key;\n}\n\n/**\n * Encode any IR field value. A nested SchemaIR is detected by a string `type`\n * field (checks carry `kind`, union `cases` carry `value`/`option` — only real\n * schema nodes have `type`) and routed through {@link keyOf} for subtree\n * memoization; everything else is serialized in sorted-key order.\n */\nfunction encodeValue(value: unknown, memo: Map<SchemaIR, string>): string {\n if (typeof value === \"bigint\") return `#${value}`;\n if (value === null) return \"null\";\n // Non-finite numbers must stay distinct: JSON.stringify maps Infinity, -Infinity\n // and NaN all to \"null\", which would merge e.g. .min(Infinity) with .min(NaN).\n if (typeof value === \"number\" && !Number.isFinite(value)) return `n!${value}`;\n if (Array.isArray(value)) return `[${value.map((v) => encodeValue(v, memo)).join(\",\")}]`;\n if (typeof value === \"object\") {\n if (typeof (value as { type?: unknown }).type === \"string\") {\n return keyOf(value as SchemaIR, memo);\n }\n const obj = value as Record<string, unknown>;\n return `{${Object.keys(obj)\n .filter((k) => obj[k] !== undefined)\n .sort()\n .map((k) => `${k}:${encodeValue(obj[k], memo)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"undefined\";\n}\n\nfunction cmp(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n"],"mappings":";;;;;;;;AAoEA,MAAM,oBAAoB;;AAG1B,MAAa,sBAAsB;AAEnC,MAAM,aAA+B;CACnC,cAAc,KAAA;CACd,MAAM;CACN,6BAAa,IA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AU,MAAM,OAAO;CAG3B,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,GAAG,OAAO,KAAK;CACtE,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,IAAI,MAAM,KAAK,MAAM,YAAY,GAAG,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;CACtF,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,OAAQ,MAA6B,SAAS,UAChD,OAAO,MAAM,OAAmB,IAAI;EAEtC,MAAM,MAAM;EACZ,OAAO,IAAI,OAAO,KAAK,GAAG,CAAC,CACxB,QAAQ,MAAM,IAAI,OAAO,KAAA,CAAS,CAAC,CACnC,KAAK,CAAC,CACN,KAAK,MAAM,GAAG,EAAE,GAAG,YAAY,IAAI,IAAI,IAAI,GAAG,CAAC,CAC/C,KAAK,GAAG,EAAE;CACf;CACA,OAAO,KAAK,UAAU,KAAK,KAAK;AAClC;AAEA,SAAS,IAAI,GAAW,GAAmB;CACzC,OAAO,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI;AAClC"}
@@ -1 +1 @@
1
- {"version":3,"file":"fast-path.d.ts","names":[],"sources":["../../../src/core/codegen/fast-path.ts"],"mappings":";;;;;;;;;;;;;iBAsHgB,cACd,mBACA,KAAK,gBACL,uBACA,QAAO,WACP,uBACC;;;;;;;;;;;;;;;;;iBA8Ca,aAAa,IAAI,UAAU,GAAG"}
1
+ {"version":3,"file":"fast-path.d.ts","names":[],"sources":["../../../src/core/codegen/fast-path.ts"],"mappings":";;;;;;;;;;;;;iBA0HgB,cACd,mBACA,KAAK,gBACL,uBACA,QAAO,WACP,uBACC;;;;;;;;;;;;;;;;;iBA8Ca,aAAa,IAAI,UAAU,GAAG"}
@@ -4,6 +4,7 @@ import { fastArray } from "./schemas/array.js";
4
4
  import { fastBigInt } from "./schemas/bigint.js";
5
5
  import { fastBoolean } from "./schemas/boolean.js";
6
6
  import { fastCatch } from "./schemas/catch.js";
7
+ import { fastCustom } from "./schemas/custom.js";
7
8
  import { fastDate } from "./schemas/date.js";
8
9
  import { fastDefault } from "./schemas/default.js";
9
10
  import { fastDiscriminatedUnion } from "./schemas/discriminated-union.js";
@@ -33,6 +34,7 @@ import { fastUndefined } from "./schemas/undefined.js";
33
34
  import { fastUnion } from "./schemas/union.js";
34
35
  import { fastUnknown } from "./schemas/unknown.js";
35
36
  import { fastVoid } from "./schemas/void.js";
37
+ import { fastZodDelegate } from "./schemas/zod-delegate.js";
36
38
  //#region src/core/codegen/fast-path.ts
37
39
  const fastRegistry = {
38
40
  string: fastString,
@@ -66,6 +68,8 @@ const fastRegistry = {
66
68
  default: fastDefault,
67
69
  pipe: fastPipe,
68
70
  effect: null,
71
+ custom: fastCustom,
72
+ zodDelegate: fastZodDelegate,
69
73
  templateLiteral: fastTemplateLiteral,
70
74
  catch: fastCatch,
71
75
  fallback: null,
@@ -1 +1 @@
1
- {"version":3,"file":"fast-path.js","names":[],"sources":["../../../src/core/codegen/fast-path.ts"],"sourcesContent":["/**\n * Fast Path: produces a boolean expression string for eligible schemas.\n * When the expression evaluates to `true` at runtime, the input is valid and\n * safeParse can return success immediately without allocating an issues array.\n *\n * Returns `null` if the schema is not eligible for Fast Path (contains coerce,\n * default, transform, or other non-pure constructs).\n */\n\nimport type { SchemaIR } from \"../types.js\";\nimport type { CodeGenContext, FastGen, FastGenerator, FastScope } from \"./context.js\";\nimport { declareFastTemps, emitRegex, emitTemp } from \"./context.js\";\nimport {\n CALL_COST,\n EXTRACT_CAP,\n estimateFastCost,\n HOISTABLE,\n MIN_EXTRACT,\n predictedInlineSize,\n} from \"./fast-size.js\";\nimport { fastAny } from \"./schemas/any.js\";\nimport { fastArray } from \"./schemas/array.js\";\nimport { fastBigInt } from \"./schemas/bigint.js\";\nimport { fastBoolean } from \"./schemas/boolean.js\";\nimport { fastCatch } from \"./schemas/catch.js\";\nimport { fastDate } from \"./schemas/date.js\";\nimport { fastDefault } from \"./schemas/default.js\";\nimport { fastDiscriminatedUnion } from \"./schemas/discriminated-union.js\";\nimport { fastEnum } from \"./schemas/enum.js\";\nimport { fastFile } from \"./schemas/file.js\";\nimport { fastIntersection } from \"./schemas/intersection.js\";\nimport { fastLiteral } from \"./schemas/literal.js\";\nimport { fastMap } from \"./schemas/map.js\";\nimport { fastNan } from \"./schemas/nan.js\";\nimport { fastNever } from \"./schemas/never.js\";\nimport { fastNull } from \"./schemas/null.js\";\nimport { fastNullable } from \"./schemas/nullable.js\";\nimport { fastNumber } from \"./schemas/number.js\";\nimport { fastObject } from \"./schemas/object.js\";\nimport { fastOptional } from \"./schemas/optional.js\";\nimport { fastPipe } from \"./schemas/pipe.js\";\nimport { fastReadonly } from \"./schemas/readonly.js\";\nimport { fastRecord } from \"./schemas/record.js\";\nimport { fastRecursionTarget, fastRecursiveRef } from \"./schemas/recursive-ref.js\";\nimport { fastSet } from \"./schemas/set.js\";\nimport { fastString } from \"./schemas/string.js\";\nimport { fastSymbol } from \"./schemas/symbol.js\";\nimport { fastTemplateLiteral } from \"./schemas/template-literal.js\";\nimport { fastTuple } from \"./schemas/tuple.js\";\nimport { fastUndefined } from \"./schemas/undefined.js\";\nimport { fastUnion } from \"./schemas/union.js\";\nimport { fastUnknown } from \"./schemas/unknown.js\";\nimport { fastVoid } from \"./schemas/void.js\";\n\n// ─── Typed registry ─────────────────────────────────────────────────────────\n// `null` = statically ineligible (the type NEVER has a fast path).\n// Non-null function = may return null at runtime (dynamically ineligible, e.g. when coerce is present).\n\nconst fastRegistry = {\n // Primitives (order follows SchemaIR union in types.ts)\n string: fastString,\n number: fastNumber,\n boolean: fastBoolean,\n bigint: fastBigInt,\n date: fastDate,\n symbol: fastSymbol,\n null: fastNull,\n undefined: fastUndefined,\n void: fastVoid,\n nan: fastNan,\n never: fastNever,\n any: fastAny,\n unknown: fastUnknown,\n literal: fastLiteral,\n enum: fastEnum,\n // Containers\n object: fastObject,\n array: fastArray,\n tuple: fastTuple,\n record: fastRecord,\n set: fastSet,\n map: fastMap,\n file: fastFile,\n // Unions & Intersections\n union: fastUnion,\n discriminatedUnion: fastDiscriminatedUnion,\n intersection: fastIntersection,\n // Modifiers\n optional: fastOptional,\n nullable: fastNullable,\n readonly: fastReadonly,\n default: fastDefault,\n pipe: fastPipe,\n // Effects\n effect: null, // statically ineligible\n // Special\n templateLiteral: fastTemplateLiteral,\n catch: fastCatch,\n fallback: null, // statically ineligible\n recursiveRef: fastRecursiveRef,\n recursionTarget: fastRecursionTarget,\n stringBool: null, // statically ineligible — output type (boolean) differs from input (string)\n} satisfies {\n [K in SchemaIR[\"type\"]]: FastGenerator<Extract<SchemaIR, { type: K }>> | null;\n};\n\n// ─── Factory ─────────────────────────────────────────────────────────────────\n\n/**\n * @param inputExpr the input expression this node validates\n * @param ctx shared codegen context\n * @param extractable whether THIS node may be hoisted (false for the root and a\n * helper's own top node — see generateFast); children are always extractable\n * @param scope size accumulator for the function being assembled (a child\n * visit shares the parent's scope; a hoisted helper body gets a fresh one)\n * @param discSkipKey discriminated-union option marker (see FastGen.discSkipKey);\n * carried only on the option's own node, never auto-propagated to children\n */\nexport function createFastGen(\n inputExpr: string,\n ctx: CodeGenContext,\n extractable = false,\n scope: FastScope = { temps: [], used: 0 },\n discSkipKey?: string,\n): FastGen {\n return {\n input: inputExpr,\n ctx,\n extractable,\n scope,\n discSkipKey,\n visit(ir, overrides) {\n // A child shares this function's scope and is itself extractable. The\n // discriminated-union skip is NOT inherited implicitly — only a caller\n // that explicitly passes overrides.discSkipKey (fastDiscriminatedUnion)\n // sets it, so nested objects keep their own type-guard.\n return generateFast(\n ir,\n createFastGen(overrides?.input ?? inputExpr, ctx, true, scope, overrides?.discSkipKey),\n );\n },\n scoped: (input) => createFastGen(input, ctx, true, { temps: [], used: 0 }),\n temp: (prefix) => emitTemp(ctx, prefix),\n local(prefix) {\n const name = emitTemp(ctx, prefix);\n scope.temps.push(name);\n return name;\n },\n regex: (prefix, pattern, flags) => emitRegex(ctx, prefix, pattern, flags),\n };\n}\n\n// ─── Dispatch ────────────────────────────────────────────────────────────────\n\n/**\n * Generate a boolean expression string that validates input against the schema.\n * Returns `null` if the schema (or any nested part) is not eligible for fast checking.\n *\n * Size-gated extraction: when inlining `ir` would push the function being\n * assembled past EXTRACT_CAP, it is hoisted into its own boolean helper\n * `function __fo_N(p){return <expr over p>;}` and replaced by a call. This keeps\n * every emitted function under V8's TurboFan optimization budget — a single\n * giant fast-check otherwise drops to the slower Maglev tier (measured ~3-4.5x\n * on deeply-nested schemas). The running total `g.scope.used` is EXACT emitted\n * chars (the returned string's length); only the extract look-ahead is an\n * estimate, scaled for access-path length. Small schemas never approach the\n * cap, so their output is byte-identical to the fully-inlined form; large\n * aggregates do split (still semantically identical — only the boolean's shape\n * changes).\n */\nexport function generateFast(ir: SchemaIR, g: FastGen): string | null {\n const gen = fastRegistry[ir.type];\n if (gen === null) return null;\n\n if (g.extractable && HOISTABLE.has(ir.type)) {\n const cache = fastSizeCache(g.ctx);\n const overBudget = g.scope.used + predictedInlineSize(ir, g.input.length, cache) > EXTRACT_CAP;\n // Extract a sub-schema big enough to be worth a call; but once the function\n // is ALREADY over budget, extract any hoistable child regardless of size —\n // otherwise a crowd of small siblings (e.g. a discriminated union of many\n // small options) grows the function unbounded since none alone clears\n // MIN_EXTRACT.\n if (overBudget && (g.scope.used > EXTRACT_CAP || estimateFastCost(ir, cache) >= MIN_EXTRACT)) {\n const param = emitTemp(g.ctx, \"op\");\n // Generate the body relative to the helper's parameter, in a fresh scope;\n // the top node is non-extractable (it IS this helper) while its children\n // stay extractable, so an oversized helper splits further recursively.\n // Carry discSkipKey so an extracted discriminated-union option still drops\n // its redundant guard inside the hoisted helper.\n const innerGen = createFastGen(param, g.ctx, false, { temps: [], used: 0 }, g.discSkipKey);\n const inner = generateFast(ir, innerGen);\n if (inner === null) return null; // ineligible sub-schema disables the whole fast path\n const fnName = emitTemp(g.ctx, \"fo\");\n g.ctx.preamble.push(\n `function ${fnName}(${param}){${declareFastTemps(innerGen.scope)}return ${inner};}`,\n );\n g.scope.used += CALL_COST;\n return `${fnName}(${g.input})`;\n }\n }\n\n // Inlined: charge the enclosing function this node's EXACT emitted size. The\n // node's own text plus its inlined descendants is exactly the returned string;\n // children mutated the shared scope as they were visited, but the parent's\n // length is authoritative, so overwrite rather than add.\n const before = g.scope.used;\n // oxlint-disable-next-line typescript/no-explicit-any -- registry dispatch requires type erasure at call site\n const out = (gen as any)(ir, g) as string | null;\n if (out === null) return null;\n g.scope.used = before + out.length;\n return out;\n}\n\n/** Per-compile memo for estimateFastCost, stashed on the shared context. */\nfunction fastSizeCache(ctx: CodeGenContext): WeakMap<SchemaIR, number> {\n return (ctx.fastSizeCache ??= new WeakMap<SchemaIR, number>());\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,MAAM,eAAe;CAEnB,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,MAAM;CACN,QAAQ;CACR,MAAM;CACN,WAAW;CACX,MAAM;CACN,KAAK;CACL,OAAO;CACP,KAAK;CACL,SAAS;CACT,SAAS;CACT,MAAM;CAEN,QAAQ;CACR,OAAO;CACP,OAAO;CACP,QAAQ;CACR,KAAK;CACL,KAAK;CACL,MAAM;CAEN,OAAO;CACP,oBAAoB;CACpB,cAAc;CAEd,UAAU;CACV,UAAU;CACV,UAAU;CACV,SAAS;CACT,MAAM;CAEN,QAAQ;CAER,iBAAiB;CACjB,OAAO;CACP,UAAU;CACV,cAAc;CACd,iBAAiB;CACjB,YAAY;AACd;;;;;;;;;;;AAgBA,SAAgB,cACd,WACA,KACA,cAAc,OACd,QAAmB;CAAE,OAAO,CAAC;CAAG,MAAM;AAAE,GACxC,aACS;CACT,OAAO;EACL,OAAO;EACP;EACA;EACA;EACA;EACA,MAAM,IAAI,WAAW;GAKnB,OAAO,aACL,IACA,cAAc,WAAW,SAAS,WAAW,KAAK,MAAM,OAAO,WAAW,WAAW,CACvF;EACF;EACA,SAAS,UAAU,cAAc,OAAO,KAAK,MAA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rE,OAAQ,IAAI,kCAAkB,IAAI,QAA0B;AAC9D"}
1
+ {"version":3,"file":"fast-path.js","names":[],"sources":["../../../src/core/codegen/fast-path.ts"],"sourcesContent":["/**\n * Fast Path: produces a boolean expression string for eligible schemas.\n * When the expression evaluates to `true` at runtime, the input is valid and\n * safeParse can return success immediately without allocating an issues array.\n *\n * Returns `null` if the schema is not eligible for Fast Path (contains coerce,\n * default, transform, or other non-pure constructs).\n */\n\nimport type { SchemaIR } from \"../types.js\";\nimport type { CodeGenContext, FastGen, FastGenerator, FastScope } from \"./context.js\";\nimport { declareFastTemps, emitRegex, emitTemp } from \"./context.js\";\nimport {\n CALL_COST,\n EXTRACT_CAP,\n estimateFastCost,\n HOISTABLE,\n MIN_EXTRACT,\n predictedInlineSize,\n} from \"./fast-size.js\";\nimport { fastAny } from \"./schemas/any.js\";\nimport { fastArray } from \"./schemas/array.js\";\nimport { fastBigInt } from \"./schemas/bigint.js\";\nimport { fastBoolean } from \"./schemas/boolean.js\";\nimport { fastCatch } from \"./schemas/catch.js\";\nimport { fastCustom } from \"./schemas/custom.js\";\nimport { fastDate } from \"./schemas/date.js\";\nimport { fastDefault } from \"./schemas/default.js\";\nimport { fastDiscriminatedUnion } from \"./schemas/discriminated-union.js\";\nimport { fastEnum } from \"./schemas/enum.js\";\nimport { fastFile } from \"./schemas/file.js\";\nimport { fastIntersection } from \"./schemas/intersection.js\";\nimport { fastLiteral } from \"./schemas/literal.js\";\nimport { fastMap } from \"./schemas/map.js\";\nimport { fastNan } from \"./schemas/nan.js\";\nimport { fastNever } from \"./schemas/never.js\";\nimport { fastNull } from \"./schemas/null.js\";\nimport { fastNullable } from \"./schemas/nullable.js\";\nimport { fastNumber } from \"./schemas/number.js\";\nimport { fastObject } from \"./schemas/object.js\";\nimport { fastOptional } from \"./schemas/optional.js\";\nimport { fastPipe } from \"./schemas/pipe.js\";\nimport { fastReadonly } from \"./schemas/readonly.js\";\nimport { fastRecord } from \"./schemas/record.js\";\nimport { fastRecursionTarget, fastRecursiveRef } from \"./schemas/recursive-ref.js\";\nimport { fastSet } from \"./schemas/set.js\";\nimport { fastString } from \"./schemas/string.js\";\nimport { fastSymbol } from \"./schemas/symbol.js\";\nimport { fastTemplateLiteral } from \"./schemas/template-literal.js\";\nimport { fastTuple } from \"./schemas/tuple.js\";\nimport { fastUndefined } from \"./schemas/undefined.js\";\nimport { fastUnion } from \"./schemas/union.js\";\nimport { fastUnknown } from \"./schemas/unknown.js\";\nimport { fastVoid } from \"./schemas/void.js\";\nimport { fastZodDelegate } from \"./schemas/zod-delegate.js\";\n\n// ─── Typed registry ─────────────────────────────────────────────────────────\n// `null` = statically ineligible (the type NEVER has a fast path).\n// Non-null function = may return null at runtime (dynamically ineligible, e.g. when coerce is present).\n\nconst fastRegistry = {\n // Primitives (order follows SchemaIR union in types.ts)\n string: fastString,\n number: fastNumber,\n boolean: fastBoolean,\n bigint: fastBigInt,\n date: fastDate,\n symbol: fastSymbol,\n null: fastNull,\n undefined: fastUndefined,\n void: fastVoid,\n nan: fastNan,\n never: fastNever,\n any: fastAny,\n unknown: fastUnknown,\n literal: fastLiteral,\n enum: fastEnum,\n // Containers\n object: fastObject,\n array: fastArray,\n tuple: fastTuple,\n record: fastRecord,\n set: fastSet,\n map: fastMap,\n file: fastFile,\n // Unions & Intersections\n union: fastUnion,\n discriminatedUnion: fastDiscriminatedUnion,\n intersection: fastIntersection,\n // Modifiers\n optional: fastOptional,\n nullable: fastNullable,\n readonly: fastReadonly,\n default: fastDefault,\n pipe: fastPipe,\n // Effects\n effect: null, // statically ineligible\n // Special\n custom: fastCustom,\n zodDelegate: fastZodDelegate,\n templateLiteral: fastTemplateLiteral,\n catch: fastCatch,\n fallback: null, // statically ineligible\n recursiveRef: fastRecursiveRef,\n recursionTarget: fastRecursionTarget,\n stringBool: null, // statically ineligible — output type (boolean) differs from input (string)\n} satisfies {\n [K in SchemaIR[\"type\"]]: FastGenerator<Extract<SchemaIR, { type: K }>> | null;\n};\n\n// ─── Factory ─────────────────────────────────────────────────────────────────\n\n/**\n * @param inputExpr the input expression this node validates\n * @param ctx shared codegen context\n * @param extractable whether THIS node may be hoisted (false for the root and a\n * helper's own top node — see generateFast); children are always extractable\n * @param scope size accumulator for the function being assembled (a child\n * visit shares the parent's scope; a hoisted helper body gets a fresh one)\n * @param discSkipKey discriminated-union option marker (see FastGen.discSkipKey);\n * carried only on the option's own node, never auto-propagated to children\n */\nexport function createFastGen(\n inputExpr: string,\n ctx: CodeGenContext,\n extractable = false,\n scope: FastScope = { temps: [], used: 0 },\n discSkipKey?: string,\n): FastGen {\n return {\n input: inputExpr,\n ctx,\n extractable,\n scope,\n discSkipKey,\n visit(ir, overrides) {\n // A child shares this function's scope and is itself extractable. The\n // discriminated-union skip is NOT inherited implicitly — only a caller\n // that explicitly passes overrides.discSkipKey (fastDiscriminatedUnion)\n // sets it, so nested objects keep their own type-guard.\n return generateFast(\n ir,\n createFastGen(overrides?.input ?? inputExpr, ctx, true, scope, overrides?.discSkipKey),\n );\n },\n scoped: (input) => createFastGen(input, ctx, true, { temps: [], used: 0 }),\n temp: (prefix) => emitTemp(ctx, prefix),\n local(prefix) {\n const name = emitTemp(ctx, prefix);\n scope.temps.push(name);\n return name;\n },\n regex: (prefix, pattern, flags) => emitRegex(ctx, prefix, pattern, flags),\n };\n}\n\n// ─── Dispatch ────────────────────────────────────────────────────────────────\n\n/**\n * Generate a boolean expression string that validates input against the schema.\n * Returns `null` if the schema (or any nested part) is not eligible for fast checking.\n *\n * Size-gated extraction: when inlining `ir` would push the function being\n * assembled past EXTRACT_CAP, it is hoisted into its own boolean helper\n * `function __fo_N(p){return <expr over p>;}` and replaced by a call. This keeps\n * every emitted function under V8's TurboFan optimization budget — a single\n * giant fast-check otherwise drops to the slower Maglev tier (measured ~3-4.5x\n * on deeply-nested schemas). The running total `g.scope.used` is EXACT emitted\n * chars (the returned string's length); only the extract look-ahead is an\n * estimate, scaled for access-path length. Small schemas never approach the\n * cap, so their output is byte-identical to the fully-inlined form; large\n * aggregates do split (still semantically identical — only the boolean's shape\n * changes).\n */\nexport function generateFast(ir: SchemaIR, g: FastGen): string | null {\n const gen = fastRegistry[ir.type];\n if (gen === null) return null;\n\n if (g.extractable && HOISTABLE.has(ir.type)) {\n const cache = fastSizeCache(g.ctx);\n const overBudget = g.scope.used + predictedInlineSize(ir, g.input.length, cache) > EXTRACT_CAP;\n // Extract a sub-schema big enough to be worth a call; but once the function\n // is ALREADY over budget, extract any hoistable child regardless of size —\n // otherwise a crowd of small siblings (e.g. a discriminated union of many\n // small options) grows the function unbounded since none alone clears\n // MIN_EXTRACT.\n if (overBudget && (g.scope.used > EXTRACT_CAP || estimateFastCost(ir, cache) >= MIN_EXTRACT)) {\n const param = emitTemp(g.ctx, \"op\");\n // Generate the body relative to the helper's parameter, in a fresh scope;\n // the top node is non-extractable (it IS this helper) while its children\n // stay extractable, so an oversized helper splits further recursively.\n // Carry discSkipKey so an extracted discriminated-union option still drops\n // its redundant guard inside the hoisted helper.\n const innerGen = createFastGen(param, g.ctx, false, { temps: [], used: 0 }, g.discSkipKey);\n const inner = generateFast(ir, innerGen);\n if (inner === null) return null; // ineligible sub-schema disables the whole fast path\n const fnName = emitTemp(g.ctx, \"fo\");\n g.ctx.preamble.push(\n `function ${fnName}(${param}){${declareFastTemps(innerGen.scope)}return ${inner};}`,\n );\n g.scope.used += CALL_COST;\n return `${fnName}(${g.input})`;\n }\n }\n\n // Inlined: charge the enclosing function this node's EXACT emitted size. The\n // node's own text plus its inlined descendants is exactly the returned string;\n // children mutated the shared scope as they were visited, but the parent's\n // length is authoritative, so overwrite rather than add.\n const before = g.scope.used;\n // oxlint-disable-next-line typescript/no-explicit-any -- registry dispatch requires type erasure at call site\n const out = (gen as any)(ir, g) as string | null;\n if (out === null) return null;\n g.scope.used = before + out.length;\n return out;\n}\n\n/** Per-compile memo for estimateFastCost, stashed on the shared context. */\nfunction fastSizeCache(ctx: CodeGenContext): WeakMap<SchemaIR, number> {\n return (ctx.fastS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,iBACJ"}
1
+ {"version":3,"file":"fast-size.d.ts","names":[],"sources":["../../../src/core/codegen/fast-size.ts"],"mappings":";;;;;;;;;cA2Ba;;;;;;;iBAiBG,oBACd,IAAI,UACJ,kBACA,OAAO,QAAQ;;;;;;cAUJ;;cAGA;;;;;;;cAQA,WAAW,YAAY;;;;;;;iBA8FpB,iBAAiB,IAAI,UAAU,OAAO,QAAQ;;;;;;iBA0F9C,mBAAmB,GACjC,gBAAgB,KAChB,OAAO,MAAM,MAAM,UACnB,KAAK,iBACJ"}
@@ -63,6 +63,7 @@ function shallowFastCost(ir) {
63
63
  case "map": return 55;
64
64
  case "file":
65
65
  case "templateLiteral": return 40;
66
+ case "custom": return 30;
66
67
  case "literal":
67
68
  case "optional":
68
69
  case "nullable":
@@ -89,7 +90,8 @@ function fastChildren(ir) {
89
90
  case "nullable":
90
91
  case "readonly":
91
92
  case "default":
92
- case "catch": return [ir.inner];
93
+ case "catch":
94
+ case "zodDelegate": return [ir.inner];
93
95
  default: return [];
94
96
  }
95
97
  }
@@ -142,6 +144,7 @@ function shallowRuntimeCost(ir) {
142
144
  case "map":
143
145
  case "tuple": return 3;
144
146
  case "templateLiteral": return 100;
147
+ case "custom": return 20;
145
148
  case "recursiveRef":
146
149
  case "recursionTarget": return 200;
147
150
  default: return 1;
@@ -1 +1 @@
1
- {"version":3,"file":"fast-size.js","names":[],"sources":["../../../src/core/codegen/fast-size.ts"],"sourcesContent":["/**\n * Fast-path size estimation, used to bound the size of each emitted fast-check\n * function. V8's TurboFan refuses to optimize functions whose bytecode exceeds\n * ~60KB and falls back to the weaker Maglev tier — measured ~1.3-1.8x slower on\n * deeply-nested schemas whose monolithic fast-check crosses that budget. By\n * extracting large, self-contained sub-schemas into their own boolean helpers\n * (`generateFast`), each function stays small enough to TurboFan.\n *\n * `estimateFastCost` is a path-agnostic subtree estimate in approximate\n * generated-character units (it can't see the access-path prefix the node will\n * be emitted under, since that lives in the call site, not the IR). The actual\n * emitted size of an inlined node grows with that prefix length — `input[\"a\"]\n * [\"b\"][\"c\"]…` repeated per check — so the extraction decision scales the\n * estimate by `1 + inputLen/PATH_GROWTH_DIVISOR` (see `predictedInlineSize`).\n * The accumulator itself (generateFast) tracks EXACT emitted chars via the\n * returned string length, so only the look-ahead prediction is approximate.\n */\n\nimport type { SchemaIR } from \"../types.js\";\nimport type { CodeGenContext } from \"./context.js\";\n\n/**\n * Per-function soft size cap, in emitted characters. Once the fast-check being\n * assembled would exceed this, the next large hoistable sub-schema is split into\n * its own helper. Set below the ~60KB bytecode point where TurboFan bails (chars\n * over-approximate bytecode) with margin for one look-ahead mis-prediction.\n */\nexport const EXTRACT_CAP = 38_000;\n\n/**\n * Each nesting level lengthens every access path inside a node (`x[\"a\"]` →\n * `x[\"a\"][\"b\"]`), inflating real emitted chars above the path-agnostic estimate.\n * The extraction look-ahead multiplies the estimate by `1 + inputLen/this` so a\n * deep subtree is split before it inlines into an over-budget function. Smaller\n * ⇒ more eager splitting at depth. Calibrated against deeply-nested fixtures.\n */\nconst PATH_GROWTH_DIVISOR = 26;\n\n/**\n * Predicted emitted size of inlining `ir` at a call site whose input expression\n * is `inputLen` chars long — the path-agnostic subtree estimate scaled up for\n * the access-path prefix that estimate omits. Used only for the extract/inline\n * decision; the running total uses exact emitted lengths.\n */\nexport function predictedInlineSize(\n ir: SchemaIR,\n inputLen: number,\n cache: WeakMap<SchemaIR, number>,\n): number {\n return estimateFastCost(ir, cache) * (1 + inputLen / PATH_GROWTH_DIVISOR);\n}\n\n/**\n * Floor for extraction: never hoist a sub-schema smaller than this even when\n * the enclosing function is over the cap — a tiny helper trades a real call for\n * no optimization benefit. Only sub-schemas big enough to matter are split.\n */\nexport const MIN_EXTRACT = 1_200;\n\n/** Approximate size contributed to the enclosing function by an extracted call `__fo_N(expr)`. */\nexport const CALL_COST = 24;\n\n/**\n * Node types whose fast-check is a self-contained boolean over a single input\n * expression and large enough to be worth hoisting into `function f(p){return …}`.\n * Thin wrappers (optional/nullable/default/…) are omitted: their inner schema is\n * visited through `generateFast` and gets hoisted on its own when large.\n */\nexport const HOISTABLE: ReadonlySet<SchemaIR[\"type\"]> = new Set([\n \"object\",\n \"record\",\n \"tuple\",\n \"discriminatedUnion\",\n \"union\",\n \"intersection\",\n]);\n\n/** A node's own contribution to the emitted fast-check, EXCLUDING its children. */\nfunction shallowFastCost(ir: SchemaIR): number {\n switch (ir.type) {\n case \"object\":\n return 50 + Object.keys(ir.properties).length * 25 + (ir.strict ? 120 : 0);\n case \"string\":\n return 20 + ir.checks.length * 35;\n case \"number\":\n return 25 + ir.checks.length * 30;\n case \"bigint\":\n case \"date\":\n return 25 + (ir.checks?.length ?? 0) * 25;\n case \"enum\":\n return 15 + ir.values.length * 12;\n case \"tuple\":\n return 40 + ir.items.length * 15;\n case \"union\":\n return 12 + ir.options.length * 6;\n case \"discriminatedUnion\":\n return 45 + ir.cases.length * 12;\n case \"array\":\n case \"record\":\n case \"set\":\n case \"map\":\n return 55;\n case \"file\":\n case \"templateLiteral\":\n return 40;\n case \"literal\":\n case \"optional\":\n case \"nullable\":\n case \"default\":\n return 22;\n case \"recursiveRef\":\n case \"recursionTarget\":\n // Both emit just a call to a hosted helper; the target's `inner` is sized\n // independently when its own helper body is generated, so it is NOT\n // counted against the enclosing function here (see fastChildren).\n return 15;\n default:\n return 18;\n }\n}\n\n/** Child IR nodes that the fast generator recurses into (mirrors the fast schema generators). */\nfunction fastChildren(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.rest] : ir.items;\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 \"pipe\":\n return [ir.in, ir.out];\n case \"optional\":\n case \"nullable\":\n case \"readonly\":\n case \"default\":\n case \"catch\":\n return [ir.inner];\n default:\n return [];\n }\n}\n\n/**\n * Estimated total size of a node's fast-check (the node plus everything inlined\n * beneath it). Memoized per IR node: schemas dedupe shared sub-trees and the\n * estimate is consulted at every nesting level, so without the cache a deep tree\n * would be re-walked quadratically.\n */\nexport function estimateFastCost(ir: SchemaIR, cache: WeakMap<SchemaIR, number>): number {\n const cached = cache.get(ir);\n if (cached !== undefined) return cached;\n // Defensive cycle break (the IR is a tree today; recursiveRef is a leaf).\n cache.set(ir, 0);\n let total = shallowFastCost(ir);\n for (const child of fastChildren(ir)) total += estimateFastCost(child, cache);\n cache.set(ir, total);\n return total;\n}\n\n// ─── Runtime cost (check ordering) ───────────────────────────────────────────\n\n/**\n * Assumed element count for unbounded collections, used only to weight a\n * container against its siblings when ordering an `&&` chain.\n */\nconst ASSUMED_ELEMENTS = 4;\n\n/** Runtime weight of one check on an already-type-confirmed value. */\nfunction checkRuntimeCost(kind: string): number {\n switch (kind) {\n // A `.test()` call costs ~9 ns of dispatch before it matches a character —\n // an order of magnitude above every other check, and the reason ordering\n // matters at all.\n case \"string_format\":\n return 100;\n // Zero-capture user predicate: a real call, cheaper than a regex.\n case \"refine_effect\":\n return 20;\n case \"includes\":\n case \"starts_with\":\n case \"ends_with\":\n return 6;\n case \"multiple_of\":\n case \"bigint_multiple_of\":\n return 4;\n default:\n // length/size/range comparisons: a load and a compare.\n return 1;\n }\n}\n\n/** A node's own runtime weight, EXCLUDING its children. */\nfunction shallowRuntimeCost(ir: SchemaIR): number {\n switch (ir.type) {\n case \"string\":\n case \"number\":\n return 2 + ir.checks.reduce((sum, c) => sum + checkRuntimeCost(c.kind), 0);\n case \"bigint\":\n case \"date\":\n return 3 + (ir.checks?.length ?? 0);\n case \"file\":\n return 3 + (ir.checks?.length ?? 0) * 2;\n case \"enum\":\n // Inlined `===` chain (or one hashed lookup) — sub-nanosecond either way.\n return 1 + Math.min(ir.values.length, 8);\n case \"object\":\n // Type guard, plus the strict pass's per-key membership test.\n return 3 + (ir.strict === true ? Object.keys(ir.properties).length : 0);\n case \"array\":\n case \"set\":\n case \"record\":\n case \"map\":\n case \"tuple\":\n return 3;\n case \"templateLiteral\":\n return 100;\n case \"recursiveRef\":\n case \"recursionTarget\":\n // A recursive call expands into an unknown amount of work; treat it as\n // the most expensive sibling so it is probed last.\n return 200;\n default:\n return 1;\n }\n}\n\n/** estimateRuntimeCost against the per-compile memo hanging off the context. */\nfunction runtimeCostOf(ir: SchemaIR, ctx: CodeGenContext): number {\n return estimateRuntimeCost(ir, (ctx.fastRuntimeCostCache ??= new WeakMap<SchemaIR, number>()));\n}\n\n/**\n * Sort a fast-check's sibling conjuncts (or union options) cheapest-first.\n * Returns a new array; ties keep source order (Array#sort is stable), so a\n * schema whose members all cost the same emits byte-identical output.\n */\nexport function orderByRuntimeCost<T>(\n items: readonly T[],\n irOf: (item: T) => SchemaIR,\n ctx: CodeGenContext,\n): T[] {\n if (items.length < 2) return [...items];\n return [...items].sort((a, b) => runtimeCostOf(irOf(a), ctx) - runtimeCostOf(irOf(b), ctx));\n}\n\n/**\n * Estimated runtime cost of a node's fast-check, in arbitrary units calibrated\n * so a regex format check dominates a handful of type guards. Memoized per IR\n * node, like estimateFastCost — the estimate is consulted at every nesting\n * level, and shared sub-trees are common.\n *\n * Used to order the conjuncts of an `&&` chain cheapest-first. Accepting input\n * runs every conjunct regardless, so ordering is free there; REJECTING input\n * stops at the first false one, which is where a schema pays for probing a\n * `z.email()` before the `kind` literal that actually discriminates. Measured\n * on a 3-option union of objects that each declare `{email, kind, note}`:\n * 102 ns → 39 ns for an input matching the last option, and 102 ns → 6 ns for\n * one matching none.\n */\nfunction estimateRuntimeCost(ir: SchemaIR, cache: WeakMap<SchemaIR, number>): number {\n const cached = cache.get(ir);\n if (cached !== undefined) return cached;\n cache.set(ir, 0); // cycle break (mirrors estimateFastCost)\n let total = shallowRuntimeCost(ir);\n const children = fastChildren(ir);\n switch (ir.type) {\n case \"array\":\n case \"set\":\n case \"record\":\n case \"map\":\n // Per-element work, repeated for an assumed handful of entries.\n for (const child of children) total += estimateRuntimeCost(child, cache) * ASSUMED_ELEMENTS;\n break;\n case \"discriminatedUnion\":\n // O(1) switch: only the matched case runs. Charge the priciest option so\n // the estimate stays an upper bound.\n total += children.reduce((max, c) => Math.max(max, estimateRuntimeCost(c, cache)), 0);\n break;\n default:\n // object/tuple/union/intersection/wrappers: every child is on the path\n // (a union probes options until one matches — worst case, all of them).\n for (const child of children) total += estimateRuntimeCost(child, cache);\n break;\n }\n cache.set(ir, total);\n return total;\n}\n"],"mappings":";;;;;;;AA2BA,MAAa,cAAc;;;;;;;;AAS3B,MAAM,sBAAsB;;;;;;;AAQ5B,SAAgB,oBACd,IACA,UACA,OACQ;CACR,OAAO,iBAAiB,IAAI,KAAK,KAAK,IAAI,WAAW;AACvD;;;;;;AAOA,MAAa,cAAc;;AAG3B,MAAa,YAAY;;;;;;;AAQzB,MAAa,4BAA2C,IAAI,IAAI;CAC9D;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAS,gBAAgB,IAAsB;CAC7C,QAAQ,GAAG,MAAX;EACE,KAAK,UACH,OAAO,KAAK,OAAO,KAAK,GAAG,UAAU,CAAC,CAAC,SAAS,MAAM,GAAG,SAAS,MAAM;EAC1E,KAAK,UACH,OAAO,KAAK,GAAG,OAAO,SAAS;EACjC,KAAK,UACH,OAAO,KAAK,GAAG,OAAO,SAAS;EACjC,KAAK;EACL,KAAK,QACH,OAAO,MAAM,GAAG,QAAQ,UAAU,KAAK;EACzC,KAAK,QACH,OAAO,KAAK,GAAG,OAAO,SAAS;EACjC,KAAK,SACH,OAAO,KAAK,GAAG,MAAM,SAAS;EAChC,KAAK,SACH,OAAO,KAAK,GAAG,QAAQ,SAAS;EAClC,KAAK,sBACH,OAAO,KAAK,GAAG,MAAM,SAAS;EAChC,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,OACH,OAAO;EACT,KAAK;EACL,KAAK,mBACH,OAAO;EACT,KAAK;EACL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AoB,OAAO,KAAK,IAAI;GAC3E;EACF,KAAK;GAGH,SAAS,SAAS,QAAQ,KAAK,MAAM,KAAK,IAAI,KAAK,oBAAoB,GAAG,KAAK,CAAC,GAAG,CAAC;GACpF;EACF;GAGE,KAAK,MAAM,SAAS,UAAU,SAAS,oBAAoB,OAAO,KAAK;GACvE;CACJ;CACA,MAAM,IAAI,IAAI,KAAK;CACnB,OAAO;AACT"}
1
+ {"version":3,"file":"fast-size.js","names":[],"sources":["../../../src/core/codegen/fast-size.ts"],"sourcesContent":["/**\n * Fast-path size estimation, used to bound the size of each emitted fast-check\n * function. V8's TurboFan refuses to optimize functions whose bytecode exceeds\n * ~60KB and falls back to the weaker Maglev tier — measured ~1.3-1.8x slower on\n * deeply-nested schemas whose monolithic fast-check crosses that budget. By\n * extracting large, self-contained sub-schemas into their own boolean helpers\n * (`generateFast`), each function stays small enough to TurboFan.\n *\n * `estimateFastCost` is a path-agnostic subtree estimate in approximate\n * generated-character units (it can't see the access-path prefix the node will\n * be emitted under, since that lives in the call site, not the IR). The actual\n * emitted size of an inlined node grows with that prefix length — `input[\"a\"]\n * [\"b\"][\"c\"]…` repeated per check — so the extraction decision scales the\n * estimate by `1 + inputLen/PATH_GROWTH_DIVISOR` (see `predictedInlineSize`).\n * The accumulator itself (generateFast) tracks EXACT emitted chars via the\n * returned string length, so only the look-ahead prediction is approximate.\n */\n\nimport type { SchemaIR } from \"../types.js\";\nimport type { CodeGenContext } from \"./context.js\";\n\n/**\n * Per-function soft size cap, in emitted characters. Once the fast-check being\n * assembled would exceed this, the next large hoistable sub-schema is split into\n * its own helper. Set below the ~60KB bytecode point where TurboFan bails (chars\n * over-approximate bytecode) with margin for one look-ahead mis-prediction.\n */\nexport const EXTRACT_CAP = 38_000;\n\n/**\n * Each nesting level lengthens every access path inside a node (`x[\"a\"]` →\n * `x[\"a\"][\"b\"]`), inflating real emitted chars above the path-agnostic estimate.\n * The extraction look-ahead multiplies the estimate by `1 + inputLen/this` so a\n * deep subtree is split before it inlines into an over-budget function. Smaller\n * ⇒ more eager splitting at depth. Calibrated against deeply-nested fixtures.\n */\nconst PATH_GROWTH_DIVISOR = 26;\n\n/**\n * Predicted emitted size of inlining `ir` at a call site whose input expression\n * is `inputLen` chars long — the path-agnostic subtree estimate scaled up for\n * the access-path prefix that estimate omits. Used only for the extract/inline\n * decision; the running total uses exact emitted lengths.\n */\nexport function predictedInlineSize(\n ir: SchemaIR,\n inputLen: number,\n cache: WeakMap<SchemaIR, number>,\n): number {\n return estimateFastCost(ir, cache) * (1 + inputLen / PATH_GROWTH_DIVISOR);\n}\n\n/**\n * Floor for extraction: never hoist a sub-schema smaller than this even when\n * the enclosing function is over the cap — a tiny helper trades a real call for\n * no optimization benefit. Only sub-schemas big enough to matter are split.\n */\nexport const MIN_EXTRACT = 1_200;\n\n/** Approximate size contributed to the enclosing function by an extracted call `__fo_N(expr)`. */\nexport const CALL_COST = 24;\n\n/**\n * Node types whose fast-check is a self-contained boolean over a single input\n * expression and large enough to be worth hoisting into `function f(p){return …}`.\n * Thin wrappers (optional/nullable/default/…) are omitted: their inner schema is\n * visited through `generateFast` and gets hoisted on its own when large.\n */\nexport const HOISTABLE: ReadonlySet<SchemaIR[\"type\"]> = new Set([\n \"object\",\n \"record\",\n \"tuple\",\n \"discriminatedUnion\",\n \"union\",\n \"intersection\",\n]);\n\n/** A node's own contribution to the emitted fast-check, EXCLUDING its children. */\nfunction shallowFastCost(ir: SchemaIR): number {\n switch (ir.type) {\n case \"object\":\n return 50 + Object.keys(ir.properties).length * 25 + (ir.strict ? 120 : 0);\n case \"string\":\n return 20 + ir.checks.length * 35;\n case \"number\":\n return 25 + ir.checks.length * 30;\n case \"bigint\":\n case \"date\":\n return 25 + (ir.checks?.length ?? 0) * 25;\n case \"enum\":\n return 15 + ir.values.length * 12;\n case \"tuple\":\n return 40 + ir.items.length * 15;\n case \"union\":\n return 12 + ir.options.length * 6;\n case \"discriminatedUnion\":\n return 45 + ir.cases.length * 12;\n case \"array\":\n case \"record\":\n case \"set\":\n case \"map\":\n return 55;\n case \"file\":\n case \"templateLiteral\":\n return 40;\n case \"custom\":\n return 30;\n case \"literal\":\n case \"optional\":\n case \"nullable\":\n case \"default\":\n return 22;\n case \"recursiveRef\":\n case \"recursionTarget\":\n // Both emit just a call to a hosted helper; the target's `inner` is sized\n // independently when its own helper body is generated, so it is NOT\n // counted against the enclosing function here (see fastChildren).\n return 15;\n default:\n return 18;\n }\n}\n\n/** Child IR nodes that the fast generator recurses into (mirrors the fast schema generators). */\nfunction fastChildren(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.rest] : ir.items;\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 \"pipe\":\n return [ir.in, ir.out];\n case \"optional\":\n case \"nullable\":\n case \"readonly\":\n case \"default\":\n case \"catch\":\n case \"zodDelegate\":\n return [ir.inner];\n default:\n return [];\n }\n}\n\n/**\n * Estimated total size of a node's fast-check (the node plus everything inlined\n * beneath it). Memoized per IR node: schemas dedupe shared sub-trees and the\n * estimate is consulted at every nesting level, so without the cache a deep tree\n * would be re-walked quadratically.\n */\nexport function estimateFastCost(ir: SchemaIR, cache: WeakMap<SchemaIR, number>): number {\n const cached = cache.get(ir);\n if (cached !== undefined) return cached;\n // Defensive cycle break (the IR is a tree today; recursiveRef is a leaf).\n cache.set(ir, 0);\n let total = shallowFastCost(ir);\n for (const child of fastChildren(ir)) total += estimateFastCost(child, cache);\n cache.set(ir, total);\n return total;\n}\n\n// ─── Runtime cost (check ordering) ───────────────────────────────────────────\n\n/**\n * Assumed element count for unbounded collections, used only to weight a\n * container against its siblings when ordering an `&&` chain.\n */\nconst ASSUMED_ELEMENTS = 4;\n\n/** Runtime weight of one check on an already-type-confirmed value. */\nfunction checkRuntimeCost(kind: string): number {\n switch (kind) {\n // A `.test()` call costs ~9 ns of dispatch before it matches a character —\n // an order of magnitude above every other check, and the reason ordering\n // matters at all.\n case \"string_format\":\n return 100;\n // Zero-capture user predicate: a real call, cheaper than a regex.\n case \"refine_effect\":\n return 20;\n case \"includes\":\n case \"starts_with\":\n case \"ends_with\":\n return 6;\n case \"multiple_of\":\n case \"bigint_multiple_of\":\n return 4;\n default:\n // length/size/range comparisons: a load and a compare.\n return 1;\n }\n}\n\n/** A node's own runtime weight, EXCLUDING its children. */\nfunction shallowRuntimeCost(ir: SchemaIR): number {\n switch (ir.type) {\n case \"string\":\n case \"number\":\n return 2 + ir.checks.reduce((sum, c) => sum + checkRuntimeCost(c.kind), 0);\n case \"bigint\":\n case \"date\":\n return 3 + (ir.checks?.length ?? 0);\n case \"file\":\n return 3 + (ir.checks?.length ?? 0) * 2;\n case \"enum\":\n // Inlined `===` chain (or one hashed lookup) — sub-nanosecond either way.\n return 1 + Math.min(ir.values.length, 8);\n case \"object\":\n // Type guard, plus the strict pass's per-key membership test.\n return 3 + (ir.strict === true ? Object.keys(ir.properties).length : 0);\n case \"array\":\n case \"set\":\n case \"record\":\n case \"map\":\n case \"tuple\":\n return 3;\n case \"templateLiteral\":\n return 100;\n case \"custom\":\n return 20;\n case \"recursiveRef\":\n case \"recursionTarget\":\n // A recursive call expands into an unknown amount of work; treat it as\n // the most expensive sibling so it is probed last.\n return 200;\n default:\n return 1;\n }\n}\n\n/** estimateRuntimeCost against the per-compile memo hanging off the context. */\nfunction runtimeCostOf(ir: SchemaIR, ctx: CodeGenContext): number {\n return estimateRuntimeCost(ir, (ctx.fastRuntimeCostCache ??= new WeakMap<SchemaIR, number>()));\n}\n\n/**\n * Sort a fast-check's sibling conjuncts (or union options) cheapest-first.\n * Returns a new array; ties keep source order (Array#sort is stable), so a\n * schema whose members all cost the same emits byte-identical output.\n */\nexport function orderByRuntimeCost<T>(\n items: readonly T[],\n irOf: (item: T) => SchemaIR,\n ctx: CodeGenContext,\n): T[] {\n if (items.length < 2) return [...items];\n return [...items].sort((a, b) => runtimeCostOf(irOf(a), ctx) - runtimeCostOf(irOf(b), ctx));\n}\n\n/**\n * Estimated runtime cost of a node's fast-check, in arbitrary units calibrated\n * so a regex format check dominates a handful of type guards. Memoized per IR\n * node, like estimateFastCost — the estimate is consulted at every nesting\n * level, and shared sub-trees are common.\n *\n * Used to order the conjuncts of an `&&` chain cheapest-first. Accepting input\n * runs every conjunct regardless, so ordering is free there; REJECTING input\n * stops at the first false one, which is where a schema pays for probing a\n * `z.email()` before the `kind` literal that actually discriminates. Measured\n * on a 3-option union of objects that each declare `{email, kind, note}`:\n * 102 ns → 39 ns for an input matching the last option, and 102 ns → 6 ns for\n * one matching none.\n */\nfunction estimateRuntimeCost(ir: SchemaIR, cache: WeakMap<SchemaIR, number>): number {\n const cached = cache.get(ir);\n if (cached !== undefined) return cached;\n cache.set(ir, 0); // cycle break (mirrors estimateFastCost)\n let total = shallowRuntimeCost(ir);\n const children = fastChildren(ir);\n switch (ir.type) {\n case \"array\":\n case \"set\":\n case \"record\":\n case \"map\":\n // Per-element work, repeated for an assumed handful of entries.\n for (const child of children) total += estimateRuntimeCost(child, cache) * ASSUMED_ELEMENTS;\n break;\n case \"discriminatedUnion\":\n // O(1) switch: only the matched case runs. Charge the priciest option so\n // the estimate stays an upper bound.\n total += children.reduce((max, c) => Math.max(max, estimateRuntimeCost(c, cache)), 0);\n break;\n default:\n // object/tuple/union/intersection/wrappers: every child is on the path\n // (a union probes options until one matches — worst case, all of them).\n for (const child of children) total += estimateRuntimeCost(child, cache);\n break;\n }\n cache.set(ir, total);\n return total;\n}\n"],"mappings":";;;;;;;AA2BA,MAAa,cAAc;;;;;;;;AAS3B,MAAM,sBAAsB;;;;;;;AAQ5B,SAAgB,oBACd,IACA,UACA,OACQ;CACR,OAAO,iBAAiB,IAAI,KAAK,KAAK,IAAI,WAAW;AACvD;;;;;;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AAK,SACH,OAAO;EACT,KAAK,mBACH,OAAO;EACT,KAAK,UACH,OAAO;EACT,KAAK;EACL,KAAK,mBAGH,OAAO;EACT,SACE,OAAO;CACX;AACF;;AAGA,SAAS,cAAc,IAAc,KAA6B;CAChE,OAAO,oBAAoB,IAAK,IAAI,yCAAyB,IAAI,QAA0B,CAAE;AAC/F;;;;;;AAOA,SAAgB,mBACd,OACA,MACA,KACK;CACL,IAAI,MAAM,SAAS,GAAG,OAAO,CAAC,GAAG,KAAK;CACtC,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,MAAM,GAAG,MAAM,cAAc,KAAK,CAAC,GAAG,GAAG,IAAI,cAAc,KAAK,CAAC,GAAG,GAAG,CAAC;AAC5F;;;;;;;;;;;;;;;AAgBA,SAAS,oBAAoB,IAAc,OAA0C;CACnF,MAAM,SAAS,MAAM,IAAI,EAAE;CAC3B,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,MAAM,IAAI,IAAI,CAAC;CACf,IAAI,QAAQ,mBAAmB,EAAE;CACjC,MAAM,WAAW,aAAa,EAAE;CAChC,QAAQ,GAAG,MAAX;EACE,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;GAEH,KAAK,MAAM,SAAS,UAAU,SAAS,oBAAoB,OAAO,KAAK,IAAI;GAC3E;EACF,KAAK;GAGH,SAAS,SAAS,QAAQ,KAAK,MAAM,KAAK,IAAI,KAAK,oBAAoB,GAAG,KAAK,CAAC,GAAG,CAAC;GACpF;EACF;GAGE,KAAK,MAAM,SAAS,UAAU,SAAS,oBAAoB,OAAO,KAAK;GACvE;CACJ;CACA,MAAM,IAAI,IAAI,KAAK;CACnB,OAAO;AACT"}
@@ -81,6 +81,22 @@ function generateValidator(ir, name, options) {
81
81
  fastExpr = `${fastFnName}(input)`;
82
82
  }
83
83
  const buildFnName = generateBuild(ir, ctx);
84
+ if (ir.type === "zodDelegate" && rebuildsOutput(ir.inner) && buildFnName === null) {
85
+ ctx.preamble.length = 0;
86
+ ctx.usedHelpers.clear();
87
+ ctx.regexCache.clear();
88
+ ctx.effectFnCache?.clear();
89
+ ctx.valueCache?.clear();
90
+ const delegate = emitRfDelegate(ctx, ir.refIndex);
91
+ return {
92
+ code: ["/* zod-compiler */", ...ctx.preamble].join("\n"),
93
+ functionDef: `function ${fnName}(input){return ${delegate}(input);}`,
94
+ refCount: options?.refCount ?? 0,
95
+ usedHelpers: ctx.usedHelpers,
96
+ fastFnName: null,
97
+ fastTotal: false
98
+ };
99
+ }
84
100
  const buildIsFnName = ctx.buildSubstitutesValue === true ? null : fastFnName;
85
101
  const baseRefCount = options?.refCount ?? 0;
86
102
  if (options?.compact === true && fastExpr !== null && fastExpr !== "true" && !hasMutation(ir) && !hasNonRootTargets) {
@@ -239,7 +255,8 @@ function childIRs(ir) {
239
255
  case "default":
240
256
  case "catch":
241
257
  case "effect":
242
- case "recursionTarget": return [ir.inner];
258
+ case "recursionTarget":
259
+ case "zodDelegate": return [ir.inner];
243
260
  case "pipe": return [ir.in, ir.out];
244
261
  default: return [];
245
262
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/core/codegen/index.ts"],"sourcesContent":["import type { SchemaIR } from \"../types.js\";\nimport type { CodeGenContext, CodeGenResult, CodegenMode, RecTargetGen } from \"./context.js\";\nimport { generateBuild, rebuildsOutput } from \"./build-path.js\";\nimport { declareFastTemps, emitRfDelegate, hasMutation } from \"./context.js\";\nimport type { SharedSchemaPlan } from \"./dedupe.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.rootDelegateRefIndex}.\n */\n compact?: boolean | 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 };\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 const fg = createFastGen(\"input\", ctx);\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);\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 // `.is()` for a build-path schema is the fast expression — stripping reshapes\n // the payload, never the verdict. A substituted `.default()` breaks that: the\n // fast check demands a present value where the schema accepts its absence, so\n // the predicate is partial and `.is()` falls back to safeParse().success\n // (which runs the build pass, so it is no slower than the eager walk was).\n const buildIsFnName = ctx.buildSubstitutesValue === true ? null : 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-bound safeParse 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 !hasNonRootTargets\n ) {\n const delegate = emitRfDelegate(ctx, baseRefCount);\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},input);`,\n `}`,\n ].join(\"\\n\"),\n refCount: baseRefCount + 1,\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 rootDelegateRefIndex: baseRefCount,\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 = emitRfDelegate(ctx, baseRefCount);\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},input);`,\n `}`,\n ].join(\"\\n\"),\n refCount: baseRefCount + 1,\n usedHelpers: ctx.usedHelpers,\n fastFnName: null,\n fastTotal: false,\n isFnName: buildIsFnName,\n rootDelegateRefIndex: baseRefCount,\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)) {\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:input};}`,\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:input};}`,\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 fastFnName,\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 && !rebuildsOutput(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 fastFnName,\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 return [ir.inner];\n case \"pipe\":\n return [ir.in, ir.out];\n default:\n return [];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAuCA,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;CACvB;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;EACvB,UAAU,SAAS,IAAI;CACzB,CAAC;CAEH,MAAM,oBAAoB,eAAe,OAAO;CAYhD,MAAM,kBAAkB,IAAI,SAAS;CACrC,MAAM,iBAAiB,IAAI,IAAI,IAA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OACH,OAAO,CAAC,GAAG,SAAS;EACtB,KAAK;EACL,KAAK,sBACH,OAAO,GAAG;EACZ,KAAK,gBACH,OAAO,CAAC,GAAG,MAAM,GAAG,KAAK;EAC3B,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,mBACH,OAAO,CAAC,GAAG,KAAK;EAClB,KAAK,QACH,OAAO,CAAC,GAAG,IAAI,GAAG,GAAG;EACvB,SACE,OAAO,CAAC;CACZ;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/core/codegen/index.ts"],"sourcesContent":["import type { SchemaIR } from \"../types.js\";\nimport type { CodeGenContext, CodeGenResult, CodegenMode, RecTargetGen } from \"./context.js\";\nimport { generateBuild, rebuildsOutput } from \"./build-path.js\";\nimport { declareFastTemps, emitRfDelegate, hasMutation } from \"./context.js\";\nimport type { SharedSchemaPlan } from \"./dedupe.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.rootDelegateRefIndex}.\n */\n compact?: boolean | 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 };\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 const fg = createFastGen(\"input\", ctx);\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);\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. A substituted `.default()` breaks that: the\n // fast check demands a present value where the schema accepts its absence, so\n // the predicate is partial and `.is()` falls back to safeParse().success\n // (which runs the build pass, so it is no slower than the eager walk was).\n const buildIsFnName = ctx.buildSubstitutesValue === true ? null : 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-bound safeParse 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 !hasNonRootTargets\n ) {\n const delegate = emitRfDelegate(ctx, baseRefCount);\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},input);`,\n `}`,\n ].join(\"\\n\"),\n refCount: baseRefCount + 1,\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 rootDelegateRefIndex: baseRefCount,\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 = emitRfDelegate(ctx, baseRefCount);\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},input);`,\n `}`,\n ].join(\"\\n\"),\n refCount: baseRefCount + 1,\n usedHelpers: ctx.usedHelpers,\n fastFnName: null,\n fastTotal: false,\n isFnName: buildIsFnName,\n rootDelegateRefIndex: baseRefCount,\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)) {\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:input};}`,\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:input};}`,\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 fastFnName,\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 && !rebuildsOutput(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 fastFnName,\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":";;;;;;;;;;;;;;AAuCA,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;CACvB;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,O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AAM,uBAAO,IAAI,IAAc;CAC/B,MAAM,QAAQ,OAAuB;EACnC,IAAI,KAAK,IAAI,EAAE,GAAG;EAClB,KAAK,IAAI,EAAE;EACX,IAAI,GAAG,SAAS,qBAAqB,CAAC,IAAI,IAAI,GAAG,KAAK,GACpD,IAAI,IAAI,GAAG,OAAO,GAAG,KAAK;EAE5B,KAAK,MAAM,SAAS,SAAS,EAAE,GAAG,KAAK,KAAK;CAC9C;CACA,KAAK,IAAI;CACT,OAAO;AACT;;AAGA,SAAS,SAAS,IAAmC;CACnD,QAAQ,GAAG,MAAX;EACE,KAAK,UACH,OAAO,OAAO,OAAO,GAAG,UAAU;EACpC,KAAK,SACH,OAAO,CAAC,GAAG,OAAO;EACpB,KAAK,SACH,OAAO,GAAG,SAAS,OAAO,GAAG,QAAQ,CAAC,GAAG,GAAG,OAAO,GAAG,IAAI;EAC5D,KAAK;EACL,KAAK,OACH,OAAO,CAAC,GAAG,SAAS,GAAG,SAAS;EAClC,KAAK,OACH,OAAO,CAAC,GAAG,SAAS;EACtB,KAAK;EACL,KAAK,sBACH,OAAO,GAAG;EACZ,KAAK,gBACH,OAAO,CAAC,GAAG,MAAM,GAAG,KAAK;EAC3B,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,eACH,OAAO,CAAC,GAAG,KAAK;EAClB,KAAK,QACH,OAAO,CAAC,GAAG,IAAI,GAAG,GAAG;EACvB,SACE,OAAO,CAAC;CACZ;AACF"}
@@ -104,6 +104,12 @@ declare const ZC_SR_OK_DECL: string;
104
104
  * callbacks return undefined, so the guard short-circuits on the first operand.
105
105
  */
106
106
  declare const ZC_SR_RUN_DECL: string;
107
+ /**
108
+ * z.custom()/z.instanceof() fast verdict. Zod treats truthy predicate returns
109
+ * as success and raises $ZodAsyncError when a synchronous parse encounters a
110
+ * thenable, including a non-async function that happens to return a Promise.
111
+ */
112
+ declare const ZC_CUSTOM_OK_DECL: string;
107
113
  /**
108
114
  * superRefine slow-path merge: run the callback, then move its issues onto the
109
115
  * validator's list the way zod's finalizeIssue does — the node's path prefixed
@@ -123,5 +129,5 @@ declare const ZC_SR_DECL: string;
123
129
  /** Non-issue runtime helper declarations hosted in the virtual module. */
124
130
  declare const RUNTIME_HELPER_DECLS: Readonly<Record<string, string>>;
125
131
  //#endregion
126
- export { ISSUE_DECLS, RUNTIME_HELPER_DECLS, ZC_AB_DECL, ZC_FSR_DECL, ZC_FZ_DECL, ZC_HOP_DECL, ZC_PFX_DECL, ZC_SR_DECL, ZC_SR_OK_DECL, ZC_SR_RUN_DECL, abortingCodeTest, propertyKeyTest };
132
+ export { ISSUE_DECLS, RUNTIME_HELPER_DECLS, ZC_AB_DECL, ZC_CUSTOM_OK_DECL, ZC_FSR_DECL, ZC_FZ_DECL, ZC_HOP_DECL, ZC_PFX_DECL, ZC_SR_DECL, ZC_SR_OK_DECL, ZC_SR_RUN_DECL, abortingCodeTest, propertyKeyTest };
127
133
  //# sourceMappingURL=issue-decls.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"issue-decls.d.ts","names":[],"sources":["../../../src/core/codegen/issue-decls.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;cA4Ca,aAAa,SAAS;;;;;;cAgBtB;;;;;;;;;;cAYA;;iBAyBG,iBAAiB;;;;;;;;;;;;;;;cAkBpB;;;;;;;;;;;;cAaA;;;;;;;;;cAaA;;iBAIG,gBAAgB;;;;;;;;;;;;;;;;cAmBnB;;;;;;;;;;;;;cAgBA;;;;;;;;;;;;;;;;cAmBA;;cAQA,sBAAsB,SAAS"}
1
+ {"version":3,"file":"issue-decls.d.ts","names":[],"sources":["../../../src/core/codegen/issue-decls.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;cA4Ca,aAAa,SAAS;;;;;;cAgBtB;;;;;;;;;;cAYA;;iBAyBG,iBAAiB;;;;;;;;;;;;;;;cAkBpB;;;;;;;;;;;;cAaA;;;;;;;;;cAaA;;iBAIG,gBAAgB;;;;;;;;;;;;;;;;cAmBnB;;;;;;;;;;;;;cAgBA;;;;;;cASA;;;;;;;;;;;;;;;;cAmBA;;cAQA,sBAAsB,SAAS"}
@@ -120,6 +120,12 @@ const ZC_SR_OK_DECL = "function __zcSrOk(f,v){var p={value:v,issues:[]};__zcSrRu
120
120
  */
121
121
  const ZC_SR_RUN_DECL = "function __zcSrRun(f,p){var r=f(p);if(r&&typeof r.then===\"function\"){throw new __zcCore.$ZodAsyncError();}}";
122
122
  /**
123
+ * z.custom()/z.instanceof() fast verdict. Zod treats truthy predicate returns
124
+ * as success and raises $ZodAsyncError when a synchronous parse encounters a
125
+ * thenable, including a non-async function that happens to return a Promise.
126
+ */
127
+ const ZC_CUSTOM_OK_DECL = "function __zcCu(f,v){var r=f(v);if(r&&typeof r.then===\"function\"){throw new __zcCore.$ZodAsyncError();}return !!r;}";
128
+ /**
123
129
  * superRefine slow-path merge: run the callback, then move its issues onto the
124
130
  * validator's list the way zod's finalizeIssue does — the node's path prefixed
125
131
  * onto any path the user supplied, and the internal `inst`/`continue` fields
@@ -142,10 +148,11 @@ const RUNTIME_HELPER_DECLS = {
142
148
  __zcFz: ZC_FZ_DECL,
143
149
  __zcHop: ZC_HOP_DECL,
144
150
  __zcPfx: ZC_PFX_DECL,
151
+ __zcCu: ZC_CUSTOM_OK_DECL,
145
152
  __zcSr: ZC_SR_DECL,
146
153
  __zcSrOk: ZC_SR_OK_DECL
147
154
  };
148
155
  //#endregion
149
- export { ISSUE_DECLS, RUNTIME_HELPER_DECLS, ZC_AB_DECL, ZC_FSR_DECL, ZC_FZ_DECL, ZC_HOP_DECL, ZC_PFX_DECL, ZC_SR_DECL, ZC_SR_OK_DECL, ZC_SR_RUN_DECL, abortingCodeTest, propertyKeyTest };
156
+ export { ISSUE_DECLS, RUNTIME_HELPER_DECLS, ZC_AB_DECL, ZC_CUSTOM_OK_DECL, ZC_FSR_DECL, ZC_FZ_DECL, ZC_HOP_DECL, ZC_PFX_DECL, ZC_SR_DECL, ZC_SR_OK_DECL, ZC_SR_RUN_DECL, abortingCodeTest, propertyKeyTest };
150
157
 
151
158
  //# sourceMappingURL=issue-decls.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"issue-decls.js","names":[],"sources":["../../../src/core/codegen/issue-decls.ts"],"sourcesContent":["/**\n * Issue factory function bodies (statement form).\n *\n * These functions produce the same `{code, ...}` shapes that lean-mode\n * generated code would otherwise inline at every check site.\n * Hosted in \"virtual:zod-compiler/runtime\" and called as `__zcTS(...)` etc.\n *\n * Argument convention (positional, kept short to minimize call-site bytes):\n * __zcTS(minimum, origin, inclusive, input, path, msg?) — too_small\n * __zcTB(maximum, origin, inclusive, input, path, msg?) — too_big\n * __zcIT(expected, input, path, msg?) — invalid_type\n * __zcIF(format, input, path, extra?, msg?) — invalid_format (extra merged into result)\n * __zcIV(values, input, path, msg?) — invalid_value\n * __zcUK(keys, input, path, msg?) — unrecognized_keys\n *\n * The trailing msg argument carries a static custom error message; when\n * absent, the __zcFin finalizer applies the configured locale default.\n */\n\nconst ZC_TS_DECL =\n 'function __zcTS(m,o,i,inp,p,msg){var r={code:\"too_small\",minimum:m,origin:o,inclusive:i,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_TS_EXACT_DECL =\n 'function __zcTSx(m,o,inp,p,msg){var r={code:\"too_small\",minimum:m,origin:o,inclusive:true,exact:true,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_TB_DECL =\n 'function __zcTB(m,o,i,inp,p,msg){var r={code:\"too_big\",maximum:m,origin:o,inclusive:i,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_TB_EXACT_DECL =\n 'function __zcTBx(m,o,inp,p,msg){var r={code:\"too_big\",maximum:m,origin:o,inclusive:true,exact:true,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_IT_DECL =\n 'function __zcIT(e,inp,p,msg){var r={code:\"invalid_type\",expected:e,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_IF_DECL =\n 'function __zcIF(f,inp,p,extra,msg){var r={code:\"invalid_format\",format:f,input:inp,path:p};if(extra)Object.assign(r,extra);if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_IV_DECL =\n 'function __zcIV(values,inp,p,msg){var r={code:\"invalid_value\",values:values,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_UK_DECL =\n 'function __zcUK(k,inp,p,msg){var r={code:\"unrecognized_keys\",keys:k,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\n/** All issue factory declarations indexed by helper name. */\nexport const ISSUE_DECLS: Readonly<Record<string, string>> = {\n __zcTS: ZC_TS_DECL,\n __zcTSx: ZC_TS_EXACT_DECL,\n __zcTB: ZC_TB_DECL,\n __zcTBx: ZC_TB_EXACT_DECL,\n __zcIT: ZC_IT_DECL,\n __zcIF: ZC_IF_DECL,\n __zcIV: ZC_IV_DECL,\n __zcUK: ZC_UK_DECL,\n};\n\n/**\n * Float-safe remainder — byte-for-byte port of zod's util.floatSafeRemainder.\n * Raw `%` mis-rejects valid multiples of decimal steps (0.3 % 0.1 !== 0);\n * zod scales both operands to integers by their decimal-place count first.\n */\nexport const ZC_FSR_DECL =\n 'function __zcFsr(v,s){var vd=((\"\"+v).split(\".\")[1]||\"\").length;var ss=\"\"+s;var sd=(ss.split(\".\")[1]||\"\").length;if(sd===0&&/\\\\d?e-\\\\d?/.test(ss)){var m=ss.match(/\\\\d?e-(\\\\d?)/);if(m&&m[1]){sd=parseInt(m[1],10);}}var d=vd>sd?vd:sd;var vi=parseInt(v.toFixed(d).replace(\".\",\"\"),10);var si=parseInt(s.toFixed(d).replace(\".\",\"\"),10);return (vi%si)/Math.pow(10,d);}';\n\n/**\n * Hoisted `Object.prototype.hasOwnProperty` reference. Record fast/slow paths\n * iterate keys with `for(k in o)` (no `Object.keys` array allocation) and guard\n * each key with `__zcHop.call(o,k)` to skip inherited enumerable properties —\n * yielding the exact own-enumerable string-key set `Object.keys` would, so\n * fast/slow stay in agreement and parity with zod's own-key record semantics is\n * preserved. The hoisted reference inlines in V8; reading the prototype property\n * per call would not.\n */\nexport const ZC_HOP_DECL = \"const __zcHop=Object.prototype.hasOwnProperty;\";\n\n/**\n * Issue codes zod raises from a schema's `_zod.parse` rather than from a check,\n * and which therefore carry `continue !== true` — what `util.aborted` looks for.\n *\n * Everything a CHECK produces (`too_small`, `too_big`, `invalid_format`,\n * `not_multiple_of`, a refine's `custom`) is continuable, because `$ZodCheck`\n * sets `continue: !def.abort` and an `abort: true` check costs the schema its\n * compiled path anyway — so classifying by code alone is exact for generated\n * issues.\n *\n * Read by {@link ZC_AB_DECL} and by the union's option-pruning loop, which\n * applies the same rule inline over a per-option issue array.\n */\nconst ABORTING_ISSUE_CODES: readonly string[] = [\n \"invalid_type\",\n \"invalid_value\",\n \"invalid_union\",\n \"unrecognized_keys\",\n \"invalid_key\",\n \"invalid_element\",\n];\n\n/** `c===\"invalid_type\"||c===\"invalid_value\"||…` over the code held in `codeExpr`. */\nexport function abortingCodeTest(codeExpr: string): string {\n return ABORTING_ISSUE_CODES.map((code) => `${codeExpr}===${JSON.stringify(code)}`).join(\"||\");\n}\n\n/**\n * Port of zod's `util.aborted(payload, startIndex)`: has anything since\n * `startIndex` produced a NON-continuable issue?\n *\n * zod gates a schema's check chain on this (`runChecks`: `else if (isAborted)\n * continue`), which is what makes a container's `.refine()` still run after a\n * property or element failed its own `min`/`max`/format check, and stop running\n * once one failed to parse at all. The `startIndex` is the issue count when the\n * node was entered, mirroring the fresh payload zod hands each sub-schema.\n *\n * Size/length checks are exempt in zod — they declare a `when` predicate, which\n * bypasses the abort gate — so generated code leaves those ungated and only\n * wraps the refine/superRefine effects.\n */\nexport const ZC_AB_DECL = `function __zcAb(e,i){for(;i<e.length;i++){var c=e[i].code;if(${abortingCodeTest(\"c\")})return true;}return false;}`;\n\n/**\n * Port of zod's `util.finalizeIssue` for issues NESTED inside an\n * `invalid_key` / `invalid_element` wrapper. Those never reach the top-level\n * finalization loop (which walks only the outer array), so zod finalizes them\n * where it builds the wrapper: locale message applied when none was baked in,\n * `input` cleared. Their `path` stays RELATIVE to the key or value schema — zod\n * ran it on a fresh payload — so nothing rewrites it.\n *\n * `input` is cleared by assignment rather than `delete`, matching the top-level\n * finalizer and the union's per-option loop.\n */\nexport const ZC_FZ_DECL =\n \"function __zcFz(e){for(var i=0;i<e.length;i++){var s=e[i];\" +\n 'if(s.message===undefined&&typeof __zcMsg===\"function\")s.message=__zcMsg(s);' +\n \"s.input=undefined;}return e;}\";\n\n/**\n * Port of zod's `util.prefixIssues(key, issues)` for a map entry whose key is a\n * property-key type: each issue's RELATIVE path is spliced onto the map's own\n * path plus the key, and the issue moves into the parent's array.\n *\n * `b.concat(k,x.path)` flattens `x.path` one level, giving exactly\n * `[...base, key, ...relative]`.\n */\nexport const ZC_PFX_DECL =\n \"function __zcPfx(d,s,b,k){for(var i=0;i<s.length;i++){var x=s[i];x.path=b.concat(k,x.path);d.push(x);}}\";\n\n/** Does `keyExpr` hold one of zod's `util.propertyKeyTypes` (string|number|symbol)? */\nexport function propertyKeyTest(keyExpr: string): string {\n return `typeof ${keyExpr}===\"string\"||typeof ${keyExpr}===\"number\"||typeof ${keyExpr}===\"symbol\"`;\n}\n\n/**\n * superRefine fast-check: run the payload callback on a throwaway payload and\n * report whether it both added nothing AND left the value alone. zod's own\n * wrapper (the referenced function) installs `addIssue` and normalizes what the\n * user adds, so the verdict is zod's; the issues themselves are re-collected by\n * the slow walk.\n *\n * The `p.value===v` half is what lets a superRefine node keep a fast path at\n * all. `value` is writable public API ($RefinementCtx extends ParsePayload), so\n * a callback may rewrite it, and the fast path's caller returns the ORIGINAL\n * input on success — which would then be stale. Reporting false when the value\n * moved routes those parses into the slow walk, which propagates the new value\n * (see ZC_SR_DECL). Callbacks that only validate — effectively all of them —\n * still take the fast exit.\n */\nexport const ZC_SR_OK_DECL =\n \"function __zcSrOk(f,v){var p={value:v,issues:[]};__zcSrRun(f,p);\" +\n \"return p.issues.length===0&&p.value===v;}\";\n\n/**\n * Module-local (never imported by generated code) — __zcSr/__zcSrOk call it.\n * Lean mode declares it in the runtime module beside them; inline mode pushes it\n * into the preamble alongside whichever of the two is used.\n *\n * Invoke the referenced wrapper, reproducing zod's synchronous-parse contract:\n * a callback that returns a promise makes zod raise $ZodAsyncError rather than\n * silently accepting. Because the ref points at zod's superRefine WRAPPER, not\n * the user's function, an async callback cannot be detected while extracting —\n * the returned thenable is the only evidence, so the test lives here. Sync\n * callbacks return undefined, so the guard short-circuits on the first operand.\n */\nexport const ZC_SR_RUN_DECL =\n \"function __zcSrRun(f,p){var r=f(p);\" +\n 'if(r&&typeof r.then===\"function\"){throw new __zcCore.$ZodAsyncError();}}';\n\n/**\n * superRefine slow-path merge: run the callback, then move its issues onto the\n * validator's list the way zod's finalizeIssue does — the node's path prefixed\n * onto any path the user supplied, and the internal `inst`/`continue` fields\n * dropped (they are zod bookkeeping, deleted before the issue is user-visible).\n *\n * Returns the payload, so the caller can write `.value` back (the callback may\n * have rewritten it) and read `.aborted`. Aborted is set when any issue aborts\n * in zod's sense (`continue !== true`, which covers `fatal: true` and the string\n * shorthand, whose issue carries no `continue` at all) — or when the callback\n * set it directly, also public payload API. A union option uses it to mark\n * itself aborted, matching how zod prunes option errors; without it an option\n * failing only through superRefine would be surfaced directly instead of inside\n * `invalid_union`.\n */\nexport const ZC_SR_DECL =\n \"function __zcSr(f,v,p,e){var q={value:v,issues:[]};__zcSrRun(f,q);\" +\n \"for(var i=0;i<q.issues.length;i++){var s=q.issues[i],t={};\" +\n 'for(var k in s){if(k!==\"inst\"&&k!==\"continue\")t[k]=s[k];}' +\n \"if(s.continue!==true)q.aborted=true;\" +\n \"t.path=s.path&&s.path.length?p.concat(s.path):p;e.push(t);}return q;}\";\n\n/** Non-issue runtime helper declarations hosted in the virtual module. */\nexport const RUNTIME_HELPER_DECLS: Readonly<Record<string, string>> = {\n __zcAb: ZC_AB_DECL,\n __zcFsr: ZC_FSR_DECL,\n __zcFz: ZC_FZ_DECL,\n __zcHop: ZC_HOP_DECL,\n __zcPfx: ZC_PFX_DECL,\n __zcSr: ZC_SR_DECL,\n __zcSrOk: ZC_SR_OK_DECL,\n};\n"],"mappings":";AA4CA,MAAa,cAAgD;CAC3D,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;AACV;;;;;;AAOA,MAAa,cACX;;;;;;;;;;AAWF,MAAa,cAAc;;;;;;;;;;;;;;AAe3B,MAAM,uBAA0C;CAC9C;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAgB,iBAAiB,UAA0B;CACzD,OAAO,qBAAqB,KAAK,SAAS,GAAG,SAAS,KAAK,KAAK,UAAU,IAAI,GAAG,CAAC,CAAC,KAAK,IAAI;AAC9F;;;;;;;;;;;;;;;AAgBA,MAAa,aAAa,gEAAgE,iBAAiB,GAAG,EAAE;;;;;;;;;;;;AAahH,MAAa,aACX;;;;;;;;;AAYF,MAAa,cACX;;AAGF,SAAgB,gBAAgB,SAAyB;CACvD,OAAO,UAAU,QAAQ,sBAAsB,QAAQ,sBAAsB,QAAQ;AACvF;;;;;;;;;;;;;;;;AAiBA,MAAa,gBACX;;;;;;;;;;;;;AAeF,MAAa,iBACX;;;;;;;;;;;;;;;;AAkBF,MAAa,aACX;;AAOF,MAAa,uBAAyD;CACpE,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,UAAU;AACZ"}
1
+ {"version":3,"file":"issue-decls.js","names":[],"sources":["../../../src/core/codegen/issue-decls.ts"],"sourcesContent":["/**\n * Issue factory function bodies (statement form).\n *\n * These functions produce the same `{code, ...}` shapes that lean-mode\n * generated code would otherwise inline at every check site.\n * Hosted in \"virtual:zod-compiler/runtime\" and called as `__zcTS(...)` etc.\n *\n * Argument convention (positional, kept short to minimize call-site bytes):\n * __zcTS(minimum, origin, inclusive, input, path, msg?) — too_small\n * __zcTB(maximum, origin, inclusive, input, path, msg?) — too_big\n * __zcIT(expected, input, path, msg?) — invalid_type\n * __zcIF(format, input, path, extra?, msg?) — invalid_format (extra merged into result)\n * __zcIV(values, input, path, msg?) — invalid_value\n * __zcUK(keys, input, path, msg?) — unrecognized_keys\n *\n * The trailing msg argument carries a static custom error message; when\n * absent, the __zcFin finalizer applies the configured locale default.\n */\n\nconst ZC_TS_DECL =\n 'function __zcTS(m,o,i,inp,p,msg){var r={code:\"too_small\",minimum:m,origin:o,inclusive:i,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_TS_EXACT_DECL =\n 'function __zcTSx(m,o,inp,p,msg){var r={code:\"too_small\",minimum:m,origin:o,inclusive:true,exact:true,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_TB_DECL =\n 'function __zcTB(m,o,i,inp,p,msg){var r={code:\"too_big\",maximum:m,origin:o,inclusive:i,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_TB_EXACT_DECL =\n 'function __zcTBx(m,o,inp,p,msg){var r={code:\"too_big\",maximum:m,origin:o,inclusive:true,exact:true,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_IT_DECL =\n 'function __zcIT(e,inp,p,msg){var r={code:\"invalid_type\",expected:e,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_IF_DECL =\n 'function __zcIF(f,inp,p,extra,msg){var r={code:\"invalid_format\",format:f,input:inp,path:p};if(extra)Object.assign(r,extra);if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_IV_DECL =\n 'function __zcIV(values,inp,p,msg){var r={code:\"invalid_value\",values:values,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\nconst ZC_UK_DECL =\n 'function __zcUK(k,inp,p,msg){var r={code:\"unrecognized_keys\",keys:k,input:inp,path:p};if(msg!==undefined)r.message=msg;return r;}';\n\n/** All issue factory declarations indexed by helper name. */\nexport const ISSUE_DECLS: Readonly<Record<string, string>> = {\n __zcTS: ZC_TS_DECL,\n __zcTSx: ZC_TS_EXACT_DECL,\n __zcTB: ZC_TB_DECL,\n __zcTBx: ZC_TB_EXACT_DECL,\n __zcIT: ZC_IT_DECL,\n __zcIF: ZC_IF_DECL,\n __zcIV: ZC_IV_DECL,\n __zcUK: ZC_UK_DECL,\n};\n\n/**\n * Float-safe remainder — byte-for-byte port of zod's util.floatSafeRemainder.\n * Raw `%` mis-rejects valid multiples of decimal steps (0.3 % 0.1 !== 0);\n * zod scales both operands to integers by their decimal-place count first.\n */\nexport const ZC_FSR_DECL =\n 'function __zcFsr(v,s){var vd=((\"\"+v).split(\".\")[1]||\"\").length;var ss=\"\"+s;var sd=(ss.split(\".\")[1]||\"\").length;if(sd===0&&/\\\\d?e-\\\\d?/.test(ss)){var m=ss.match(/\\\\d?e-(\\\\d?)/);if(m&&m[1]){sd=parseInt(m[1],10);}}var d=vd>sd?vd:sd;var vi=parseInt(v.toFixed(d).replace(\".\",\"\"),10);var si=parseInt(s.toFixed(d).replace(\".\",\"\"),10);return (vi%si)/Math.pow(10,d);}';\n\n/**\n * Hoisted `Object.prototype.hasOwnProperty` reference. Record fast/slow paths\n * iterate keys with `for(k in o)` (no `Object.keys` array allocation) and guard\n * each key with `__zcHop.call(o,k)` to skip inherited enumerable properties —\n * yielding the exact own-enumerable string-key set `Object.keys` would, so\n * fast/slow stay in agreement and parity with zod's own-key record semantics is\n * preserved. The hoisted reference inlines in V8; reading the prototype property\n * per call would not.\n */\nexport const ZC_HOP_DECL = \"const __zcHop=Object.prototype.hasOwnProperty;\";\n\n/**\n * Issue codes zod raises from a schema's `_zod.parse` rather than from a check,\n * and which therefore carry `continue !== true` — what `util.aborted` looks for.\n *\n * Everything a CHECK produces (`too_small`, `too_big`, `invalid_format`,\n * `not_multiple_of`, a refine's `custom`) is continuable, because `$ZodCheck`\n * sets `continue: !def.abort` and an `abort: true` check costs the schema its\n * compiled path anyway — so classifying by code alone is exact for generated\n * issues.\n *\n * Read by {@link ZC_AB_DECL} and by the union's option-pruning loop, which\n * applies the same rule inline over a per-option issue array.\n */\nconst ABORTING_ISSUE_CODES: readonly string[] = [\n \"invalid_type\",\n \"invalid_value\",\n \"invalid_union\",\n \"unrecognized_keys\",\n \"invalid_key\",\n \"invalid_element\",\n];\n\n/** `c===\"invalid_type\"||c===\"invalid_value\"||…` over the code held in `codeExpr`. */\nexport function abortingCodeTest(codeExpr: string): string {\n return ABORTING_ISSUE_CODES.map((code) => `${codeExpr}===${JSON.stringify(code)}`).join(\"||\");\n}\n\n/**\n * Port of zod's `util.aborted(payload, startIndex)`: has anything since\n * `startIndex` produced a NON-continuable issue?\n *\n * zod gates a schema's check chain on this (`runChecks`: `else if (isAborted)\n * continue`), which is what makes a container's `.refine()` still run after a\n * property or element failed its own `min`/`max`/format check, and stop running\n * once one failed to parse at all. The `startIndex` is the issue count when the\n * node was entered, mirroring the fresh payload zod hands each sub-schema.\n *\n * Size/length checks are exempt in zod — they declare a `when` predicate, which\n * bypasses the abort gate — so generated code leaves those ungated and only\n * wraps the refine/superRefine effects.\n */\nexport const ZC_AB_DECL = `function __zcAb(e,i){for(;i<e.length;i++){var c=e[i].code;if(${abortingCodeTest(\"c\")})return true;}return false;}`;\n\n/**\n * Port of zod's `util.finalizeIssue` for issues NESTED inside an\n * `invalid_key` / `invalid_element` wrapper. Those never reach the top-level\n * finalization loop (which walks only the outer array), so zod finalizes them\n * where it builds the wrapper: locale message applied when none was baked in,\n * `input` cleared. Their `path` stays RELATIVE to the key or value schema — zod\n * ran it on a fresh payload — so nothing rewrites it.\n *\n * `input` is cleared by assignment rather than `delete`, matching the top-level\n * finalizer and the union's per-option loop.\n */\nexport const ZC_FZ_DECL =\n \"function __zcFz(e){for(var i=0;i<e.length;i++){var s=e[i];\" +\n 'if(s.message===undefined&&typeof __zcMsg===\"function\")s.message=__zcMsg(s);' +\n \"s.input=undefined;}return e;}\";\n\n/**\n * Port of zod's `util.prefixIssues(key, issues)` for a map entry whose key is a\n * property-key type: each issue's RELATIVE path is spliced onto the map's own\n * path plus the key, and the issue moves into the parent's array.\n *\n * `b.concat(k,x.path)` flattens `x.path` one level, giving exactly\n * `[...base, key, ...relative]`.\n */\nexport const ZC_PFX_DECL =\n \"function __zcPfx(d,s,b,k){for(var i=0;i<s.length;i++){var x=s[i];x.path=b.concat(k,x.path);d.push(x);}}\";\n\n/** Does `keyExpr` hold one of zod's `util.propertyKeyTypes` (string|number|symbol)? */\nexport function propertyKeyTest(keyExpr: string): string {\n return `typeof ${keyExpr}===\"string\"||typeof ${keyExpr}===\"number\"||typeof ${keyExpr}===\"symbol\"`;\n}\n\n/**\n * superRefine fast-check: run the payload callback on a throwaway payload and\n * report whether it both added nothing AND left the value alone. zod's own\n * wrapper (the referenced function) installs `addIssue` and normalizes what the\n * user adds, so the verdict is zod's; the issues themselves are re-collected by\n * the slow walk.\n *\n * The `p.value===v` half is what lets a superRefine node keep a fast path at\n * all. `value` is writable public API ($RefinementCtx extends ParsePayload), so\n * a callback may rewrite it, and the fast path's caller returns the ORIGINAL\n * input on success — which would then be stale. Reporting false when the value\n * moved routes those parses into the slow walk, which propagates the new value\n * (see ZC_SR_DECL). Callbacks that only validate — effectively all of them —\n * still take the fast exit.\n */\nexport const ZC_SR_OK_DECL =\n \"function __zcSrOk(f,v){var p={value:v,issues:[]};__zcSrRun(f,p);\" +\n \"return p.issues.length===0&&p.value===v;}\";\n\n/**\n * Module-local (never imported by generated code) — __zcSr/__zcSrOk call it.\n * Lean mode declares it in the runtime module beside them; inline mode pushes it\n * into the preamble alongside whichever of the two is used.\n *\n * Invoke the referenced wrapper, reproducing zod's synchronous-parse contract:\n * a callback that returns a promise makes zod raise $ZodAsyncError rather than\n * silently accepting. Because the ref points at zod's superRefine WRAPPER, not\n * the user's function, an async callback cannot be detected while extracting —\n * the returned thenable is the only evidence, so the test lives here. Sync\n * callbacks return undefined, so the guard short-circuits on the first operand.\n */\nexport const ZC_SR_RUN_DECL =\n \"function __zcSrRun(f,p){var r=f(p);\" +\n 'if(r&&typeof r.then===\"function\"){throw new __zcCore.$ZodAsyncError();}}';\n\n/**\n * z.custom()/z.instanceof() fast verdict. Zod treats truthy predicate returns\n * as success and raises $ZodAsyncError when a synchronous parse encounters a\n * thenable, including a non-async function that happens to return a Promise.\n */\nexport const ZC_CUSTOM_OK_DECL =\n \"function __zcCu(f,v){var r=f(v);\" +\n 'if(r&&typeof r.then===\"function\"){throw new __zcCore.$ZodAsyncError();}return !!r;}';\n\n/**\n * superRefine slow-path merge: run the callback, then move its issues onto the\n * validator's list the way zod's finalizeIssue does — the node's path prefixed\n * onto any path the user supplied, and the internal `inst`/`continue` fields\n * dropped (they are zod bookkeeping, deleted before the issue is user-visible).\n *\n * Returns the payload, so the caller can write `.value` back (the callback may\n * have rewritten it) and read `.aborted`. Aborted is set when any issue aborts\n * in zod's sense (`continue !== true`, which covers `fatal: true` and the string\n * shorthand, whose issue carries no `continue` at all) — or when the callback\n * set it directly, also public payload API. A union option uses it to mark\n * itself aborted, matching how zod prunes option errors; without it an option\n * failing only through superRefine would be surfaced directly instead of inside\n * `invalid_union`.\n */\nexport const ZC_SR_DECL =\n \"function __zcSr(f,v,p,e){var q={value:v,issues:[]};__zcSrRun(f,q);\" +\n \"for(var i=0;i<q.issues.length;i++){var s=q.issues[i],t={};\" +\n 'for(var k in s){if(k!==\"inst\"&&k!==\"continue\")t[k]=s[k];}' +\n \"if(s.continue!==true)q.aborted=true;\" +\n \"t.path=s.path&&s.path.length?p.concat(s.path):p;e.push(t);}return q;}\";\n\n/** Non-issue runtime helper declarations hosted in the virtual module. */\nexport const RUNTIME_HELPER_DECLS: Readonly<Record<string, string>> = {\n __zcAb: ZC_AB_DECL,\n __zcFsr: ZC_FSR_DECL,\n __zcFz: ZC_FZ_DECL,\n __zcHop: ZC_HOP_DECL,\n __zcPfx: ZC_PFX_DECL,\n __zcCu: ZC_CUSTOM_OK_DECL,\n __zcSr: ZC_SR_DECL,\n __zcSrOk: ZC_SR_OK_DECL,\n};\n"],"mappings":";AA4CA,MAAa,cAAgD;CAC3D,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;AACV;;;;;;AAOA,MAAa,cACX;;;;;;;;;;AAWF,MAAa,cAAc;;;;;;;;;;;;;;AAe3B,MAAM,uBAA0C;CAC9C;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAgB,iBAAiB,UAA0B;CACzD,OAAO,qBAAqB,KAAK,SAAS,GAAG,SAAS,KAAK,KAAK,UAAU,IAAI,GAAG,CAAC,CAAC,KAAK,IAAI;AAC9F;;;;;;;;;;;;;;;AAgBA,MAAa,aAAa,gEAAgE,iBAAiB,GAAG,EAAE;;;;;;;;;;;;AAahH,MAAa,aACX;;;;;;;;;AAYF,MAAa,cACX;;AAGF,SAAgB,gBAAgB,SAAyB;CACvD,OAAO,UAAU,QAAQ,sBAAsB,QAAQ,sBAAsB,QAAQ;AACvF;;;;;;;;;;;;;;;;AAiBA,MAAa,gBACX;;;;;;;;;;;;;AAeF,MAAa,iBACX;;;;;;AAQF,MAAa,oBACX;;;;;;;;;;;;;;;;AAkBF,MAAa,aACX;;AAOF,MAAa,uBAAyD;CACpE,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,UAAU;AACZ"}
@@ -0,0 +1,10 @@
1
+ import { CustomIR } from "../../types.js";
2
+ import { FastGen, SlowGen } from "../context.js";
3
+ //#region src/core/codegen/schemas/custom.d.ts
4
+ /** Total hot-path predicate for z.custom() and z.instanceof(). */
5
+ declare function fastCustom(ir: CustomIR, g: FastGen): string;
6
+ /** Let Zod construct the exact custom/instanceof issue only after rejection. */
7
+ declare function slowCustom(ir: CustomIR, g: SlowGen): string;
8
+ //#endregion
9
+ export { fastCustom, slowCustom };
10
+ //# sourceMappingURL=custom.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"custom.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/custom.ts"],"mappings":";;;;iBAOgB,WAAW,IAAI,UAAU,GAAG;;iBAM5B,WAAW,IAAI,UAAU,GAAG"}