zod-compiler 2.0.6 → 2.0.8

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 (66) hide show
  1. package/README.md +59 -55
  2. package/dist/cli/emitter.d.ts.map +1 -1
  3. package/dist/cli/emitter.js +10 -4
  4. package/dist/cli/emitter.js.map +1 -1
  5. package/dist/core/codegen/build-path.d.ts.map +1 -1
  6. package/dist/core/codegen/build-path.js +15 -6
  7. package/dist/core/codegen/build-path.js.map +1 -1
  8. package/dist/core/codegen/context.d.ts +21 -3
  9. package/dist/core/codegen/context.d.ts.map +1 -1
  10. package/dist/core/codegen/context.js +17 -1
  11. package/dist/core/codegen/context.js.map +1 -1
  12. package/dist/core/codegen/index.d.ts +8 -0
  13. package/dist/core/codegen/index.d.ts.map +1 -1
  14. package/dist/core/codegen/index.js +13 -11
  15. package/dist/core/codegen/index.js.map +1 -1
  16. package/dist/core/codegen/issue-decls.d.ts +11 -1
  17. package/dist/core/codegen/issue-decls.d.ts.map +1 -1
  18. package/dist/core/codegen/issue-decls.js +12 -1
  19. package/dist/core/codegen/issue-decls.js.map +1 -1
  20. package/dist/core/codegen/schemas/string.d.ts +15 -2
  21. package/dist/core/codegen/schemas/string.d.ts.map +1 -1
  22. package/dist/core/codegen/schemas/string.js +97 -35
  23. package/dist/core/codegen/schemas/string.js.map +1 -1
  24. package/dist/core/compile.d.ts +4 -3
  25. package/dist/core/compile.d.ts.map +1 -1
  26. package/dist/core/compile.js +1 -0
  27. package/dist/core/compile.js.map +1 -1
  28. package/dist/core/extract/error-class.d.ts +32 -0
  29. package/dist/core/extract/error-class.d.ts.map +1 -0
  30. package/dist/core/extract/error-class.js +13 -0
  31. package/dist/core/extract/error-class.js.map +1 -0
  32. package/dist/core/iife.d.ts +52 -18
  33. package/dist/core/iife.d.ts.map +1 -1
  34. package/dist/core/iife.js +82 -20
  35. package/dist/core/iife.js.map +1 -1
  36. package/dist/core/pipeline.d.ts +1 -0
  37. package/dist/core/pipeline.d.ts.map +1 -1
  38. package/dist/core/pipeline.js +6 -1
  39. package/dist/core/pipeline.js.map +1 -1
  40. package/dist/core/types.d.ts +16 -5
  41. package/dist/core/types.d.ts.map +1 -1
  42. package/dist/is-zod-schema.d.ts +5 -3
  43. package/dist/is-zod-schema.d.ts.map +1 -1
  44. package/dist/is-zod-schema.js +3 -1
  45. package/dist/is-zod-schema.js.map +1 -1
  46. package/dist/jit.d.ts +5 -4
  47. package/dist/jit.d.ts.map +1 -1
  48. package/dist/jit.js +17 -3
  49. package/dist/jit.js.map +1 -1
  50. package/dist/register/index.js.map +1 -1
  51. package/dist/runtime.d.ts +3 -0
  52. package/dist/runtime.js +7 -2
  53. package/dist/static-filter.d.ts +19 -1
  54. package/dist/static-filter.d.ts.map +1 -1
  55. package/dist/static-filter.js +27 -1
  56. package/dist/static-filter.js.map +1 -1
  57. package/dist/unplugin/hoist-compile.d.ts.map +1 -1
  58. package/dist/unplugin/hoist-compile.js +5 -1
  59. package/dist/unplugin/hoist-compile.js.map +1 -1
  60. package/dist/unplugin/transform.d.ts.map +1 -1
  61. package/dist/unplugin/transform.js +10 -4
  62. package/dist/unplugin/transform.js.map +1 -1
  63. package/dist/unplugin/virtual.d.ts.map +1 -1
  64. package/dist/unplugin/virtual.js +6 -1
  65. package/dist/unplugin/virtual.js.map +1 -1
  66. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-class.d.ts","names":[],"sources":["../../../src/core/extract/error-class.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;KA2BY;iBAEI,gBAAgB,kBAAkB"}
@@ -0,0 +1,13 @@
1
+ //#region src/core/extract/error-class.ts
2
+ function zodErrorClassOf(schema) {
3
+ if (typeof schema !== "object" || schema === null) return "ZodError";
4
+ try {
5
+ const traits = schema._zod?.traits;
6
+ if (typeof traits?.has === "function" && !traits.has("ZodType")) return "$ZodError";
7
+ } catch {}
8
+ return "ZodError";
9
+ }
10
+ //#endregion
11
+ export { zodErrorClassOf };
12
+
13
+ //# sourceMappingURL=error-class.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-class.js","names":[],"sources":["../../../src/core/extract/error-class.ts"],"sourcesContent":["/**\n * The error class a schema's own parse methods build, which a compiled\n * validator installed on that schema has to build too.\n *\n * Classic `zod` and `zod/mini` share every internal the compiler reads\n * (`_zod.def`, `_zod.bag`, the checks), so one IR and one validator serve both.\n * The error a failed parse hands back is where they part. Classic methods build\n * classic's `ZodError`: `name: \"ZodError\"`, `.format()` and `.flatten()`, and\n * the `\"ZodError\"` trait that `instanceof z.ZodError` tests. Mini's methods\n * call zod/v4/core's parse functions, which build core's `$ZodError`:\n * `name: \"$ZodError\"`, none of those methods, and the `\"$ZodError\"` trait\n * alone. The issues are the same either way, but the class is observable, and\n * a compiled Mini schema used to answer with the classic one.\n *\n * Decided by the ROOT schema, whose methods the validator replaces. A Mini\n * object holding a classic field still fails with Mini's error from its own\n * `parse()`, so its compiled replacement does too.\n *\n * Read off the `\"ZodType\"` trait, which only classic's `ZodType` constructor\n * adds (Mini's adds `\"ZodMiniType\"`). A schema built straight from\n * `zod/v4/core` carries neither and has no parse methods of its own; core's\n * `parse()` builds the core error for it, so that is the class it gets. A\n * schema whose traits cannot be read keeps the classic class, which is what\n * every schema got before the distinction existed.\n */\n\n/** The `name` zod gives the error class: classic's, or zod/v4/core's (Mini). */\nexport type ZodErrorClass = \"ZodError\" | \"$ZodError\";\n\nexport function zodErrorClassOf(schema: unknown): ZodErrorClass {\n if (typeof schema !== \"object\" || schema === null) return \"ZodError\";\n try {\n const traits = (schema as { _zod?: { traits?: { has?: unknown } } })._zod?.traits;\n if (typeof traits?.has === \"function\" && !(traits as Set<string>).has(\"ZodType\")) {\n return \"$ZodError\";\n }\n } catch {\n // A Proxy trapping `get`: nothing zod built, so nothing to match.\n }\n return \"ZodError\";\n}\n"],"mappings":";AA6BA,SAAgB,gBAAgB,QAAgC;CAC9D,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO;CAC1D,IAAI;EACF,MAAM,SAAU,OAAqD,MAAM;EAC3E,IAAI,OAAO,QAAQ,QAAQ,cAAc,CAAE,OAAuB,IAAI,SAAS,GAC7E,OAAO;CAEX,QAAQ,CAER;CACA,OAAO;AACT"}
@@ -1,12 +1,21 @@
1
1
  import { CompiledSchemaInfo } from "./pipeline.js";
2
2
  //#region src/core/iife.d.ts
3
3
  /**
4
- * Import statement required by generateIIFE output (references
4
+ * Import statements required by generateIIFE output (references
5
5
  * __zodCompilerConfig). `core` is bound for $ZodAsyncError: superRefine and
6
6
  * custom callbacks may only reveal that they are async through the promise
7
- * they return, at which point zod's own synchronous parse raises.
7
+ * they return, at which point zod's own synchronous parse raises. It also
8
+ * supplies `$ZodRealError`, the error class `zod/mini` schemas fail with (see
9
+ * FAIL_CORE_CLASS_DECL); `ZodRealError` is classic's.
10
+ *
11
+ * `core` comes from `zod/v4/core` directly — the same module object classic
12
+ * re-exports as `core`, but reached as a namespace IMPORT, whose member reads a
13
+ * bundler can resolve one by one. Through classic's `export * as core`
14
+ * re-export, esbuild instead materializes the whole namespace, every locale
15
+ * included: a `zod/mini` bundle touching one `__zcCore` member measured 20 KB
16
+ * before that read and 398 KB after.
8
17
  */
9
- declare const ZOD_CONFIG_IMPORT = "import { config as __zodCompilerConfig, core as __zcCore, ZodRealError as __zcZodError } from \"zod\";";
18
+ declare const ZOD_CONFIG_IMPORT: string;
10
19
  /**
11
20
  * File-level `__zcMsg` declaration (must appear once after ZOD_CONFIG_IMPORT):
12
21
  * the message an issue gets when nothing was baked into it at build time.
@@ -53,23 +62,37 @@ declare const ZOD_MSG_DECLARATION: string;
53
62
  * trace) — stays deferred inside the cached accessor exactly as before, since
54
63
  * the issues array is observable solely through `.error`.
55
64
  *
56
- * `input` is `delete`d, not assigned `undefined`. Key PRESENCE is observable —
57
- * `"input" in issue`, `Object.keys(issue)`, object spread, `toStrictEqual`
58
- * against a zod issue — and zod's `util.finalizeIssue` does `delete full.input`
59
- * whenever `reportInput` is off, so assignment left every compiled issue one
60
- * enumerable key wider than zod's. The delete's dictionary-mode transition is
61
- * affordable precisely BECAUSE of the deferral above: it runs only after a
62
- * caller asks for `.error` on a failed parse, and is memoised in `_c`. Neither
63
- * a successful parse nor a `.success`/`.is()` check on a rejected one reaches
64
- * it — measured, the two are unchanged, while the `.error` read itself goes
65
- * ~3.95us -> ~4.19us per failure, i.e. ~6% of a path whose cost is already
66
- * dominated by the ZodError construction on the next line (stack capture plus a
67
- * JSON.stringify of every issue).
65
+ * `input` and `continue` are left OUT, not assigned `undefined`. Key PRESENCE is
66
+ * observable — `"input" in issue`, `Object.keys(issue)`, object spread,
67
+ * `toStrictEqual` against a zod issue — and zod's `util.finalizeIssue` deletes
68
+ * `continue`, and `input` whenever `reportInput` is off, so assignment left every
69
+ * compiled issue one enumerable key wider than zod's. Each issue is COPIED
70
+ * without them rather than `delete`d from: removing a key that is not the last
71
+ * one added drops the object into V8's dictionary mode, ~70 ns an issue. `.error`
72
+ * over six issues went 1.49 -> 1.06 us, over one 653 -> 608 ns. The copy keeps
73
+ * key order and takes own keys only, so an enumerable key added to
74
+ * `Object.prototype` stays out, as it does from zod's spread. All of it runs only
75
+ * after a caller asks for `.error` on a failed parse, and is memoised in `_c`.
68
76
  */
69
77
  declare const FAIL_CLASS_DECL: string;
78
+ /**
79
+ * {@link FAIL_CLASS_DECL} for a schema that fails with zod/v4/core's
80
+ * `$ZodError` instead of classic's `ZodError`: `zod/mini`, whose methods call
81
+ * core's parse functions, and raw core (see zodErrorClassOf). The finalization
82
+ * is identical; only the class constructed at the end differs, and with it
83
+ * everything the class carries (`name`, the trait `instanceof` tests,
84
+ * classic's `.format()`/`.flatten()`).
85
+ *
86
+ * A class of its own, with its own finalizers, rather than a constructor
87
+ * picked per failure: generated code names the pair its schema needs, so a
88
+ * bundle keeps only the class its validators construct (see failClassDecl).
89
+ */
90
+ declare const FAIL_CORE_CLASS_DECL: string;
70
91
  /** Eager finalizer (mutation / partial-fast-path schemas): issues already
71
92
  * collected in `e`; success short-circuits to a plain result literal. */
72
- declare const FIN_DECL = "function __zcFin(e,d){if(!e.length)return{success:true,data:d};return new __ZcFail(e,null,null);}";
93
+ declare const FIN_DECL: string;
94
+ /** {@link FIN_DECL} for schemas failing with core's `$ZodError` (see {@link FAIL_CORE_CLASS_DECL}). */
95
+ declare const FIN_CORE_DECL: string;
73
96
  /**
74
97
  * Deferred-collection finalizer for Fast-Path-eligible schemas. When the
75
98
  * fast check fails, the ENTIRE slow path (the issue-collecting re-walk) is
@@ -92,7 +115,18 @@ declare const FIN_DECL = "function __zcFin(e,d){if(!e.length)return{success:true
92
115
  * mutated value (zod materializes at parse time). Same caveat class as the
93
116
  * documented __zcFin deferral.
94
117
  */
95
- declare const FIN_DEFERRED_DECL = "function __zcFinD(f,inp){return new __ZcFail(null,f,inp);}";
118
+ declare const FIN_DEFERRED_DECL: string;
119
+ /** {@link FIN_DEFERRED_DECL} for schemas failing with core's `$ZodError` (see {@link FAIL_CORE_CLASS_DECL}). */
120
+ declare const FIN_DEFERRED_CORE_DECL: string;
121
+ /**
122
+ * Whether generated code that uses `helpers` builds core `$ZodError`s.
123
+ *
124
+ * Every emitter has always supplied the classic `__zcFin` whether or not any
125
+ * validator calls it. A file whose validators fail with core errors skips that
126
+ * default (a validator that does call it names it anyway): there it would be
127
+ * dead code that reaches for classic zod's error class.
128
+ */
129
+ declare function usesCoreErrors(helpers: ReadonlySet<string>): boolean;
96
130
  /**
97
131
  * Compact-mode failure class — a lazy failure that delegates error reporting to
98
132
  * the ORIGINAL Zod schema's `safeParse`. Used by `output: "compact"`, where the
@@ -255,5 +289,5 @@ declare function generateIIFE(schemaExpr: string, schema: CompiledSchemaInfo, op
255
289
  pure?: boolean | undefined;
256
290
  }): string;
257
291
  //#endregion
258
- export { FAILZ_CLASS_DECL, FAIL_CLASS_DECL, FINZ_DECL, FIN_DECL, FIN_DEFERRED_DECL, MK_VALIDATOR_DECL, ZOD_CONFIG_IMPORT, ZOD_MSG_DECLARATION, generateIIFE, iifeDerefsSchema };
292
+ export { FAILZ_CLASS_DECL, FAIL_CLASS_DECL, FAIL_CORE_CLASS_DECL, FINZ_DECL, FIN_CORE_DECL, FIN_DECL, FIN_DEFERRED_CORE_DECL, FIN_DEFERRED_DECL, MK_VALIDATOR_DECL, ZOD_CONFIG_IMPORT, ZOD_MSG_DECLARATION, generateIIFE, iifeDerefsSchema, usesCoreErrors };
259
293
  //# sourceMappingURL=iife.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"iife.d.ts","names":[],"sources":["../../src/core/iife.ts"],"mappings":";;;;;;;;cAca;;;;;;;;;;;;;;;;;;;;cAsBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA8CA;;;cAUA;;;;;;;;;;;;;;;;;;;;;;;cAyBA;;;;;;;;;;;;;;;;;;;;;;;;;;cA2BA;;cAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAqGA;;;;;;;;;;;;;;;;;iBA6BG,iBAAiB,QAAQ;;;;;;;;;;;;;iBAgBzB,aACd,oBACA,QAAQ,oBACR;EAAY;EAAiC"}
1
+ {"version":3,"file":"iife.d.ts","names":[],"sources":["../../src/core/iife.ts"],"mappings":";;;;;;;;;;;;;;;;;cAuBa;;;;;;;;;;;;;;;;;;;;cAuBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA6CA;;;;;;;;;;;;;cAcA;;;cAmCA;;cAGA;;;;;;;;;;;;;;;;;;;;;;;cA4BA;;cAGA;;;;;;;;;iBAcG,eAAe,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;cA6B3B;;cAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAqGA;;;;;;;;;;;;;;;;;iBA6BG,iBAAiB,QAAQ;;;;;;;;;;;;;iBAgBzB,aACd,oBACA,QAAQ,oBACR;EAAY;EAAiC"}
package/dist/core/iife.js CHANGED
@@ -1,16 +1,25 @@
1
- import { RETAINED_SCHEMA_VAR } from "./codegen/context.js";
1
+ import { FINALIZERS, RETAINED_SCHEMA_VAR } from "./codegen/context.js";
2
2
  //#region src/core/iife.ts
3
3
  /**
4
4
  * Shared CompiledSchema<T> IIFE generation.
5
5
  * Used by both CLI emitter and unplugin transform.
6
6
  */
7
7
  /**
8
- * Import statement required by generateIIFE output (references
8
+ * Import statements required by generateIIFE output (references
9
9
  * __zodCompilerConfig). `core` is bound for $ZodAsyncError: superRefine and
10
10
  * custom callbacks may only reveal that they are async through the promise
11
- * they return, at which point zod's own synchronous parse raises.
11
+ * they return, at which point zod's own synchronous parse raises. It also
12
+ * supplies `$ZodRealError`, the error class `zod/mini` schemas fail with (see
13
+ * FAIL_CORE_CLASS_DECL); `ZodRealError` is classic's.
14
+ *
15
+ * `core` comes from `zod/v4/core` directly — the same module object classic
16
+ * re-exports as `core`, but reached as a namespace IMPORT, whose member reads a
17
+ * bundler can resolve one by one. Through classic's `export * as core`
18
+ * re-export, esbuild instead materializes the whole namespace, every locale
19
+ * included: a `zod/mini` bundle touching one `__zcCore` member measured 20 KB
20
+ * before that read and 398 KB after.
12
21
  */
13
- const ZOD_CONFIG_IMPORT = "import { config as __zodCompilerConfig, core as __zcCore, ZodRealError as __zcZodError } from \"zod\";";
22
+ const ZOD_CONFIG_IMPORT = "import { config as __zodCompilerConfig, ZodRealError as __zcZodError } from \"zod\";\nimport * as __zcCore from \"zod/v4/core\";";
14
23
  /**
15
24
  * File-level `__zcMsg` declaration (must appear once after ZOD_CONFIG_IMPORT):
16
25
  * the message an issue gets when nothing was baked into it at build time.
@@ -57,23 +66,60 @@ const ZOD_MSG_DECLARATION = "function __zcUw(m){return typeof m===\"string\"?m:(
57
66
  * trace) — stays deferred inside the cached accessor exactly as before, since
58
67
  * the issues array is observable solely through `.error`.
59
68
  *
60
- * `input` is `delete`d, not assigned `undefined`. Key PRESENCE is observable —
61
- * `"input" in issue`, `Object.keys(issue)`, object spread, `toStrictEqual`
62
- * against a zod issue — and zod's `util.finalizeIssue` does `delete full.input`
63
- * whenever `reportInput` is off, so assignment left every compiled issue one
64
- * enumerable key wider than zod's. The delete's dictionary-mode transition is
65
- * affordable precisely BECAUSE of the deferral above: it runs only after a
66
- * caller asks for `.error` on a failed parse, and is memoised in `_c`. Neither
67
- * a successful parse nor a `.success`/`.is()` check on a rejected one reaches
68
- * it — measured, the two are unchanged, while the `.error` read itself goes
69
- * ~3.95us -> ~4.19us per failure, i.e. ~6% of a path whose cost is already
70
- * dominated by the ZodError construction on the next line (stack capture plus a
71
- * JSON.stringify of every issue).
69
+ * `input` and `continue` are left OUT, not assigned `undefined`. Key PRESENCE is
70
+ * observable — `"input" in issue`, `Object.keys(issue)`, object spread,
71
+ * `toStrictEqual` against a zod issue — and zod's `util.finalizeIssue` deletes
72
+ * `continue`, and `input` whenever `reportInput` is off, so assignment left every
73
+ * compiled issue one enumerable key wider than zod's. Each issue is COPIED
74
+ * without them rather than `delete`d from: removing a key that is not the last
75
+ * one added drops the object into V8's dictionary mode, ~70 ns an issue. `.error`
76
+ * over six issues went 1.49 -> 1.06 us, over one 653 -> 608 ns. The copy keeps
77
+ * key order and takes own keys only, so an enumerable key added to
78
+ * `Object.prototype` stays out, as it does from zod's spread. All of it runs only
79
+ * after a caller asks for `.error` on a failed parse, and is memoised in `_c`.
80
+ */
81
+ const FAIL_CLASS_DECL = failClassDecl("__ZcFail", "__zcZodError");
82
+ /**
83
+ * {@link FAIL_CLASS_DECL} for a schema that fails with zod/v4/core's
84
+ * `$ZodError` instead of classic's `ZodError`: `zod/mini`, whose methods call
85
+ * core's parse functions, and raw core (see zodErrorClassOf). The finalization
86
+ * is identical; only the class constructed at the end differs, and with it
87
+ * everything the class carries (`name`, the trait `instanceof` tests,
88
+ * classic's `.format()`/`.flatten()`).
89
+ *
90
+ * A class of its own, with its own finalizers, rather than a constructor
91
+ * picked per failure: generated code names the pair its schema needs, so a
92
+ * bundle keeps only the class its validators construct (see failClassDecl).
93
+ */
94
+ const FAIL_CORE_CLASS_DECL = failClassDecl("__ZcFailC", "__zcCore.$ZodRealError");
95
+ /**
96
+ * The failure class, for either error flavor; `errorClass` is the constructor
97
+ * expression.
98
+ *
99
+ * Wrapped in a `@__PURE__` IIFE so a bundle drops whichever class its
100
+ * validators never construct. A bare declaration is kept by every bundler
101
+ * for the `Object.defineProperty` that installs the getter (rolldown and
102
+ * esbuild both measured): the core class would cost every classic bundle
103
+ * ~500 B, and the classic class cost every `zod/mini` bundle 2.3-3.1 KB, since
104
+ * it carries classic zod's error class in with it. The wrapper itself costs a
105
+ * classic bundle 26-64 B.
106
+ *
107
+ * The binding is a `var`, not a hoisted function, so it must be initialized
108
+ * before a validator fails. Every emitter declares it at the head of the module
109
+ * (or of the evaluated body, under `jit()`), ahead of the finalizers and of
110
+ * every statement that could run a validator.
72
111
  */
73
- const FAIL_CLASS_DECL = "function __ZcFail(e,f,i){this.success=false;this._e=e;this._f=f;this._i=i;this._c=undefined;}Object.defineProperty(__ZcFail.prototype,\"error\",{configurable:true,get:function(){if(this._c)return this._c;var e=this._f!==null?this._f(this._i):this._e;for(var i=0;i<e.length;i++){if(e[i].message===undefined&&typeof __zcMsg===\"function\")e[i].message=__zcMsg(e[i]);delete e[i].input;delete e[i].continue;}return this._c=new __zcZodError(e);}});";
112
+ function failClassDecl(name, errorClass) {
113
+ return `var ${name}=/* @__PURE__ */(function(){function ${name}(e,f,i){this.success=false;this._e=e;this._f=f;this._i=i;this._c=undefined;}Object.defineProperty(${name}.prototype,"error",{configurable:true,get:function(){if(this._c)return this._c;var e=this._f!==null?this._f(this._i):this._e;for(var i=0;i<e.length;i++){var s=e[i],o={},k;if(s.message===undefined&&typeof __zcMsg==="function")s.message=__zcMsg(s);for(k in s){if(k!=="input"&&k!=="continue"&&Object.prototype.hasOwnProperty.call(s,k))o[k]=s[k];}e[i]=o;}return this._c=new ${errorClass}(e);}});return ${name};})();`;
114
+ }
74
115
  /** Eager finalizer (mutation / partial-fast-path schemas): issues already
75
116
  * collected in `e`; success short-circuits to a plain result literal. */
76
- const FIN_DECL = "function __zcFin(e,d){if(!e.length)return{success:true,data:d};return new __ZcFail(e,null,null);}";
117
+ const FIN_DECL = finDecl(FINALIZERS.ZodError.eager, "__ZcFail");
118
+ /** {@link FIN_DECL} for schemas failing with core's `$ZodError` (see {@link FAIL_CORE_CLASS_DECL}). */
119
+ const FIN_CORE_DECL = finDecl(FINALIZERS.$ZodError.eager, "__ZcFailC");
120
+ function finDecl(name, failClass) {
121
+ return `function ${name}(e,d){if(!e.length)return{success:true,data:d};return new ${failClass}(e,null,null);}`;
122
+ }
77
123
  /**
78
124
  * Deferred-collection finalizer for Fast-Path-eligible schemas. When the
79
125
  * fast check fails, the ENTIRE slow path (the issue-collecting re-walk) is
@@ -96,7 +142,23 @@ const FIN_DECL = "function __zcFin(e,d){if(!e.length)return{success:true,data:d}
96
142
  * mutated value (zod materializes at parse time). Same caveat class as the
97
143
  * documented __zcFin deferral.
98
144
  */
99
- const FIN_DEFERRED_DECL = "function __zcFinD(f,inp){return new __ZcFail(null,f,inp);}";
145
+ const FIN_DEFERRED_DECL = finDeferredDecl(FINALIZERS.ZodError.deferred, "__ZcFail");
146
+ /** {@link FIN_DEFERRED_DECL} for schemas failing with core's `$ZodError` (see {@link FAIL_CORE_CLASS_DECL}). */
147
+ const FIN_DEFERRED_CORE_DECL = finDeferredDecl(FINALIZERS.$ZodError.deferred, "__ZcFailC");
148
+ function finDeferredDecl(name, failClass) {
149
+ return `function ${name}(f,inp){return new ${failClass}(null,f,inp);}`;
150
+ }
151
+ /**
152
+ * Whether generated code that uses `helpers` builds core `$ZodError`s.
153
+ *
154
+ * Every emitter has always supplied the classic `__zcFin` whether or not any
155
+ * validator calls it. A file whose validators fail with core errors skips that
156
+ * default (a validator that does call it names it anyway): there it would be
157
+ * dead code that reaches for classic zod's error class.
158
+ */
159
+ function usesCoreErrors(helpers) {
160
+ return helpers.has(FINALIZERS.$ZodError.eager) || helpers.has(FINALIZERS.$ZodError.deferred);
161
+ }
100
162
  /**
101
163
  * Compact-mode failure class — a lazy failure that delegates error reporting to
102
164
  * the ORIGINAL Zod schema's `safeParse`. Used by `output: "compact"`, where the
@@ -281,6 +343,6 @@ function generateIIFE(schemaExpr, schema, options) {
281
343
  ].join("\n");
282
344
  }
283
345
  //#endregion
284
- export { FAILZ_CLASS_DECL, FAIL_CLASS_DECL, FINZ_DECL, FIN_DECL, FIN_DEFERRED_DECL, MK_VALIDATOR_DECL, ZOD_CONFIG_IMPORT, ZOD_MSG_DECLARATION, generateIIFE, iifeDerefsSchema };
346
+ export { FAILZ_CLASS_DECL, FAIL_CLASS_DECL, FAIL_CORE_CLASS_DECL, FINZ_DECL, FIN_CORE_DECL, FIN_DECL, FIN_DEFERRED_CORE_DECL, FIN_DEFERRED_DECL, MK_VALIDATOR_DECL, ZOD_CONFIG_IMPORT, ZOD_MSG_DECLARATION, generateIIFE, iifeDerefsSchema, usesCoreErrors };
285
347
 
286
348
  //# sourceMappingURL=iife.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"iife.js","names":[],"sources":["../../src/core/iife.ts"],"sourcesContent":["/**\n * Shared CompiledSchema<T> IIFE generation.\n * Used by both CLI emitter and unplugin transform.\n */\n\nimport { RETAINED_SCHEMA_VAR } from \"./codegen/context.js\";\nimport type { CompiledSchemaInfo } from \"./pipeline.js\";\n\n/**\n * Import statement required by generateIIFE output (references\n * __zodCompilerConfig). `core` is bound for $ZodAsyncError: superRefine and\n * custom callbacks may only reveal that they are async through the promise\n * they return, at which point zod's own synchronous parse raises.\n */\nexport const ZOD_CONFIG_IMPORT =\n 'import { config as __zodCompilerConfig, core as __zcCore, ZodRealError as __zcZodError } from \"zod\";';\n\n/**\n * File-level `__zcMsg` declaration (must appear once after ZOD_CONFIG_IMPORT):\n * the message an issue gets when nothing was baked into it at build time.\n *\n * Resolves zod's tail of `finalizeIssue` — `config.customError` then\n * `config.localeError` then \"Invalid input\" — and does it PER CALL, because the\n * config is mutable: `z.config({ localeError })` in an entry point runs after\n * the schema modules it imports, so a value snapshotted at module init misses\n * it. Reading a captured `localeError` alone also dropped `customError`\n * outright, silently ignoring the global map most i18n setups install.\n *\n * The head of zod's chain — the schema's own `error` option — is baked into the\n * issue at build time and short-circuits this. The one link that cannot be\n * reproduced is a per-CALL `ctx.error`, which would have to travel through\n * `safeParse`; that entry point sits at V8's inlining budget, where even an\n * unused extra parameter measured ~12% on every parse.\n *\n * Only ever called while building an error, never on a successful parse.\n */\nexport const ZOD_MSG_DECLARATION =\n 'function __zcUw(m){return typeof m===\"string\"?m:(m===undefined||m===null?undefined:m.message);}' +\n \"var __zcMsg=function(iss){var c=__zodCompilerConfig(),m;\" +\n \"if(c.customError){m=__zcUw(c.customError(iss));if(m!==undefined&&m!==null)return m;}\" +\n \"if(c.localeError){m=__zcUw(c.localeError(iss));if(m!==undefined&&m!==null)return m;}\" +\n 'return \"Invalid input\";};';\n\n/**\n * Shared failure-result for __zcFin / __zcFinD. Inline mode (CLI emitter)\n * declares it once per compiled file; lean mode (all unplugin bundlers) declares\n * it once per bundle in the plugin-materialized runtime module (module-local —\n * generated code only ever references __zcFin/__zcFinD, never __ZcFail).\n *\n * Why a prototype getter and not `{success:false, get error(){...}}`: an object\n * literal with an inline accessor forces V8 down its slow accessor-defining\n * allocation path — ~110ns per failure, measured — which dominates the entire\n * invalid-input cost whenever callers never read `.error`. Hosting `error` on\n * the prototype turns each failure into a plain field-only instantiation (~2ns,\n * ~13x), with the lazy-cache semantics intact. (Trade-off: `error` is a\n * prototype accessor, so it no longer shows up in `Object.keys(result)` / spread\n * / JSON.stringify of the result wrapper — `.success`/`.error`/`.data` access,\n * destructuring, and `in` are unaffected.)\n *\n * One class serves both finalizers, so the instances share one hidden class:\n * __zcFin passes pre-collected issues in `_e` (with `_f===null`); __zcFinD\n * passes the hosted slow-walk in `_f` plus the input in `_i`, and the getter\n * runs the walk on first `.error` read. The whole finalization — locale fill\n * (__zcMsg applied ONLY when an issue carries no message, never overwriting a\n * baked-in custom/fallback message), input strip, and ZodError construction\n * (zod v4 JSON.stringifies every issue into `message` and captures a stack\n * trace) — stays deferred inside the cached accessor exactly as before, since\n * the issues array is observable solely through `.error`.\n *\n * `input` is `delete`d, not assigned `undefined`. Key PRESENCE is observable —\n * `\"input\" in issue`, `Object.keys(issue)`, object spread, `toStrictEqual`\n * against a zod issue — and zod's `util.finalizeIssue` does `delete full.input`\n * whenever `reportInput` is off, so assignment left every compiled issue one\n * enumerable key wider than zod's. The delete's dictionary-mode transition is\n * affordable precisely BECAUSE of the deferral above: it runs only after a\n * caller asks for `.error` on a failed parse, and is memoised in `_c`. Neither\n * a successful parse nor a `.success`/`.is()` check on a rejected one reaches\n * it — measured, the two are unchanged, while the `.error` read itself goes\n * ~3.95us -> ~4.19us per failure, i.e. ~6% of a path whose cost is already\n * dominated by the ZodError construction on the next line (stack capture plus a\n * JSON.stringify of every issue).\n */\nexport const FAIL_CLASS_DECL =\n \"function __ZcFail(e,f,i){this.success=false;this._e=e;this._f=f;this._i=i;this._c=undefined;}\" +\n 'Object.defineProperty(__ZcFail.prototype,\"error\",{configurable:true,get:function(){' +\n \"if(this._c)return this._c;\" +\n \"var e=this._f!==null?this._f(this._i):this._e;\" +\n 'for(var i=0;i<e.length;i++){if(e[i].message===undefined&&typeof __zcMsg===\"function\")e[i].message=__zcMsg(e[i]);delete e[i].input;delete e[i].continue;}' +\n \"return this._c=new __zcZodError(e);}});\";\n\n/** Eager finalizer (mutation / partial-fast-path schemas): issues already\n * collected in `e`; success short-circuits to a plain result literal. */\nexport const FIN_DECL =\n \"function __zcFin(e,d){if(!e.length)return{success:true,data:d};return new __ZcFail(e,null,null);}\";\n\n/**\n * Deferred-collection finalizer for Fast-Path-eligible schemas. When the\n * fast check fails, the ENTIRE slow path (the issue-collecting re-walk) is\n * pushed into the cached `.error` accessor instead of running eagerly:\n * fast-eligible schemas never mutate, so the walk's only output is the\n * issues array, which is observable solely through `.error` — one step\n * further along the same lazy boundary `__zcFin` already established (locale\n * fill, input strip, ZodError construction). A failed safeParse whose\n * `.error` is never read costs the fast check alone.\n *\n * Takes the schema's HOSTED slow-walk function plus the input — NOT a\n * per-call closure: `__zcFinD(__sw_N, input)` allocates only the result\n * object, where `__zcFinD(function(){...})` paid a closure environment and\n * function object per failure. Hosting the walk also shrinks safeParse to\n * two statements, within V8's inlining budget (the success-path result\n * literal becomes escape-analyzable at monomorphic call sites).\n *\n * The walk re-reads `input` at `.error`-read time; a caller that mutates\n * the input between safeParse and reading `.error` sees issues for the\n * mutated value (zod materializes at parse time). Same caveat class as the\n * documented __zcFin deferral.\n */\nexport const FIN_DEFERRED_DECL = \"function __zcFinD(f,inp){return new __ZcFail(null,f,inp);}\";\n\n/**\n * Compact-mode failure class — a lazy failure that delegates error reporting to\n * the ORIGINAL Zod schema's `safeParse`. Used by `output: \"compact\"`, where the\n * compiled slow walk is dropped entirely: a mutation-free schema's fast check\n * is the only generated validation, and on a fast-check failure the cold error\n * path is produced by the retained Zod schema itself (`zod` is the source of\n * truth, so the issues are byte-identical — no second validation engine).\n *\n * `_z` is the schema's PRISTINE safeParse method, captured by\n * emitRetainedMethod (see context.ts), and `_r` is its receiver — the `__zs`\n * binding generateIIFE places above that capture. Both are read before the\n * trailing `__zcMkv` call installs anything, so the method is zod's own\n * implementation, never the compiled delegate, avoiding infinite recursion\n * without allocating a bound function. The zod parse is deferred until `.error`\n * is read and cached, so\n * the common `safeParse(x).success`/`.is(x)` checks on invalid input cost only\n * the fast check (zod never runs) — the same deferral boundary `__zcFinD`\n * establishes for the compiled slow walk. Sound because compact mode is gated\n * on a TOTAL fast path: `fc(input) === false` ⟹ zod rejects, so `success:false`\n * holds without consulting zod.\n *\n * The getter returns zod's OWN ZodError verbatim (no locale fill / input strip /\n * re-wrap — zod already finalized it), so a delegated failure is exactly what\n * the unaltered schema would have produced.\n */\nexport const FAILZ_CLASS_DECL =\n \"function __ZcFailZ(z,r,i){this.success=false;this._z=z;this._r=r;this._i=i;this._c=undefined;}\" +\n 'Object.defineProperty(__ZcFailZ.prototype,\"error\",{configurable:true,get:function(){' +\n \"return this._c||(this._c=this._z.call(this._r,this._i).error);}});\";\n\n/** Compact-mode finalizer: retain a pristine safeParse, its receiver, and input lazily. */\nexport const FINZ_DECL = \"function __zcFinZ(z,r,i){return new __ZcFailZ(z,r,i);}\";\n\n/**\n * Validator factory. Inline mode (CLI emitter) declares it once per compiled\n * file; lean mode (all unplugin bundlers) exports it once per bundle from the\n * plugin-materialized runtime module — generated code never imports it from\n * the zod-compiler package itself, so zod-compiler stays a devDependency and\n * the helper set is always version-locked to the codegen that calls it.\n * Wraps a safeParse function into the CompiledSchema interface.\n *\n * IDENTITY-PRESERVING: with zodCompat (schema != null) the compiled\n * parse/safeParse/parseAsync/safeParseAsync are installed as OWN properties\n * on the original schema object, which is returned as-is. zod v4 keys\n * several APIs on object identity — toJSONSchema's ctx.seen registers the\n * object it is handed while each processor closure captures the original\n * inst (a wrapper crashes `optionalProcessor` with \"Cannot set properties\n * of undefined (setting 'ref')\" the moment a compiled schema is composed\n * into another schema), and globalRegistry/.meta() is a WeakMap keyed by\n * the schema instance (a wrapper silently loses OpenAPI titles/ids). An\n * Object.create wrapper breaks both; mutating the original breaks neither\n * (zod's internal parsing flows through _zod.run, never the public\n * methods, and derived schemas — .optional(), .extend() — are fresh\n * instances that fall back to plain zod). schema=null (zodCompat: false)\n * still produces a plain method-bag object.\n *\n * fc is the schema's hosted fast-check boolean function (null when no Fast\n * Path exists). parse()/parseAsync() try it first and return the input\n * directly on success: fc is small enough for V8 to inline, so the hot parse\n * path runs with zero allocations — calling fn would allocate an intermediate\n * SafeParseResult that escape analysis cannot remove (fn never inlines).\n * Fast-path-eligible schemas never mutate, so fc(input) ⟹ data === input.\n *\n * is is the TOTAL fast-check predicate (fc when the fast path is total, else\n * null). Installed as `.is()` — a zero-allocation boolean type guard. When\n * null (partial fast path or none) `.is()` derives from fn(input).success: a\n * partial fc can pass-through valid input but its `false` does not imply\n * rejection (a default/catch may still succeed), so it would be unsound as a\n * standalone guard.\n *\n * parseAsync/safeParseAsync wrap the SYNC validator, which is right for every\n * schema the compiler can reproduce — none of them are async. It is wrong for\n * the ones it cannot: an `async` refinement or a `z.promise()` extracts to a\n * Zod delegate, and delegating means calling Zod's SYNCHRONOUS safeParse, which\n * raises `$ZodAsyncError` by design. Wrapping that gave the compiled schema an\n * async pair that rejected with `$ZodAsyncError` for EVERY input — including\n * valid ones — where Zod resolves normally, so `await UserSchema.parseAsync(x)`\n * stopped working the moment any part of the schema went async.\n *\n * So both are guarded: a synchronous throw hands off to the schema's ORIGINAL\n * async method, captured before these are installed — the same escape hatch\n * `~standard` already uses for its throw path, and for the same reason (the\n * compiled validator has no async mode to offer, and Zod's is exact). It also\n * fixes the smaller wart that a throwing `fn` made `parseAsync` throw\n * SYNCHRONOUSLY rather than return a rejected promise. With `zodCompat: false`\n * there is no schema to delegate to and the throw propagates as before.\n *\n * `~standard` is REPLACED, not merely preserved. Zod builds it lazily as\n * `validate: (v) => safeParse(inst, v)` — the core FUNCTION, which goes straight\n * to `inst._zod.run`. It never reads the schema's own `safeParse` property, so\n * installing the compiled one leaves this route entirely uncompiled: measured\n * 271.7 ns against the compiled 26.6 ns on the same schema, i.e. Standard Schema\n * consumers (tRPC, Hono, TanStack) were getting plain Zod.\n *\n * Zod's own `~standard` is never READ, only overwritten. Zod installs the slot\n * with `util.defineLazy` — commented there as \"avoid creating objects for every\n * schema\" — so it is an accessor that builds `{version, vendor, validate}` plus\n * its closure on first touch. Reading it to capture a fallback fired that getter\n * for every compiled schema while the module was still initializing.\n *\n * How much that costs depends on the entry point, and only one of them is free:\n * classic `zod` forces the slot itself during `ZodType.init` (it does\n * `Object.assign(inst[\"~standard\"], { jsonSchema })`), so there the read hit an\n * already-built object and cost only an accessor call. `zod/mini` and raw\n * `zod/v4/core` never touch it, so for those the read built — and retained — an\n * object and a closure per schema, purely to capture a fallback the schema will\n * most likely never expose to a Standard Schema consumer.\n *\n * The throw path is rebuilt instead of captured. Zod's validate catches a\n * synchronous throw and retries through `safeParseAsync` — that is how an async\n * refinement resolves and how a throwing check surfaces as a rejected promise\n * rather than a synchronous throw — so calling the already-captured `zspa` and\n * mapping its result is the same route to the same result. `vendor` is likewise\n * a constant: schema discovery only ever admits zod schemas, and classic, mini\n * and core all hardcode `vendor: \"zod\"` themselves.\n *\n * Not carried over (unchanged by this, and pre-dating it): classic's\n * `~standard.jsonSchema` extension, which the replacement object has never\n * reproduced.\n *\n * Installed with defineProperty rather than assignment: Zod's lazy setter\n * redefines the slot as non-writable, so a second `__zcMkv` on the same schema\n * object — two exports aliasing one schema — would throw under ESM strict mode.\n *\n * A rebuilding schema (no `fc`) reaches `parse()` through `fn`, i.e. through a\n * SafeParseResult unwrapped a line later. Handing the build function over so\n * `parse()` could call it directly was measured and declined: the wrapper is a\n * young-generation bump allocation that V8 elides outright where `fn` inlines,\n * and even across eight schemas sharing this closure — where it cannot — the\n * direct call came out level (41.5 vs 41.8 ns), for a wider signature on every\n * bundle.\n */\nexport const MK_VALIDATOR_DECL =\n \"function __zcMkv(fn,schema,fc,is){var w=schema||{};var zpa=w.parseAsync,zspa=w.safeParseAsync;w.parse=fc?function(input){if(fc(input))return input;var r=fn(input);if(r.success)return r.data;throw r.error;}:function(input){var r=fn(input);if(r.success)return r.data;throw r.error;};w.safeParse=fn;w.safeParseAsync=function(input){try{return Promise.resolve(fn(input));}catch(e){if(zspa)return zspa(input);throw e;}};w.parseAsync=fc?function(input){try{if(fc(input))return Promise.resolve(input);var r=fn(input);if(r.success)return Promise.resolve(r.data);return Promise.reject(r.error);}catch(e){if(zpa)return zpa(input);throw e;}}:function(input){try{var r=fn(input);if(r.success)return Promise.resolve(r.data);return Promise.reject(r.error);}catch(e){if(zpa)return zpa(input);throw e;}};w.is=is||function(input){return fn(input).success;};\" +\n 'Object.defineProperty(w,\"~standard\",{configurable:true,value:{version:1,vendor:\"zod\",validate:function(input){var r;try{if(fc&&fc(input))return{value:input};r=fn(input);}catch(e){if(zspa)return zspa(input).then(function(q){return q.success?{value:q.data}:{issues:q.error.issues};});throw e;}return r.success?{value:r.data}:{issues:r.error.issues};}}});' +\n \"return w;}\";\n\nfunction extractFunctionName(functionDef: string): string {\n const match = /^function\\s+(\\w+)\\s*\\(/.exec(functionDef);\n if (!match?.[1]) {\n throw new Error(\"Cannot extract function name from generated code\");\n }\n return match[1];\n}\n\n/**\n * Does the IIFE's preamble DEREFERENCE the retained schema at evaluation time?\n *\n * Only `__rf` does: every entry is `__zs<accessPath>`, and an access path walks\n * the schema's structure — `._zod.innerType` fires a `z.lazy()` getter,\n * `.shape` materializes a `z.object()` shape (zod v4 reads every property\n * descriptor, so ONE `.shape` read fires ALL of an object's recursion getters).\n * Binding `__zs` itself does not: constructing the schema leaves deferred\n * callbacks unforced, and `usesRetainedSchema`'s only read is `__zs.safeParse`,\n * a prototype getter that binds the method and installs the bound copy on the\n * instance without touching the schema's structure.\n *\n * The distinction decides whether the IIFE may be evaluated inside the\n * INITIALIZER of the binding the schema's own deferred callbacks close over —\n * see the self-referential path in the unplugin's autoDiscover rewrite.\n */\nexport function iifeDerefsSchema(schema: CompiledSchemaInfo): boolean {\n return schema.refEntries.length > 0;\n}\n\n/**\n * Generate a `/* @__PURE__ * /` IIFE wrapping a compiled validator.\n *\n * @param schemaExpr - Expression resolving to the original Zod schema\n * (e.g. `\"UserSchema\"` in unplugin, `\"(__src_X as any).schema\"` in CLI)\n * @param schema\n * @param options - `pure: false` drops the `/* @__PURE__ * /` annotation, for\n * the one caller that emits the IIFE as a STATEMENT following the\n * declaration rather than as its initializer: there the call's whole point is\n * its side effect (`__zcMkv` installing the compiled methods on the schema),\n * and a bundler that believed it pure would drop the compilation outright.\n */\nexport function generateIIFE(\n schemaExpr: string,\n schema: CompiledSchemaInfo,\n options?: { zodCompat?: boolean | undefined; pure?: boolean | undefined },\n): string {\n const { codegenResult, refEntries } = schema;\n const fnName = extractFunctionName(codegenResult.functionDef);\n const zodCompat = options?.zodCompat !== false;\n // Every fallback access starts from the same source schema, and compact\n // delegation names it outright. Capture it once whenever either needs it, so\n // an inline initializer is not reconstructed for each path and again for the\n // identity-preserving __zcMkv target.\n const bindsSchema = refEntries.length > 0 || codegenResult.usesRetainedSchema === true;\n const retainedSchema = bindsSchema ? RETAINED_SCHEMA_VAR : schemaExpr;\n const schemaArg = zodCompat ? retainedSchema : \"null\";\n const fcArg = codegenResult.fastFnName ?? \"null\";\n // `.is()` gets the fast-check directly only when it is a total predicate;\n // partial/none falls back to safeParse().success inside __zcMkv. A rebuilding\n // schema has no by-reference `fc` but still names its predicate separately.\n const isArg = codegenResult.isFnName ?? (codegenResult.fastTotal ? fcArg : \"null\");\n\n return [\n options?.pure === false ? \"(() => {\" : \"/* @__PURE__ */ (() => {\",\n ...(bindsSchema ? [`var ${RETAINED_SCHEMA_VAR}=${schemaExpr};`] : []),\n // Only fallback refs need the array; a compact validator with none of its\n // own reads `__zs` directly rather than allocating `[__zs]` to index into.\n ...(refEntries.length > 0\n ? [`var __rf=[${refEntries.map((fb) => `${retainedSchema}${fb.accessPath}`).join(\",\")}];`]\n : []),\n ...codegenResult.code\n .split(\"\\n\")\n .filter((l) => l.trim() !== \"\" && l.trim() !== \"/* zod-compiler */\"),\n codegenResult.functionDef,\n `return __zcMkv(${fnName},${schemaArg},${fcArg},${isArg});`,\n \"})()\",\n ].join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;AAcA,MAAa,oBACX;;;;;;;;;;;;;;;;;;;;AAqBF,MAAa,sBACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CF,MAAa,kBACX;;;AASF,MAAa,WACX;;;;;;;;;;;;;;;;;;;;;;;AAwBF,MAAa,oBAAoB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AC,CAAC,KAAK,IAAI;AACb"}
1
+ {"version":3,"file":"iife.js","names":[],"sources":["../../src/core/iife.ts"],"sourcesContent":["/**\n * Shared CompiledSchema<T> IIFE generation.\n * Used by both CLI emitter and unplugin transform.\n */\n\nimport { FINALIZERS, RETAINED_SCHEMA_VAR } from \"./codegen/context.js\";\nimport type { CompiledSchemaInfo } from \"./pipeline.js\";\n\n/**\n * Import statements required by generateIIFE output (references\n * __zodCompilerConfig). `core` is bound for $ZodAsyncError: superRefine and\n * custom callbacks may only reveal that they are async through the promise\n * they return, at which point zod's own synchronous parse raises. It also\n * supplies `$ZodRealError`, the error class `zod/mini` schemas fail with (see\n * FAIL_CORE_CLASS_DECL); `ZodRealError` is classic's.\n *\n * `core` comes from `zod/v4/core` directly — the same module object classic\n * re-exports as `core`, but reached as a namespace IMPORT, whose member reads a\n * bundler can resolve one by one. Through classic's `export * as core`\n * re-export, esbuild instead materializes the whole namespace, every locale\n * included: a `zod/mini` bundle touching one `__zcCore` member measured 20 KB\n * before that read and 398 KB after.\n */\nexport const ZOD_CONFIG_IMPORT =\n 'import { config as __zodCompilerConfig, ZodRealError as __zcZodError } from \"zod\";\\n' +\n 'import * as __zcCore from \"zod/v4/core\";';\n\n/**\n * File-level `__zcMsg` declaration (must appear once after ZOD_CONFIG_IMPORT):\n * the message an issue gets when nothing was baked into it at build time.\n *\n * Resolves zod's tail of `finalizeIssue` — `config.customError` then\n * `config.localeError` then \"Invalid input\" — and does it PER CALL, because the\n * config is mutable: `z.config({ localeError })` in an entry point runs after\n * the schema modules it imports, so a value snapshotted at module init misses\n * it. Reading a captured `localeError` alone also dropped `customError`\n * outright, silently ignoring the global map most i18n setups install.\n *\n * The head of zod's chain — the schema's own `error` option — is baked into the\n * issue at build time and short-circuits this. The one link that cannot be\n * reproduced is a per-CALL `ctx.error`, which would have to travel through\n * `safeParse`; that entry point sits at V8's inlining budget, where even an\n * unused extra parameter measured ~12% on every parse.\n *\n * Only ever called while building an error, never on a successful parse.\n */\nexport const ZOD_MSG_DECLARATION =\n 'function __zcUw(m){return typeof m===\"string\"?m:(m===undefined||m===null?undefined:m.message);}' +\n \"var __zcMsg=function(iss){var c=__zodCompilerConfig(),m;\" +\n \"if(c.customError){m=__zcUw(c.customError(iss));if(m!==undefined&&m!==null)return m;}\" +\n \"if(c.localeError){m=__zcUw(c.localeError(iss));if(m!==undefined&&m!==null)return m;}\" +\n 'return \"Invalid input\";};';\n\n/**\n * Shared failure-result for __zcFin / __zcFinD. Inline mode (CLI emitter)\n * declares it once per compiled file; lean mode (all unplugin bundlers) declares\n * it once per bundle in the plugin-materialized runtime module (module-local —\n * generated code only ever references __zcFin/__zcFinD, never __ZcFail).\n *\n * Why a prototype getter and not `{success:false, get error(){...}}`: an object\n * literal with an inline accessor forces V8 down its slow accessor-defining\n * allocation path — ~110ns per failure, measured — which dominates the entire\n * invalid-input cost whenever callers never read `.error`. Hosting `error` on\n * the prototype turns each failure into a plain field-only instantiation (~2ns,\n * ~13x), with the lazy-cache semantics intact. (Trade-off: `error` is a\n * prototype accessor, so it no longer shows up in `Object.keys(result)` / spread\n * / JSON.stringify of the result wrapper — `.success`/`.error`/`.data` access,\n * destructuring, and `in` are unaffected.)\n *\n * One class serves both finalizers, so the instances share one hidden class:\n * __zcFin passes pre-collected issues in `_e` (with `_f===null`); __zcFinD\n * passes the hosted slow-walk in `_f` plus the input in `_i`, and the getter\n * runs the walk on first `.error` read. The whole finalization — locale fill\n * (__zcMsg applied ONLY when an issue carries no message, never overwriting a\n * baked-in custom/fallback message), input strip, and ZodError construction\n * (zod v4 JSON.stringifies every issue into `message` and captures a stack\n * trace) — stays deferred inside the cached accessor exactly as before, since\n * the issues array is observable solely through `.error`.\n *\n * `input` and `continue` are left OUT, not assigned `undefined`. Key PRESENCE is\n * observable — `\"input\" in issue`, `Object.keys(issue)`, object spread,\n * `toStrictEqual` against a zod issue — and zod's `util.finalizeIssue` deletes\n * `continue`, and `input` whenever `reportInput` is off, so assignment left every\n * compiled issue one enumerable key wider than zod's. Each issue is COPIED\n * without them rather than `delete`d from: removing a key that is not the last\n * one added drops the object into V8's dictionary mode, ~70 ns an issue. `.error`\n * over six issues went 1.49 -> 1.06 us, over one 653 -> 608 ns. The copy keeps\n * key order and takes own keys only, so an enumerable key added to\n * `Object.prototype` stays out, as it does from zod's spread. All of it runs only\n * after a caller asks for `.error` on a failed parse, and is memoised in `_c`.\n */\nexport const FAIL_CLASS_DECL = failClassDecl(\"__ZcFail\", \"__zcZodError\");\n\n/**\n * {@link FAIL_CLASS_DECL} for a schema that fails with zod/v4/core's\n * `$ZodError` instead of classic's `ZodError`: `zod/mini`, whose methods call\n * core's parse functions, and raw core (see zodErrorClassOf). The finalization\n * is identical; only the class constructed at the end differs, and with it\n * everything the class carries (`name`, the trait `instanceof` tests,\n * classic's `.format()`/`.flatten()`).\n *\n * A class of its own, with its own finalizers, rather than a constructor\n * picked per failure: generated code names the pair its schema needs, so a\n * bundle keeps only the class its validators construct (see failClassDecl).\n */\nexport const FAIL_CORE_CLASS_DECL = failClassDecl(\"__ZcFailC\", \"__zcCore.$ZodRealError\");\n\n/**\n * The failure class, for either error flavor; `errorClass` is the constructor\n * expression.\n *\n * Wrapped in a `@__PURE__` IIFE so a bundle drops whichever class its\n * validators never construct. A bare declaration is kept by every bundler\n * for the `Object.defineProperty` that installs the getter (rolldown and\n * esbuild both measured): the core class would cost every classic bundle\n * ~500 B, and the classic class cost every `zod/mini` bundle 2.3-3.1 KB, since\n * it carries classic zod's error class in with it. The wrapper itself costs a\n * classic bundle 26-64 B.\n *\n * The binding is a `var`, not a hoisted function, so it must be initialized\n * before a validator fails. Every emitter declares it at the head of the module\n * (or of the evaluated body, under `jit()`), ahead of the finalizers and of\n * every statement that could run a validator.\n */\nfunction failClassDecl(name: string, errorClass: string): string {\n return (\n `var ${name}=/* @__PURE__ */(function(){` +\n `function ${name}(e,f,i){this.success=false;this._e=e;this._f=f;this._i=i;this._c=undefined;}` +\n `Object.defineProperty(${name}.prototype,\"error\",{configurable:true,get:function(){` +\n \"if(this._c)return this._c;\" +\n \"var e=this._f!==null?this._f(this._i):this._e;\" +\n 'for(var i=0;i<e.length;i++){var s=e[i],o={},k;if(s.message===undefined&&typeof __zcMsg===\"function\")s.message=__zcMsg(s);' +\n 'for(k in s){if(k!==\"input\"&&k!==\"continue\"&&Object.prototype.hasOwnProperty.call(s,k))o[k]=s[k];}e[i]=o;}' +\n `return this._c=new ${errorClass}(e);}});` +\n `return ${name};})();`\n );\n}\n\n/** Eager finalizer (mutation / partial-fast-path schemas): issues already\n * collected in `e`; success short-circuits to a plain result literal. */\nexport const FIN_DECL = finDecl(FINALIZERS.ZodError.eager, \"__ZcFail\");\n\n/** {@link FIN_DECL} for schemas failing with core's `$ZodError` (see {@link FAIL_CORE_CLASS_DECL}). */\nexport const FIN_CORE_DECL = finDecl(FINALIZERS.$ZodError.eager, \"__ZcFailC\");\n\nfunction finDecl(name: string, failClass: string): string {\n return `function ${name}(e,d){if(!e.length)return{success:true,data:d};return new ${failClass}(e,null,null);}`;\n}\n\n/**\n * Deferred-collection finalizer for Fast-Path-eligible schemas. When the\n * fast check fails, the ENTIRE slow path (the issue-collecting re-walk) is\n * pushed into the cached `.error` accessor instead of running eagerly:\n * fast-eligible schemas never mutate, so the walk's only output is the\n * issues array, which is observable solely through `.error` — one step\n * further along the same lazy boundary `__zcFin` already established (locale\n * fill, input strip, ZodError construction). A failed safeParse whose\n * `.error` is never read costs the fast check alone.\n *\n * Takes the schema's HOSTED slow-walk function plus the input — NOT a\n * per-call closure: `__zcFinD(__sw_N, input)` allocates only the result\n * object, where `__zcFinD(function(){...})` paid a closure environment and\n * function object per failure. Hosting the walk also shrinks safeParse to\n * two statements, within V8's inlining budget (the success-path result\n * literal becomes escape-analyzable at monomorphic call sites).\n *\n * The walk re-reads `input` at `.error`-read time; a caller that mutates\n * the input between safeParse and reading `.error` sees issues for the\n * mutated value (zod materializes at parse time). Same caveat class as the\n * documented __zcFin deferral.\n */\nexport const FIN_DEFERRED_DECL = finDeferredDecl(FINALIZERS.ZodError.deferred, \"__ZcFail\");\n\n/** {@link FIN_DEFERRED_DECL} for schemas failing with core's `$ZodError` (see {@link FAIL_CORE_CLASS_DECL}). */\nexport const FIN_DEFERRED_CORE_DECL = finDeferredDecl(FINALIZERS.$ZodError.deferred, \"__ZcFailC\");\n\nfunction finDeferredDecl(name: string, failClass: string): string {\n return `function ${name}(f,inp){return new ${failClass}(null,f,inp);}`;\n}\n\n/**\n * Whether generated code that uses `helpers` builds core `$ZodError`s.\n *\n * Every emitter has always supplied the classic `__zcFin` whether or not any\n * validator calls it. A file whose validators fail with core errors skips that\n * default (a validator that does call it names it anyway): there it would be\n * dead code that reaches for classic zod's error class.\n */\nexport function usesCoreErrors(helpers: ReadonlySet<string>): boolean {\n return helpers.has(FINALIZERS.$ZodError.eager) || helpers.has(FINALIZERS.$ZodError.deferred);\n}\n\n/**\n * Compact-mode failure class — a lazy failure that delegates error reporting to\n * the ORIGINAL Zod schema's `safeParse`. Used by `output: \"compact\"`, where the\n * compiled slow walk is dropped entirely: a mutation-free schema's fast check\n * is the only generated validation, and on a fast-check failure the cold error\n * path is produced by the retained Zod schema itself (`zod` is the source of\n * truth, so the issues are byte-identical — no second validation engine).\n *\n * `_z` is the schema's PRISTINE safeParse method, captured by\n * emitRetainedMethod (see context.ts), and `_r` is its receiver — the `__zs`\n * binding generateIIFE places above that capture. Both are read before the\n * trailing `__zcMkv` call installs anything, so the method is zod's own\n * implementation, never the compiled delegate, avoiding infinite recursion\n * without allocating a bound function. The zod parse is deferred until `.error`\n * is read and cached, so\n * the common `safeParse(x).success`/`.is(x)` checks on invalid input cost only\n * the fast check (zod never runs) — the same deferral boundary `__zcFinD`\n * establishes for the compiled slow walk. Sound because compact mode is gated\n * on a TOTAL fast path: `fc(input) === false` ⟹ zod rejects, so `success:false`\n * holds without consulting zod.\n *\n * The getter returns zod's OWN ZodError verbatim (no locale fill / input strip /\n * re-wrap — zod already finalized it), so a delegated failure is exactly what\n * the unaltered schema would have produced.\n */\nexport const FAILZ_CLASS_DECL =\n \"function __ZcFailZ(z,r,i){this.success=false;this._z=z;this._r=r;this._i=i;this._c=undefined;}\" +\n 'Object.defineProperty(__ZcFailZ.prototype,\"error\",{configurable:true,get:function(){' +\n \"return this._c||(this._c=this._z.call(this._r,this._i).error);}});\";\n\n/** Compact-mode finalizer: retain a pristine safeParse, its receiver, and input lazily. */\nexport const FINZ_DECL = \"function __zcFinZ(z,r,i){return new __ZcFailZ(z,r,i);}\";\n\n/**\n * Validator factory. Inline mode (CLI emitter) declares it once per compiled\n * file; lean mode (all unplugin bundlers) exports it once per bundle from the\n * plugin-materialized runtime module — generated code never imports it from\n * the zod-compiler package itself, so zod-compiler stays a devDependency and\n * the helper set is always version-locked to the codegen that calls it.\n * Wraps a safeParse function into the CompiledSchema interface.\n *\n * IDENTITY-PRESERVING: with zodCompat (schema != null) the compiled\n * parse/safeParse/parseAsync/safeParseAsync are installed as OWN properties\n * on the original schema object, which is returned as-is. zod v4 keys\n * several APIs on object identity — toJSONSchema's ctx.seen registers the\n * object it is handed while each processor closure captures the original\n * inst (a wrapper crashes `optionalProcessor` with \"Cannot set properties\n * of undefined (setting 'ref')\" the moment a compiled schema is composed\n * into another schema), and globalRegistry/.meta() is a WeakMap keyed by\n * the schema instance (a wrapper silently loses OpenAPI titles/ids). An\n * Object.create wrapper breaks both; mutating the original breaks neither\n * (zod's internal parsing flows through _zod.run, never the public\n * methods, and derived schemas — .optional(), .extend() — are fresh\n * instances that fall back to plain zod). schema=null (zodCompat: false)\n * still produces a plain method-bag object.\n *\n * fc is the schema's hosted fast-check boolean function (null when no Fast\n * Path exists). parse()/parseAsync() try it first and return the input\n * directly on success: fc is small enough for V8 to inline, so the hot parse\n * path runs with zero allocations — calling fn would allocate an intermediate\n * SafeParseResult that escape analysis cannot remove (fn never inlines).\n * Fast-path-eligible schemas never mutate, so fc(input) ⟹ data === input.\n *\n * is is the TOTAL fast-check predicate (fc when the fast path is total, else\n * null). Installed as `.is()` — a zero-allocation boolean type guard. When\n * null (partial fast path or none) `.is()` derives from fn(input).success: a\n * partial fc can pass-through valid input but its `false` does not imply\n * rejection (a default/catch may still succeed), so it would be unsound as a\n * standalone guard.\n *\n * parseAsync/safeParseAsync wrap the SYNC validator, which is right for every\n * schema the compiler can reproduce — none of them are async. It is wrong for\n * the ones it cannot: an `async` refinement or a `z.promise()` extracts to a\n * Zod delegate, and delegating means calling Zod's SYNCHRONOUS safeParse, which\n * raises `$ZodAsyncError` by design. Wrapping that gave the compiled schema an\n * async pair that rejected with `$ZodAsyncError` for EVERY input — including\n * valid ones — where Zod resolves normally, so `await UserSchema.parseAsync(x)`\n * stopped working the moment any part of the schema went async.\n *\n * So both are guarded: a synchronous throw hands off to the schema's ORIGINAL\n * async method, captured before these are installed — the same escape hatch\n * `~standard` already uses for its throw path, and for the same reason (the\n * compiled validator has no async mode to offer, and Zod's is exact). It also\n * fixes the smaller wart that a throwing `fn` made `parseAsync` throw\n * SYNCHRONOUSLY rather than return a rejected promise. With `zodCompat: false`\n * there is no schema to delegate to and the throw propagates as before.\n *\n * `~standard` is REPLACED, not merely preserved. Zod builds it lazily as\n * `validate: (v) => safeParse(inst, v)` — the core FUNCTION, which goes straight\n * to `inst._zod.run`. It never reads the schema's own `safeParse` property, so\n * installing the compiled one leaves this route entirely uncompiled: measured\n * 271.7 ns against the compiled 26.6 ns on the same schema, i.e. Standard Schema\n * consumers (tRPC, Hono, TanStack) were getting plain Zod.\n *\n * Zod's own `~standard` is never READ, only overwritten. Zod installs the slot\n * with `util.defineLazy` — commented there as \"avoid creating objects for every\n * schema\" — so it is an accessor that builds `{version, vendor, validate}` plus\n * its closure on first touch. Reading it to capture a fallback fired that getter\n * for every compiled schema while the module was still initializing.\n *\n * How much that costs depends on the entry point, and only one of them is free:\n * classic `zod` forces the slot itself during `ZodType.init` (it does\n * `Object.assign(inst[\"~standard\"], { jsonSchema })`), so there the read hit an\n * already-built object and cost only an accessor call. `zod/mini` and raw\n * `zod/v4/core` never touch it, so for those the read built — and retained — an\n * object and a closure per schema, purely to capture a fallback the schema will\n * most likely never expose to a Standard Schema consumer.\n *\n * The throw path is rebuilt instead of captured. Zod's validate catches a\n * synchronous throw and retries through `safeParseAsync` — that is how an async\n * refinement resolves and how a throwing check surfaces as a rejected promise\n * rather than a synchronous throw — so calling the already-captured `zspa` and\n * mapping its result is the same route to the same result. `vendor` is likewise\n * a constant: schema discovery only ever admits zod schemas, and classic, mini\n * and core all hardcode `vendor: \"zod\"` themselves.\n *\n * Not carried over (unchanged by this, and pre-dating it): classic's\n * `~standard.jsonSchema` extension, which the replacement object has never\n * reproduced.\n *\n * Installed with defineProperty rather than assignment: Zod's lazy setter\n * redefines the slot as non-writable, so a second `__zcMkv` on the same schema\n * object — two exports aliasing one schema — would throw under ESM strict mode.\n *\n * A rebuilding schema (no `fc`) reaches `parse()` through `fn`, i.e. through a\n * SafeParseResult unwrapped a line later. Handing the build function over so\n * `parse()` could call it directly was measured and declined: the wrapper is a\n * young-generation bump allocation that V8 elides outright where `fn` inlines,\n * and even across eight schemas sharing this closure — where it cannot — the\n * direct call came out level (41.5 vs 41.8 ns), for a wider signature on every\n * bundle.\n */\nexport const MK_VALIDATOR_DECL =\n \"function __zcMkv(fn,schema,fc,is){var w=schema||{};var zpa=w.parseAsync,zspa=w.safeParseAsync;w.parse=fc?function(input){if(fc(input))return input;var r=fn(input);if(r.success)return r.data;throw r.error;}:function(input){var r=fn(input);if(r.success)return r.data;throw r.error;};w.safeParse=fn;w.safeParseAsync=function(input){try{return Promise.resolve(fn(input));}catch(e){if(zspa)return zspa(input);throw e;}};w.parseAsync=fc?function(input){try{if(fc(input))return Promise.resolve(input);var r=fn(input);if(r.success)return Promise.resolve(r.data);return Promise.reject(r.error);}catch(e){if(zpa)return zpa(input);throw e;}}:function(input){try{var r=fn(input);if(r.success)return Promise.resolve(r.data);return Promise.reject(r.error);}catch(e){if(zpa)return zpa(input);throw e;}};w.is=is||function(input){return fn(input).success;};\" +\n 'Object.defineProperty(w,\"~standard\",{configurable:true,value:{version:1,vendor:\"zod\",validate:function(input){var r;try{if(fc&&fc(input))return{value:input};r=fn(input);}catch(e){if(zspa)return zspa(input).then(function(q){return q.success?{value:q.data}:{issues:q.error.issues};});throw e;}return r.success?{value:r.data}:{issues:r.error.issues};}}});' +\n \"return w;}\";\n\nfunction extractFunctionName(functionDef: string): string {\n const match = /^function\\s+(\\w+)\\s*\\(/.exec(functionDef);\n if (!match?.[1]) {\n throw new Error(\"Cannot extract function name from generated code\");\n }\n return match[1];\n}\n\n/**\n * Does the IIFE's preamble DEREFERENCE the retained schema at evaluation time?\n *\n * Only `__rf` does: every entry is `__zs<accessPath>`, and an access path walks\n * the schema's structure — `._zod.innerType` fires a `z.lazy()` getter,\n * `.shape` materializes a `z.object()` shape (zod v4 reads every property\n * descriptor, so ONE `.shape` read fires ALL of an object's recursion getters).\n * Binding `__zs` itself does not: constructing the schema leaves deferred\n * callbacks unforced, and `usesRetainedSchema`'s only read is `__zs.safeParse`,\n * a prototype getter that binds the method and installs the bound copy on the\n * instance without touching the schema's structure.\n *\n * The distinction decides whether the IIFE may be evaluated inside the\n * INITIALIZER of the binding the schema's own deferred callbacks close over —\n * see the self-referential path in the unplugin's autoDiscover rewrite.\n */\nexport function iifeDerefsSchema(schema: CompiledSchemaInfo): boolean {\n return schema.refEntries.length > 0;\n}\n\n/**\n * Generate a `/* @__PURE__ * /` IIFE wrapping a compiled validator.\n *\n * @param schemaExpr - Expression resolving to the original Zod schema\n * (e.g. `\"UserSchema\"` in unplugin, `\"(__src_X as any).schema\"` in CLI)\n * @param schema\n * @param options - `pure: false` drops the `/* @__PURE__ * /` annotation, for\n * the one caller that emits the IIFE as a STATEMENT following the\n * declaration rather than as its initializer: there the call's whole point is\n * its side effect (`__zcMkv` installing the compiled methods on the schema),\n * and a bundler that believed it pure would drop the compilation outright.\n */\nexport function generateIIFE(\n schemaExpr: string,\n schema: CompiledSchemaInfo,\n options?: { zodCompat?: boolean | undefined; pure?: boolean | undefined },\n): string {\n const { codegenResult, refEntries } = schema;\n const fnName = extractFunctionName(codegenResult.functionDef);\n const zodCompat = options?.zodCompat !== false;\n // Every fallback access starts from the same source schema, and compact\n // delegation names it outright. Capture it once whenever either needs it, so\n // an inline initializer is not reconstructed for each path and again for the\n // identity-preserving __zcMkv target.\n const bindsSchema = refEntries.length > 0 || codegenResult.usesRetainedSchema === true;\n const retainedSchema = bindsSchema ? RETAINED_SCHEMA_VAR : schemaExpr;\n const schemaArg = zodCompat ? retainedSchema : \"null\";\n const fcArg = codegenResult.fastFnName ?? \"null\";\n // `.is()` gets the fast-check directly only when it is a total predicate;\n // partial/none falls back to safeParse().success inside __zcMkv. A rebuilding\n // schema has no by-reference `fc` but still names its predicate separately.\n const isArg = codegenResult.isFnName ?? (codegenResult.fastTotal ? fcArg : \"null\");\n\n return [\n options?.pure === false ? \"(() => {\" : \"/* @__PURE__ */ (() => {\",\n ...(bindsSchema ? [`var ${RETAINED_SCHEMA_VAR}=${schemaExpr};`] : []),\n // Only fallback refs need the array; a compact validator with none of its\n // own reads `__zs` directly rather than allocating `[__zs]` to index into.\n ...(refEntries.length > 0\n ? [`var __rf=[${refEntries.map((fb) => `${retainedSchema}${fb.accessPath}`).join(\",\")}];`]\n : []),\n ...codegenResult.code\n .split(\"\\n\")\n .filter((l) => l.trim() !== \"\" && l.trim() !== \"/* zod-compiler */\"),\n codegenResult.functionDef,\n `return __zcMkv(${fnName},${schemaArg},${fcArg},${isArg});`,\n \"})()\",\n ].join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuBA,MAAa,oBACX;;;;;;;;;;;;;;;;;;;;AAsBF,MAAa,sBACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CF,MAAa,kBAAkB,cAAc,YAAY,cAAc;;;;;;;;;;;;;AAcvE,MAAa,uBAAuB,cAAc,aAAa,wBAAwB;;;;;;;;;;;;;;;;;;AAmB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MAAM,cAAc,WAAW,SAAS,KAAK,cAAc,uBAAuB;CAClF,MAAM,iBAAiB,cAAc,sBAAsB;CAC3D,MAAM,YAAY,YAAY,iBAAiB;CAC/C,MAAM,QAAQ,cAAc,cAAc;CAI1C,MAAM,QAAQ,cAAc,aAAa,cAAc,YAAY,QAAQ;CAE3E,OAAO;EACL,SAAS,SAAS,QAAQ,aAAa;EACvC,GAAI,cAAc,CAAC,OAAO,oBAAoB,GAAG,WAAW,EAAE,IAAI,CAAC;EAGnE,GAAI,WAAW,SAAS,IACpB,CAAC,aAAa,WAAW,KAAK,OAAO,GAAG,iBAAiB,GAAG,YAAY,CAAC,CAAC,KAAK,GAAG,EAAE,GAAG,IACvF,CAAC;EACL,GAAG,cAAc,KACd,MAAM,IAAI,CAAC,CACX,QAAQ,MAAM,EAAE,KAAK,MAAM,MAAM,EAAE,KAAK,MAAM,oBAAoB;EACrE,cAAc;EACd,kBAAkB,OAAO,GAAG,UAAU,GAAG,MAAM,GAAG,MAAM;EACxD;CACF,CAAC,CAAC,KAAK,IAAI;AACb"}
@@ -1,6 +1,7 @@
1
1
  import { DiscoveredSchema } from "./types.js";
2
2
  import { CodeGenResult, CodegenMode } from "./codegen/context.js";
3
3
  import { RefEntry } from "./extract/types.js";
4
+ import "./extract/index.js";
4
5
  //#region src/core/pipeline.d.ts
5
6
  /** Result of compiling a single discovered schema through extract → generate pipeline. */
6
7
  interface CompiledSchemaInfo {
@@ -1 +1 @@
1
- {"version":3,"file":"pipeline.d.ts","names":[],"sources":["../../src/core/pipeline.ts"],"mappings":";;;;;UAaiB;EACf;EACA,eAAe;EACf,YAAY;;;UAIG;;EAEf;;EAEA,aAAa;;;UAIE;EACf,SAAS;EACT,QAAQ;;UAGO;;EAEf,MAAM;;;;;;;;EAQN;;EAEA,WAAW,oBAAoB,OAAO;;;;;;;;;;;;iBA4FxB,eACd,SAAS,oBACT,SAAS,wBACR;;;;;iBAwHa,qBAAqB,SAAS,uBAAuB"}
1
+ {"version":3,"file":"pipeline.d.ts","names":[],"sources":["../../src/core/pipeline.ts"],"mappings":";;;;;;UAciB;EACf;EACA,eAAe;EACf,YAAY;;;UAIG;;EAEf;;EAEA,aAAa;;;UAIE;EACf,SAAS;EACT,QAAQ;;UAGO;;EAEf,MAAM;;;;;;;;EAQN;;EAEA,WAAW,oBAAoB,OAAO;;;;;;;;;;;;iBA4FxB,eACd,SAAS,oBACT,SAAS,wBACR;;;;;iBAqIa,qBAAqB,SAAS,uBAAuB"}
@@ -1,5 +1,6 @@
1
1
  import { SHARED_BLOCK_MARKER, createSharedSchemaPlan } from "./codegen/dedupe.js";
2
2
  import { generateValidator } from "./codegen/index.js";
3
+ import { zodErrorClassOf } from "./extract/error-class.js";
3
4
  import { extractSchema } from "./extract/index.js";
4
5
  //#region src/core/pipeline.ts
5
6
  /**
@@ -73,7 +74,8 @@ function compileSchemas(schemas, options) {
73
74
  exportName: s.exportName,
74
75
  schema: s.schema,
75
76
  ir,
76
- refEntries
77
+ refEntries,
78
+ errorClass: zodErrorClassOf(s.schema)
77
79
  });
78
80
  } catch (err) {
79
81
  handle(s.exportName, err);
@@ -88,6 +90,7 @@ function compileSchemas(schemas, options) {
88
90
  mode: options.mode,
89
91
  sharedSchemas: plan,
90
92
  compact: options.compact,
93
+ errorClass: e.errorClass,
91
94
  onConstant(constant) {
92
95
  constants.set(constant.name, constant);
93
96
  }
@@ -98,6 +101,7 @@ function compileSchemas(schemas, options) {
98
101
  schema: e.schema,
99
102
  ir: e.ir,
100
103
  refEntries: e.refEntries,
104
+ errorClass: e.errorClass,
101
105
  codegenResult
102
106
  });
103
107
  } catch (err) {
@@ -113,6 +117,7 @@ function compileSchemas(schemas, options) {
113
117
  mode: options.mode,
114
118
  sharedSchemas: plan,
115
119
  compact: options.compact,
120
+ errorClass: entry.errorClass,
116
121
  sharedConstantNames
117
122
  });
118
123
  const results = generated.map((entry) => ({
@@ -1 +1 @@
1
- {"version":3,"file":"pipeline.js","names":[],"sources":["../../src/core/pipeline.ts"],"sourcesContent":["import type {\n CodeGenResult,\n CodegenMode,\n ConstantKind,\n GeneratedConstant,\n} from \"./codegen/context.js\";\nimport { createSharedSchemaPlan, SHARED_BLOCK_MARKER } from \"./codegen/dedupe.js\";\nimport { generateValidator } from \"./codegen/index.js\";\nimport type { RefEntry } from \"./extract/index.js\";\nimport { extractSchema } from \"./extract/index.js\";\nimport type { DiscoveredSchema, SchemaIR } from \"./types.js\";\n\n/** Result of compiling a single discovered schema through extract → generate pipeline. */\nexport interface CompiledSchemaInfo {\n exportName: string;\n codegenResult: CodeGenResult;\n refEntries: RefEntry[];\n}\n\n/** Module-scope declarations produced by file-level schema and constant dedup. */\nexport interface SharedSchemaBlock {\n /** Shared constants and `__zcSw_N` functions. Empty string when nothing repeats. */\n code: string;\n /** Runtime helper names referenced by the shared block (lean mode imports). */\n usedHelpers: Set<string>;\n}\n\n/** Output of {@link compileSchemas}: per-schema validators plus the file's shared block. */\nexport interface CompileSchemasResult {\n schemas: CompiledSchemaInfo[];\n shared: SharedSchemaBlock;\n}\n\nexport interface CompileSchemasOptions {\n /** \"inline\" for CLI .compiled.ts; \"lean\" for unplugin (imports from virtual:zod-compiler/runtime). */\n mode: CodegenMode;\n /**\n * Compact output (`output: \"compact\"`). Drop the compiled slow walk for\n * mutation-free, total-fast-path schemas and delegate their cold error path\n * to the retained Zod schema. Disables slow-walk sharing (delegated schemas\n * never emit a walk to share); delegated validators read the retained schema\n * through the `__zs` binding rather than through `__rf[]`.\n */\n compact?: boolean | undefined;\n /** When provided, per-schema failures call this and continue. Otherwise the first error throws. */\n onError?: (exportName: string, error: Error) => void;\n}\n\n/**\n * Occurrences of a generated identifier in `source`, ignoring the longer names\n * it is a prefix of — every generated name ends in `_<digits>`, so `__set_ks_1`\n * would otherwise count itself inside `__set_ks_10`.\n */\nfunction referenceCount(source: string, name: string): number {\n let count = 0;\n for (let at = source.indexOf(name); at !== -1; at = source.indexOf(name, at + name.length)) {\n const next = source.charCodeAt(at + name.length);\n if (!(next >= 48 && next <= 57)) count += 1;\n }\n return count;\n}\n\n/**\n * Plan exact constant initializers used by at least two validators in this file.\n *\n * Names are assigned per kind (`__zcSet_0`, …) and ordered by initializer text,\n * so a given file always produces the same names for the same content.\n */\nfunction planSharedConstants(\n results: readonly CompiledSchemaInfo[],\n constantsByResult: ReadonlyMap<CodeGenResult, readonly GeneratedConstant[]>,\n): ReadonlyMap<string, string> {\n const byInitializer = new Map<string, { kind: ConstantKind; users: Set<CodeGenResult> }>();\n for (const { codegenResult } of results) {\n const source = `${codegenResult.code}\\n${codegenResult.functionDef}`;\n for (const constant of constantsByResult.get(codegenResult) ?? []) {\n const declaration = `var ${constant.name}=${constant.initializer};`;\n // Fast-path generation can emit a constant before a later node aborts.\n // Its preamble is rolled back, so only collect declarations that survived.\n if (!source.includes(declaration)) continue;\n // A surviving declaration is not the same as a use. Two generators emit a\n // constant before they can decline — the build path names its FAIL\n // sentinel up front, and an abandoned fast-path walk leaves whatever it\n // declared behind — so a validator can hold a declaration it never reads.\n // Counting those as pool users hoisted constants nothing referenced, and\n // (worse) tripped the regeneration pass for a file that gained nothing by\n // it. Require the name to appear at least once beyond its own declaration.\n if (referenceCount(source, constant.name) < 2) continue;\n const entry = byInitializer.get(constant.initializer);\n if (entry === undefined) {\n byInitializer.set(constant.initializer, {\n kind: constant.kind,\n users: new Set([codegenResult]),\n });\n } else {\n entry.users.add(codegenResult);\n }\n }\n }\n\n const repeated = [...byInitializer.entries()]\n .filter(([, entry]) => entry.users.size >= 2)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n\n const nextIndex = new Map<ConstantKind, number>();\n return new Map(\n repeated.map(([initializer, entry]) => {\n const index = nextIndex.get(entry.kind) ?? 0;\n nextIndex.set(entry.kind, index + 1);\n return [initializer, `__zc${entry.kind}_${index}`];\n }),\n );\n}\n\nfunction emitSharedConstants(sharedConstantNames: ReadonlyMap<string, string>): string {\n return [...sharedConstantNames]\n .map(([initializer, name]) => {\n // `/* @__PURE__ */` earns its bytes only on a constructor call, where it\n // tells a bundler the declaration is droppable when nothing reads it. On a\n // plain object literal it is inert, and the annotation is longer than the\n // initializer it annotates.\n const pure = initializer.startsWith(\"new \") ? \"/* @__PURE__ */\" : \"\";\n return `var ${name}=${pure}${initializer};`;\n })\n .join(\"\\n\");\n}\n\n/**\n * Run the extract → generate pipeline for each discovered schema.\n * Shared by CLI generate and unplugin transform.\n *\n * Pass 1 extracts every schema's IR and plans repeated slow walks. Pass 2\n * generates each validator, calling shared `__zcSw_N` functions instead of\n * re-inlining them. Exact constant initializers reported during generation are\n * then pooled when at least two validators use them. Files with no repetition\n * keep their original local declarations.\n */\nexport function compileSchemas(\n schemas: DiscoveredSchema[],\n options: CompileSchemasOptions,\n): CompileSchemasResult {\n const handle = (exportName: string, err: unknown): void => {\n if (options.onError) {\n options.onError(exportName, err instanceof Error ? err : new Error(String(err)));\n } else {\n throw err;\n }\n };\n\n // Pass 1: extract IR (and fallback refs) for every schema.\n const extracted: Array<{\n exportName: string;\n schema: unknown;\n ir: SchemaIR;\n refEntries: RefEntry[];\n }> = [];\n for (const s of schemas) {\n try {\n const refEntries: RefEntry[] = [];\n const ir = extractSchema(s.schema, refEntries);\n extracted.push({ exportName: s.exportName, schema: s.schema, ir, refEntries });\n } catch (err) {\n handle(s.exportName, err);\n }\n }\n\n // Compact mode delegates the cold error path of total-fast-path schemas to\n // zod, so they emit no slow walk to share — skip the plan (and the dead\n // shared functions it would generate for shapes that now only delegate).\n const plan = options.compact\n ? undefined\n : createSharedSchemaPlan(\n extracted.map((e) => e.ir),\n options.mode,\n );\n\n // Pass 2: generate each validator, sharing repeated slow walks via the plan\n // and observing which constant declarations survive codegen rollback.\n const generated: Array<{\n exportName: string;\n schema: unknown;\n ir: SchemaIR;\n refEntries: RefEntry[];\n codegenResult: CodeGenResult;\n }> = [];\n const constantsByResult = new Map<CodeGenResult, GeneratedConstant[]>();\n for (const e of extracted) {\n try {\n const constants = new Map<string, GeneratedConstant>();\n const codegenResult = generateValidator(e.ir, e.exportName, {\n refCount: e.refEntries.length,\n mode: options.mode,\n sharedSchemas: plan,\n compact: options.compact,\n onConstant(constant) {\n constants.set(constant.name, constant);\n },\n });\n constantsByResult.set(codegenResult, [...constants.values()]);\n generated.push({\n exportName: e.exportName,\n schema: e.schema,\n ir: e.ir,\n refEntries: e.refEntries,\n codegenResult,\n });\n } catch (err) {\n handle(e.exportName, err);\n }\n }\n\n const initialResults = generated.map(\n ({ exportName, codegenResult, refEntries }): CompiledSchemaInfo => ({\n exportName,\n codegenResult,\n refEntries,\n }),\n );\n const sharedConstantNames = planSharedConstants(initialResults, constantsByResult);\n\n // Regenerate only when sharing is profitable. Selecting shared names before\n // emission avoids textual rewriting of generated JavaScript, where a user\n // enum string can legally contain text resembling a generated identifier.\n if (sharedConstantNames.size > 0) {\n for (const entry of generated) {\n entry.codegenResult = generateValidator(entry.ir, entry.exportName, {\n refCount: entry.refEntries.length,\n mode: options.mode,\n sharedSchemas: plan,\n compact: options.compact,\n sharedConstantNames,\n });\n }\n }\n\n const results: CompiledSchemaInfo[] = generated.map((entry) => ({\n exportName: entry.exportName,\n codegenResult: entry.codegenResult,\n refEntries: entry.refEntries,\n }));\n\n const sharedConstantCode = emitSharedConstants(sharedConstantNames);\n const slowWalkCode = plan?.code ?? \"\";\n const sharedCode =\n sharedConstantCode === \"\"\n ? slowWalkCode\n : slowWalkCode === \"\"\n ? `${SHARED_BLOCK_MARKER}\\n${sharedConstantCode}`\n : `${slowWalkCode}\\n${sharedConstantCode}`;\n\n return {\n schemas: results,\n shared: { code: sharedCode, usedHelpers: plan?.usedHelpers ?? new Set() },\n };\n}\n\n/**\n * Aggregate `usedHelpers` across multiple compiled schemas (typically all schemas in one file).\n * Used by the unplugin transform to construct a single import statement per file.\n */\nexport function aggregateUsedHelpers(schemas: CompiledSchemaInfo[]): Set<string> {\n const all = new Set<string>();\n for (const s of schemas) {\n for (const h of s.codegenResult.usedHelpers) all.add(h);\n }\n return all;\n}\n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,UAAU,OAAO,CAAC,CAAC;EAC5D,UAAU,KAAK;GACb,YAAY,EAAE;GACd,QAAQ,EAAE;GACV,IAAI,EAAE;GACN,YAAY,EAAE;GACd;EACF,CAAC;CACH,SAAS,KAAK;EACZ,OAAO,EAAE,YAAY,GAAG;CAC1B;CAUF,MAAM,sBAAsB,oBAPL,UAAU,KAC9B,EAAE,YAAY,eAAe,kBAAsC;EAClE;EACA;EACA;CACF,EAE2D,GAAG,iBAAiB;CAKjF,IAAI,oBAAoB,OAAO,GAC7B,KAAK,MAAM,SAAS,WAClB,MAAM,gBAAgB,kBAAkB,MAAM,IAAI,MAAM,YAAY;EAClE,UAAU,MAAM,WAAW;EAC3B,MAAM,QAAQ;EACd,eAAe;EACf,SAAS,QAAQ;EACjB;CACF,CAAC;CAIL,MAAM,UAAgC,UAAU,KAAK,WAAW;EAC9D,YAAY,MAAM;EAClB,eAAe,MAAM;EACrB,YAAY,MAAM;CACpB,EAAE;CAEF,MAAM,qBAAqB,oBAAoB,mBAAmB;CAClE,MAAM,eAAe,MAAM,QAAQ;CAQnC,OAAO;EACL,SAAS;EACT,QAAQ;GAAE,MARV,uBAAuB,KACnB,eACA,iBAAiB,KACf,GAAG,oBAAoB,IAAI,uBAC3B,GAAG,aAAa,IAAI;GAIE,aAAa,MAAM,+BAAe,IAAI,IAAI;EAAE;CAC1E;AACF;;;;;AAMA,SAAgB,qBAAqB,SAA4C;CAC/E,MAAM,sBAAM,IAAI,IAAY;CAC5B,KAAK,MAAM,KAAK,SACd,KAAK,MAAM,KAAK,EAAE,cAAc,aAAa,IAAI,IAAI,CAAC;CAExD,OAAO;AACT"}
1
+ {"version":3,"file":"pipeline.js","names":[],"sources":["../../src/core/pipeline.ts"],"sourcesContent":["import type {\n CodeGenResult,\n CodegenMode,\n ConstantKind,\n GeneratedConstant,\n} from \"./codegen/context.js\";\nimport { createSharedSchemaPlan, SHARED_BLOCK_MARKER } from \"./codegen/dedupe.js\";\nimport { generateValidator } from \"./codegen/index.js\";\nimport { zodErrorClassOf, type ZodErrorClass } from \"./extract/error-class.js\";\nimport type { RefEntry } from \"./extract/index.js\";\nimport { extractSchema } from \"./extract/index.js\";\nimport type { DiscoveredSchema, SchemaIR } from \"./types.js\";\n\n/** Result of compiling a single discovered schema through extract → generate pipeline. */\nexport interface CompiledSchemaInfo {\n exportName: string;\n codegenResult: CodeGenResult;\n refEntries: RefEntry[];\n}\n\n/** Module-scope declarations produced by file-level schema and constant dedup. */\nexport interface SharedSchemaBlock {\n /** Shared constants and `__zcSw_N` functions. Empty string when nothing repeats. */\n code: string;\n /** Runtime helper names referenced by the shared block (lean mode imports). */\n usedHelpers: Set<string>;\n}\n\n/** Output of {@link compileSchemas}: per-schema validators plus the file's shared block. */\nexport interface CompileSchemasResult {\n schemas: CompiledSchemaInfo[];\n shared: SharedSchemaBlock;\n}\n\nexport interface CompileSchemasOptions {\n /** \"inline\" for CLI .compiled.ts; \"lean\" for unplugin (imports from virtual:zod-compiler/runtime). */\n mode: CodegenMode;\n /**\n * Compact output (`output: \"compact\"`). Drop the compiled slow walk for\n * mutation-free, total-fast-path schemas and delegate their cold error path\n * to the retained Zod schema. Disables slow-walk sharing (delegated schemas\n * never emit a walk to share); delegated validators read the retained schema\n * through the `__zs` binding rather than through `__rf[]`.\n */\n compact?: boolean | undefined;\n /** When provided, per-schema failures call this and continue. Otherwise the first error throws. */\n onError?: (exportName: string, error: Error) => void;\n}\n\n/**\n * Occurrences of a generated identifier in `source`, ignoring the longer names\n * it is a prefix of — every generated name ends in `_<digits>`, so `__set_ks_1`\n * would otherwise count itself inside `__set_ks_10`.\n */\nfunction referenceCount(source: string, name: string): number {\n let count = 0;\n for (let at = source.indexOf(name); at !== -1; at = source.indexOf(name, at + name.length)) {\n const next = source.charCodeAt(at + name.length);\n if (!(next >= 48 && next <= 57)) count += 1;\n }\n return count;\n}\n\n/**\n * Plan exact constant initializers used by at least two validators in this file.\n *\n * Names are assigned per kind (`__zcSet_0`, …) and ordered by initializer text,\n * so a given file always produces the same names for the same content.\n */\nfunction planSharedConstants(\n results: readonly CompiledSchemaInfo[],\n constantsByResult: ReadonlyMap<CodeGenResult, readonly GeneratedConstant[]>,\n): ReadonlyMap<string, string> {\n const byInitializer = new Map<string, { kind: ConstantKind; users: Set<CodeGenResult> }>();\n for (const { codegenResult } of results) {\n const source = `${codegenResult.code}\\n${codegenResult.functionDef}`;\n for (const constant of constantsByResult.get(codegenResult) ?? []) {\n const declaration = `var ${constant.name}=${constant.initializer};`;\n // Fast-path generation can emit a constant before a later node aborts.\n // Its preamble is rolled back, so only collect declarations that survived.\n if (!source.includes(declaration)) continue;\n // A surviving declaration is not the same as a use. Two generators emit a\n // constant before they can decline — the build path names its FAIL\n // sentinel up front, and an abandoned fast-path walk leaves whatever it\n // declared behind — so a validator can hold a declaration it never reads.\n // Counting those as pool users hoisted constants nothing referenced, and\n // (worse) tripped the regeneration pass for a file that gained nothing by\n // it. Require the name to appear at least once beyond its own declaration.\n if (referenceCount(source, constant.name) < 2) continue;\n const entry = byInitializer.get(constant.initializer);\n if (entry === undefined) {\n byInitializer.set(constant.initializer, {\n kind: constant.kind,\n users: new Set([codegenResult]),\n });\n } else {\n entry.users.add(codegenResult);\n }\n }\n }\n\n const repeated = [...byInitializer.entries()]\n .filter(([, entry]) => entry.users.size >= 2)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n\n const nextIndex = new Map<ConstantKind, number>();\n return new Map(\n repeated.map(([initializer, entry]) => {\n const index = nextIndex.get(entry.kind) ?? 0;\n nextIndex.set(entry.kind, index + 1);\n return [initializer, `__zc${entry.kind}_${index}`];\n }),\n );\n}\n\nfunction emitSharedConstants(sharedConstantNames: ReadonlyMap<string, string>): string {\n return [...sharedConstantNames]\n .map(([initializer, name]) => {\n // `/* @__PURE__ */` earns its bytes only on a constructor call, where it\n // tells a bundler the declaration is droppable when nothing reads it. On a\n // plain object literal it is inert, and the annotation is longer than the\n // initializer it annotates.\n const pure = initializer.startsWith(\"new \") ? \"/* @__PURE__ */\" : \"\";\n return `var ${name}=${pure}${initializer};`;\n })\n .join(\"\\n\");\n}\n\n/**\n * Run the extract → generate pipeline for each discovered schema.\n * Shared by CLI generate and unplugin transform.\n *\n * Pass 1 extracts every schema's IR and plans repeated slow walks. Pass 2\n * generates each validator, calling shared `__zcSw_N` functions instead of\n * re-inlining them. Exact constant initializers reported during generation are\n * then pooled when at least two validators use them. Files with no repetition\n * keep their original local declarations.\n */\nexport function compileSchemas(\n schemas: DiscoveredSchema[],\n options: CompileSchemasOptions,\n): CompileSchemasResult {\n const handle = (exportName: string, err: unknown): void => {\n if (options.onError) {\n options.onError(exportName, err instanceof Error ? err : new Error(String(err)));\n } else {\n throw err;\n }\n };\n\n // Pass 1: extract IR (and fallback refs) for every schema.\n const extracted: Array<{\n exportName: string;\n schema: unknown;\n ir: SchemaIR;\n refEntries: RefEntry[];\n errorClass: ZodErrorClass;\n }> = [];\n for (const s of schemas) {\n try {\n const refEntries: RefEntry[] = [];\n const ir = extractSchema(s.schema, refEntries);\n extracted.push({\n exportName: s.exportName,\n schema: s.schema,\n ir,\n refEntries,\n // Read off the schema object, whose methods the validator replaces;\n // the IR is the same for classic and mini.\n errorClass: zodErrorClassOf(s.schema),\n });\n } catch (err) {\n handle(s.exportName, err);\n }\n }\n\n // Compact mode delegates the cold error path of total-fast-path schemas to\n // zod, so they emit no slow walk to share — skip the plan (and the dead\n // shared functions it would generate for shapes that now only delegate).\n const plan = options.compact\n ? undefined\n : createSharedSchemaPlan(\n extracted.map((e) => e.ir),\n options.mode,\n );\n\n // Pass 2: generate each validator, sharing repeated slow walks via the plan\n // and observing which constant declarations survive codegen rollback.\n const generated: Array<{\n exportName: string;\n schema: unknown;\n ir: SchemaIR;\n refEntries: RefEntry[];\n errorClass: ZodErrorClass;\n codegenResult: CodeGenResult;\n }> = [];\n const constantsByResult = new Map<CodeGenResult, GeneratedConstant[]>();\n for (const e of extracted) {\n try {\n const constants = new Map<string, GeneratedConstant>();\n const codegenResult = generateValidator(e.ir, e.exportName, {\n refCount: e.refEntries.length,\n mode: options.mode,\n sharedSchemas: plan,\n compact: options.compact,\n errorClass: e.errorClass,\n onConstant(constant) {\n constants.set(constant.name, constant);\n },\n });\n constantsByResult.set(codegenResult, [...constants.values()]);\n generated.push({\n exportName: e.exportName,\n schema: e.schema,\n ir: e.ir,\n refEntries: e.refEntries,\n errorClass: e.errorClass,\n codegenResult,\n });\n } catch (err) {\n handle(e.exportName, err);\n }\n }\n\n const initialResults = generated.map(\n ({ exportName, codegenResult, refEntries }): CompiledSchemaInfo => ({\n exportName,\n codegenResult,\n refEntries,\n }),\n );\n const sharedConstantNames = planSharedConstants(initialResults, constantsByResult);\n\n // Regenerate only when sharing is profitable. Selecting shared names before\n // emission avoids textual rewriting of generated JavaScript, where a user\n // enum string can legally contain text resembling a generated identifier.\n if (sharedConstantNames.size > 0) {\n for (const entry of generated) {\n entry.codegenResult = generateValidator(entry.ir, entry.exportName, {\n refCount: entry.refEntries.length,\n mode: options.mode,\n sharedSchemas: plan,\n compact: options.compact,\n errorClass: entry.errorClass,\n sharedConstantNames,\n });\n }\n }\n\n const results: CompiledSchemaInfo[] = generated.map((entry) => ({\n exportName: entry.exportName,\n codegenResult: entry.codegenResult,\n refEntries: entry.refEntries,\n }));\n\n const sharedConstantCode = emitSharedConstants(sharedConstantNames);\n const slowWalkCode = plan?.code ?? \"\";\n const sharedCode =\n sharedConstantCode === \"\"\n ? slowWalkCode\n : slowWalkCode === \"\"\n ? `${SHARED_BLOCK_MARKER}\\n${sharedConstantCode}`\n : `${slowWalkCode}\\n${sharedConstantCode}`;\n\n return {\n schemas: results,\n shared: { code: sharedCode, usedHelpers: plan?.usedHelpers ?? new Set() },\n };\n}\n\n/**\n * Aggregate `usedHelpers` across multiple compiled schemas (typically all schemas in one file).\n * Used by the unplugin transform to construct a single import statement per file.\n */\nexport function aggregateUsedHelpers(schemas: CompiledSchemaInfo[]): Set<string> {\n const all = new Set<string>();\n for (const s of schemas)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
- /**
3
- * SchemaIR — Intermediate representation for Zod schemas.
4
- * Extracted from Zod's `_zod.def` and `_zod.bag` at build time.
5
- */
6
4
  /** Shared base: static custom error message extracted from the check's `error` param. */
7
5
  interface CheckBase {
8
6
  /** Static message from e.g. `.min(3, "too short")`. Dynamic error maps force fallback. */
@@ -641,6 +639,19 @@ interface CompiledSchema<T> {
641
639
  */
642
640
  is(input: unknown): input is T;
643
641
  }
642
+ /**
643
+ * What `compile()` and `jit()` accept: a schema built by classic `zod` or by
644
+ * `zod/mini`. The compiler reads only the internals the two share, so either
645
+ * compiles to the same validator.
646
+ *
647
+ * Deliberately narrower than zod/v4/core's `$ZodType`, which both extend. Both
648
+ * functions return the schema itself, typed as carrying `parse`/`safeParse`,
649
+ * and until a build replaces them those are the schema's OWN methods (and stay
650
+ * so under `jit()` wherever runtime codegen is off). A schema built straight
651
+ * from `zod/v4/core` has none, so admitting it would type-check calls that
652
+ * throw.
653
+ */
654
+ type CompilableSchema = ZodType | ZodMiniType;
644
655
  //#endregion
645
- export { AnyIR, ArrayIR, BigIntCheckIR, BigIntIR, BooleanIR, CatchIR, CheckBase, CheckBigIntGreaterThan, CheckBigIntLessThan, CheckBigIntMultipleOf, CheckDateGreaterThan, CheckDateLessThan, CheckEndsWith, CheckGreaterThan, CheckIR, CheckIncludes, CheckLengthEquals, CheckLessThan, CheckMaxLength, CheckMaxSize, CheckMimeType, CheckMinLength, CheckMinSize, CheckMultipleOf, CheckNumberFormat, CheckOrEffectIR, CheckSizeEquals, CheckStartsWith, CheckStringFormat, CompiledSchema, CustomIR, DateCheckIR, DateIR, DefaultIR, DiscoveredSchema, DiscriminatedUnionIR, EnumIR, FallbackIR, FileCheckIR, FileIR, IntersectionIR, LiteralIR, LiteralValue, MapIR, NanIR, NeverIR, NullIR, NullableIR, NumberIR, ObjectIR, OptionalIR, OverwriteEffectCheckIR, PipeIR, PreprocessEffectIR, ReadonlyIR, RecordIR, RecursionTargetIR, RecursiveRefIR, RefineEffectCheckIR, SafeParseError, SafeParseResult, SafeParseSuccess, SchemaIR, SetCheckIR, SetIR, StringBoolIR, StringIR, SuperRefineEffectCheckIR, SymbolIR, TemplateLiteralIR, TransformEffectIR, TupleIR, TypeMessageCarrier, UndefinedIR, UnionIR, UnknownIR, VoidIR, ZodDelegateIR, ZodErrorLike, ZodIssueLike };
656
+ export { AnyIR, ArrayIR, BigIntCheckIR, BigIntIR, BooleanIR, CatchIR, CheckBase, CheckBigIntGreaterThan, CheckBigIntLessThan, CheckBigIntMultipleOf, CheckDateGreaterThan, CheckDateLessThan, CheckEndsWith, CheckGreaterThan, CheckIR, CheckIncludes, CheckLengthEquals, CheckLessThan, CheckMaxLength, CheckMaxSize, CheckMimeType, CheckMinLength, CheckMinSize, CheckMultipleOf, CheckNumberFormat, CheckOrEffectIR, CheckSizeEquals, CheckStartsWith, CheckStringFormat, CompilableSchema, CompiledSchema, CustomIR, DateCheckIR, DateIR, DefaultIR, DiscoveredSchema, DiscriminatedUnionIR, EnumIR, FallbackIR, FileCheckIR, FileIR, IntersectionIR, LiteralIR, LiteralValue, MapIR, NanIR, NeverIR, NullIR, NullableIR, NumberIR, ObjectIR, OptionalIR, OverwriteEffectCheckIR, PipeIR, PreprocessEffectIR, ReadonlyIR, RecordIR, RecursionTargetIR, RecursiveRefIR, RefineEffectCheckIR, SafeParseError, SafeParseResult, SafeParseSuccess, SchemaIR, SetCheckIR, SetIR, StringBoolIR, StringIR, SuperRefineEffectCheckIR, SymbolIR, TemplateLiteralIR, TransformEffectIR, TupleIR, TypeMessageCarrier, UndefinedIR, UnionIR, UnknownIR, VoidIR, ZodDelegateIR, ZodErrorLike, ZodIssueLike };
646
657
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":[],"sources":["../../src/core/types.ts"],"mappings":";;;;;;UAQiB;;EAEf;;UAGe,uBAAuB;EACtC;EACA;;UAGe,uBAAuB;EACtC;EACA;;UAGe,0BAA0B;EACzC;EACA;;UA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SAEA,oBACA,qBAEA,WACA,gBACA,oBACA,UACA,aACA,iBACA,oBACA;UAKW,iBAAiB;EAChC;EACA,MAAM;;UAGS;EACf;EACA,OAAO;;KAGG,gBAAgB,KAAK,iBAAiB,KAAK;UAEtC;EACf;EACA;EACA;GAEC;;UAGc;EACf,QAAQ;;UAGO;EACf;EACA;;UAGe,eAAe;EAC9B,MAAM,iBAAiB;EACvB,WAAW,iBAAiB,QAAQ;EACpC,UAAU,iBAAiB,gBAAgB;EAC3C,eAAe,iBAAiB,QAAQ,gBAAgB;;;;;;;;;;EAUxD,GAAG,iBAAiB,SAAS"}
1
+ {"version":3,"file":"types.d.ts","names":[],"sources":["../../src/core/types.ts"],"mappings":";;;;UAWiB;;EAEf;;UAGe,uBAAuB;EACtC;EACA;;UAGe,uBAAuB;EACtC;EACA;;UAGe,0BAA0B;EACzC;EACA;;UAGe,yBAAyB;EACxC;EACA;EACA;;UAGe,sBAAsB;EACrC;EACA;EACA;;UAGe,wBAAwB;EACvC;EACA;;UAGe,0BAA0B;EACzC;EACA;;UAGe,0BAA0B;EACzC;EACA;EACA;;EAEA;;EAEA;EACA;;EAEA;EACA;;EAEA;;;;;;;;;;;;;;;;;;EAkBA;;UAGe,sBAAsB;EACrC;EACA;EACA;;UAGe,wBAAwB;EACvC;EACA;;UAGe,sBAAsB;EACrC;EACA;;KAGU,UACR,iBACA,iBACA,oBACA,mBACA,gBACA,kBACA,oBACA,oBACA,gBACA,kBACA;UAMa;EACf;;;;;;EAMA;;;;;;;;;EASA;;EAEA;;;;;;EAMA;;;;;;;;;EASA;;;;;;;;;;;;;UAce;EACf;;EAEA;;;;;;UAOe;EACf;;EAEA;;;KAIU,kBACR,UACA,sBACA,2BACA;UAIa,6BAA6B;EAC5C;EACA;EACA;EACA;;UAGe,0BAA0B;EACzC;EACA;EACA;EACA;;KAGU,cAAc,uBAAuB;UAIhC,+BAA+B;EAC9C;;EAEA;EACA;;UAGe,4BAA4B;EAC3C;;EAEA;EACA;;UAG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,KAAK;;UAKU;EACf;EACA;;;;;EAKA;;;;;;;EAOA;;EAEA,OAAO;;UAGQ;EACf;EACA;;EAEA;;EAEA;;EAEA,OAAO;;;;;;UASQ;EACf;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;UAQe;EACf;EACA,OAAO;;EAEP;;UAGe;EACf;EACA;;EAUA;;UAGe;EACf;EACA;;UAGe;EACf;EACA,OAAO;;EAEP;;UAGe;EACf;;;;;;;;;EASA;;;;;;;;;;UAWe;EACf;EACA;EACA,OAAO;;UAGQ;EACf;EACA;EACA;EACA;;;;;;;;;UAYe;EACf;;KAGU,WAAW,sBAGjB,WACA,WACA,YACA,WACA,SACA,WACA,SACA,cACA,SACA,QACA,UACA,QACA,YACA,YACA,SAEA,WACA,UACA,UACA,WACA,QACA,QACA,SAEA,UACA,uBACA,iBAEA,aACA,aACA,aACA,YACA,SAEA,oBACA,qBAEA,WACA,gBACA,oBACA,UACA,aACA,iBACA,oBACA;UAKW,iBAAiB;EAChC;EACA,MAAM;;UAGS;EACf;EACA,OAAO;;KAGG,gBAAgB,KAAK,iBAAiB,KAAK;UAEtC;EACf;EACA;EACA;GAEC;;UAGc;EACf,QAAQ;;UAGO;EACf;EACA;;UAGe,eAAe;EAC9B,MAAM,iBAAiB;EACvB,WAAW,iBAAiB,QAAQ;EACpC,UAAU,iBAAiB,gBAAgB;EAC3C,eAAe,iBAAiB,QAAQ,gBAAgB;;;;;;;;;;EAUxD,GAAG,iBAAiB,SAAS;;;;;;;;;;;;;;KAenB,mBAAmB,UAAU"}
@@ -1,9 +1,11 @@
1
- import { ZodType } from "zod";
1
+ import { core } from "zod";
2
2
  //#region src/is-zod-schema.d.ts
3
3
  /**
4
4
  * Is this value a Zod schema? Zod schemas carry `_zod.def`, so that is the
5
5
  * probe — the same one auto-discovery uses at build time and `jitAll` uses at
6
- * runtime.
6
+ * runtime. It holds for every flavor (classic, `zod/mini`, raw `zod/v4/core`),
7
+ * so the narrowing is to the `$ZodType` they all extend, not to classic's
8
+ * `ZodType`.
7
9
  *
8
10
  * The probe is applied to values the caller does not control: every own value
9
11
  * of a module namespace under `jitAll`, every export of a candidate file under
@@ -17,7 +19,7 @@ import { ZodType } from "zod";
17
19
  * Kept as a leaf module with no runtime imports: `jit`/`jitAll` reach it on the
18
20
  * startup path, where pulling in the build-time graph would be pure cost.
19
21
  */
20
- declare function isZodSchema(value: unknown): value is ZodType;
22
+ declare function isZodSchema(value: unknown): value is core.$ZodType;
21
23
  //#endregion
22
24
  export { isZodSchema };
23
25
  //# sourceMappingURL=is-zod-schema.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"is-zod-schema.d.ts","names":[],"sources":["../src/is-zod-schema.ts"],"mappings":";;;;;;;;;;;;;;;;;;;iBAmBgB,YAAY,iBAAiB,SAAS"}
1
+ {"version":3,"file":"is-zod-schema.d.ts","names":[],"sources":["../src/is-zod-schema.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;iBAqBgB,YAAY,iBAAiB,SAAS,KAAK"}