zod-compiler 1.26.0 → 1.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -132,7 +132,8 @@ that blocks eval both leave a working plain-Zod schema.
132
132
  | Bun | `import zodCompiler from "zod-compiler/bun"` |
133
133
  | Farm | `import zodCompiler from "zod-compiler/farm"` |
134
134
 
135
- Turbopack takes a loader rather than a plugin — see [Next.js (Turbopack)](#nextjs-turbopack).
135
+ Turbopack takes a loader rather than a plugin — see [Next.js (Turbopack)](#nextjs-turbopack). Metro
136
+ has neither — see [React Native / Expo](#react-native--expo).
136
137
 
137
138
  ### Options
138
139
 
@@ -295,12 +296,47 @@ Defaults `codegenMode` to `"inline"` (SWC has no virtual-module hook); pass
295
296
  `zodCompiler: { codegenMode: "lean" }` if a later bundler resolves the runtime specifier. Honours
296
297
  `include`/`exclude` and keeps no disk cache.
297
298
 
299
+ ### React Native / Expo
300
+
301
+ There is no Metro plugin — unplugin has no Metro adapter. Use the [CLI](#3-cli-no-bundler); Metro
302
+ bundles what it emits as ordinary source:
303
+
304
+ ```bash
305
+ npx zod-compiler generate src/schemas/ -o src/schemas/compiled/ --watch
306
+ ```
307
+
308
+ Worth the step: **Hermes ships no JIT and no `new Function`**, so Zod's own object fast path is
309
+ unavailable on device and [`jit()`](#4-runtime-compilation-no-build-step) cannot run there at all.
310
+
311
+ Keep schema modules free of `react-native` and `expo-*` imports, transitively — discovery executes
312
+ each file and its import graph in Node (in both modes), and one that throws falls back to runtime
313
+ Zod silently.
314
+
298
315
  ### Compact Output (`output: "compact"`)
299
316
 
300
317
  Compiles the fast path and delegates the cold error path to the retained Zod schema, dropping
301
318
  **~73% raw / ~71% gzipped** on 50 distinct schemas. The hot path is unchanged and errors are Zod's own;
302
319
  only reading `.error` invokes Zod. Mutually exclusive with `output: "bag"`.
303
320
 
321
+ ```typescript
322
+ zodCompiler({ output: "compact" });
323
+ ```
324
+
325
+ ### Workers and Serverless Startup
326
+
327
+ Workers often construct every imported schema during module initialization, even when an isolate only
328
+ validates a few of them. Compiling all of those schemas can improve validation while increasing bundle
329
+ size and startup work. Compact output reduces compiler-generated error-path code, but still retains the
330
+ original Zod schema and does not make eager schema construction lazy.
331
+
332
+ Automatic discovery remains the default. If an application has a clear schema boundary, narrow
333
+ `include` or use `schemas: "explicit"` to avoid compiling intermediate exports.
334
+
335
+ Use `output: "bag"` only when consumers do not need Zod APIs such as `.shape`, `.extend()`, `.meta()`,
336
+ or `z.toJSONSchema()`; it can omit the retained schema entirely.
337
+
338
+ Measure startup separately from validation throughput using the target deployment and bundle.
339
+
304
340
  ### Auto Mode: Side Effects Warning
305
341
 
306
342
  Auto mode executes files to inspect their exports, so a file with schema-shaped exports **and** side
@@ -481,6 +517,9 @@ Schema-level `error` and `z.config()` maps are unaffected; for a per-call map us
481
517
  | medium object (invalid) | 504K | 80K | **14.7M** | 2.9M | 7.7M | **184x** |
482
518
  | large object (10 items) | 122K | 166K | **5.3M** | 5.9M | 1.2M | **32x** |
483
519
  | large object (100 items) | 13K | 18K | **781K** | 1.3M | 125K | **43x** |
520
+ | readonly field (wrapper compiles away) | 3.1M | 4.4M | **15.7M** | — | — | 3.6x |
521
+ | readonly root object (rebuild + freeze) | 2.9M | 3.8M | **12.2M** | — | — | 3.2x |
522
+ | readonly array (delegates to Zod) | 3.9M | 2.9M | **2.9M** | — | — | 1.0x |
484
523
  | recursive tree (7 nodes) | 569K | 2.1M | **8.2M** | 11.6M | 4.8M | 3.9x |
485
524
  | recursive tree (121 nodes) | 32K | 135K | **800K** | 1.9M | 372K | 5.9x |
486
525
  | nested recursion (7 nodes) | 391K | 1.0M | **7.9M** | 11.1M | 3.1M | 7.8x |
@@ -11,8 +11,8 @@ interface EmitterOptions {
11
11
  */
12
12
  zodCompat?: boolean | undefined;
13
13
  /**
14
- * File-level shared validator declarations (schema dedup). Emitted once at
15
- * module scope so each compiled export can call into them.
14
+ * File-level shared validator and constant declarations. Emitted once at
15
+ * module scope so each compiled export can reference them.
16
16
  */
17
17
  sharedCode?: string | undefined;
18
18
  }
@@ -1 +1 @@
1
- {"version":3,"file":"emitter.js","names":[],"sources":["../../src/cli/emitter.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n FAIL_CLASS_DECL,\n FAILZ_CLASS_DECL,\n FIN_DECL,\n FIN_DEFERRED_DECL,\n FINZ_DECL,\n generateIIFE,\n MK_VALIDATOR_DECL,\n ZOD_CONFIG_IMPORT,\n ZOD_MSG_DECLARATION,\n} from \"../core/iife.js\";\nimport type { CompiledSchemaInfo } from \"../core/pipeline.js\";\n\n/**\n * Generate the content of a .compiled.ts file from multiple schemas.\n */\nexport interface EmitterOptions {\n /**\n * When true (default), installs the compiled methods on the original schema\n * object for Zod-compatible output.\n * When false, produces a minimal plain object (smaller bundle).\n */\n zodCompat?: boolean | undefined;\n /**\n * File-level shared validator declarations (schema dedup). Emitted once at\n * module scope so each compiled export can call into them.\n */\n sharedCode?: string | undefined;\n}\n\nexport function generateCompiledFileContent(\n schemas: CompiledSchemaInfo[],\n sourceRelPath: string,\n options?: EmitterOptions,\n): string {\n let importPath = sourceRelPath.replace(/\\.[cm]?[jt]sx?$/, \"\");\n if (!importPath.startsWith(\".\")) {\n importPath = `./${importPath}`;\n }\n\n const zodCompat = options?.zodCompat !== false;\n\n // Compact-mode schemas delegate cold errors to zod via __zcFinZ (its own\n // __ZcFailZ class), emitted only when some export uses it.\n const usesFinZ = schemas.some((s) => s.codegenResult.usedHelpers.has(\"__zcFinZ\"));\n\n // A schema needs the source import when:\n // - zodCompat: true (__zcMkv installs compiled methods on the schema)\n // - has refEntries (fallback schemas referenced via __rf[])\n const schemasNeedingImport = schemas.filter((s) => zodCompat || s.refEntries.length > 0);\n\n const exports = schemas.map((schema) => {\n const needsImport = zodCompat || schema.refEntries.length > 0;\n // `compile()` returns the schema augmented with a non-enumerable `schema`\n // self-reference; auto-discovery (the default) instead finds plain exported\n // Zod schemas, which have no such property. Both shapes must resolve, so\n // fall through to the export itself — reading `.schema` alone yields\n // undefined there, which silently cost __zcMkv the real schema to augment\n // and hard-crashed every `__rf[]` base at module load.\n const src = `__src_${schema.exportName}`;\n const schemaExpr = needsImport ? `((${src} as any).schema ?? ${src})` : \"\";\n return `export const ${schema.exportName} = ${generateIIFE(schemaExpr, schema, { zodCompat })};`;\n });\n\n const importLine =\n schemasNeedingImport.length > 0\n ? [\n `import { ${schemasNeedingImport.map((s) => `${s.exportName} as __src_${s.exportName}`).join(\", \")} } from \"${importPath}\";`,\n \"\",\n ]\n : [];\n\n return [\n \"// AUTO-GENERATED by zod-compiler — DO NOT EDIT\",\n `// Source: ${sourceRelPath}`,\n \"\",\n ZOD_CONFIG_IMPORT,\n ZOD_MSG_DECLARATION,\n FAIL_CLASS_DECL,\n MK_VALIDATOR_DECL,\n FIN_DECL,\n FIN_DEFERRED_DECL,\n ...(usesFinZ ? [FAILZ_CLASS_DECL, FINZ_DECL] : []),\n ...(options?.sharedCode ? [\"\", options.sharedCode] : []),\n \"\",\n ...importLine,\n ...exports,\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Resolve the output file path for a given input file.\n */\nexport function resolveOutputPath(inputPath: string, outputFlag: string | undefined): string {\n if (outputFlag) {\n // If output flag ends with / or is a directory, put the compiled file inside it\n if (outputFlag.endsWith(\"/\") || outputFlag.endsWith(path.sep)) {\n const baseName = path.basename(inputPath, path.extname(inputPath));\n return path.join(outputFlag, `${baseName}.compiled.ts`);\n }\n return outputFlag;\n }\n\n // Default: replace .ts with .compiled.ts\n const dir = path.dirname(inputPath);\n const baseName = path.basename(inputPath, path.extname(inputPath));\n return path.join(dir, `${baseName}.compiled.ts`);\n}\n\n/**\n * Write the compiled file content to disk.\n */\nexport async function writeCompiledFile(outputPath: string, content: string): Promise<void> {\n const dir = path.dirname(outputPath);\n await fs.promises.mkdir(dir, { recursive: true });\n await fs.promises.writeFile(outputPath, content, \"utf-8\");\n}\n"],"mappings":";;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ACA,OAAO;CACT;CAGA,MAAM,MAAM,KAAK,QAAQ,SAAS;CAClC,MAAM,WAAW,KAAK,SAAS,WAAW,KAAK,QAAQ,SAAS,CAAC;CACjE,OAAO,KAAK,KAAK,KAAK,GAAG,SAAS,aAAa;AACjD;;;;AAKA,eAAsB,kBAAkB,YAAoB,SAAgC;CAC1F,MAAM,MAAM,KAAK,QAAQ,UAAU;CACnC,MAAM,GAAG,SAAS,MAAM,KAAK,EAAE,WAAW,KAAK,CAAC;CAChD,MAAM,GAAG,SAAS,UAAU,YAAY,SAAS,OAAO;AAC1D"}
1
+ {"version":3,"file":"emitter.js","names":[],"sources":["../../src/cli/emitter.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n FAIL_CLASS_DECL,\n FAILZ_CLASS_DECL,\n FIN_DECL,\n FIN_DEFERRED_DECL,\n FINZ_DECL,\n generateIIFE,\n MK_VALIDATOR_DECL,\n ZOD_CONFIG_IMPORT,\n ZOD_MSG_DECLARATION,\n} from \"../core/iife.js\";\nimport type { CompiledSchemaInfo } from \"../core/pipeline.js\";\n\n/**\n * Generate the content of a .compiled.ts file from multiple schemas.\n */\nexport interface EmitterOptions {\n /**\n * When true (default), installs the compiled methods on the original schema\n * object for Zod-compatible output.\n * When false, produces a minimal plain object (smaller bundle).\n */\n zodCompat?: boolean | undefined;\n /**\n * File-level shared validator and constant declarations. Emitted once at\n * module scope so each compiled export can reference them.\n */\n sharedCode?: string | undefined;\n}\n\nexport function generateCompiledFileContent(\n schemas: CompiledSchemaInfo[],\n sourceRelPath: string,\n options?: EmitterOptions,\n): string {\n let importPath = sourceRelPath.replace(/\\.[cm]?[jt]sx?$/, \"\");\n if (!importPath.startsWith(\".\")) {\n importPath = `./${importPath}`;\n }\n\n const zodCompat = options?.zodCompat !== false;\n\n // Compact-mode schemas delegate cold errors to zod via __zcFinZ (its own\n // __ZcFailZ class), emitted only when some export uses it.\n const usesFinZ = schemas.some((s) => s.codegenResult.usedHelpers.has(\"__zcFinZ\"));\n\n // A schema needs the source import when:\n // - zodCompat: true (__zcMkv installs compiled methods on the schema)\n // - has refEntries (fallback schemas referenced via __rf[])\n const schemasNeedingImport = schemas.filter((s) => zodCompat || s.refEntries.length > 0);\n\n const exports = schemas.map((schema) => {\n const needsImport = zodCompat || schema.refEntries.length > 0;\n // `compile()` returns the schema augmented with a non-enumerable `schema`\n // self-reference; auto-discovery (the default) instead finds plain exported\n // Zod schemas, which have no such property. Both shapes must resolve, so\n // fall through to the export itself — reading `.schema` alone yields\n // undefined there, which silently cost __zcMkv the real schema to augment\n // and hard-crashed every `__rf[]` base at module load.\n const src = `__src_${schema.exportName}`;\n const schemaExpr = needsImport ? `((${src} as any).schema ?? ${src})` : \"\";\n return `export const ${schema.exportName} = ${generateIIFE(schemaExpr, schema, { zodCompat })};`;\n });\n\n const importLine =\n schemasNeedingImport.length > 0\n ? [\n `import { ${schemasNeedingImport.map((s) => `${s.exportName} as __src_${s.exportName}`).join(\", \")} } from \"${importPath}\";`,\n \"\",\n ]\n : [];\n\n return [\n \"// AUTO-GENERATED by zod-compiler — DO NOT EDIT\",\n `// Source: ${sourceRelPath}`,\n \"\",\n ZOD_CONFIG_IMPORT,\n ZOD_MSG_DECLARATION,\n FAIL_CLASS_DECL,\n MK_VALIDATOR_DECL,\n FIN_DECL,\n FIN_DEFERRED_DECL,\n ...(usesFinZ ? [FAILZ_CLASS_DECL, FINZ_DECL] : []),\n ...(options?.sharedCode ? [\"\", options.sharedCode] : []),\n \"\",\n ...importLine,\n ...exports,\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Resolve the output file path for a given input file.\n */\nexport function resolveOutputPath(inputPath: string, outputFlag: string | undefined): string {\n if (outputFlag) {\n // If output flag ends with / or is a directory, put the compiled file inside it\n if (outputFlag.endsWith(\"/\") || outputFlag.endsWith(path.sep)) {\n const baseName = path.basename(inputPath, path.extname(inputPath));\n return path.join(outputFlag, `${baseName}.compiled.ts`);\n }\n return outputFlag;\n }\n\n // Default: replace .ts with .compiled.ts\n const dir = path.dirname(inputPath);\n const baseName = path.basename(inputPath, path.extname(inputPath));\n return path.join(dir, `${baseName}.compiled.ts`);\n}\n\n/**\n * Write the compiled file content to disk.\n */\nexport async function writeCompiledFile(outputPath: string, content: string): Promise<void> {\n const dir = path.dirname(outputPath);\n await fs.promises.mkdir(dir, { recursive: true });\n await fs.promises.writeFile(outputPath, content, \"utf-8\");\n}\n"],"mappings":";;;;AAgCA,SAAgB,4BACd,SACA,eACA,SACQ;CACR,IAAI,aAAa,cAAc,QAAQ,mBAAmB,EAAE;CAC5D,IAAI,CAAC,WAAW,WAAW,GAAG,GAC5B,aAAa,KAAK;CAGpB,MAAM,YAAY,SAAS,cAAc;CAIzC,MAAM,WAAW,QAAQ,MAAM,MAAM,EAAE,cAAc,YAAY,IAAI,UAAU,CAAC;CAKhF,MAAM,uBAAuB,QAAQ,QAAQ,MAAM,aAAa,EAAE,WAAW,SAAS,CAAC;CAEvF,MAAM,UAAU,QAAQ,KAAK,WAAW;EACtC,MAAM,cAAc,aAAa,OAAO,WAAW,SAAS;EAO5D,MAAM,MAAM,SAAS,OAAO;EAC5B,MAAM,aAAa,cAAc,KAAK,IAAI,qBAAqB,IAAI,KAAK;EACxE,OAAO,gBAAgB,OAAO,WAAW,KAAK,aAAa,YAAY,QAAQ,EAAE,UAAU,CAAC,EAAE;CAChG,CAAC;CAED,MAAM,aACJ,qBAAqB,SAAS,IAC1B,CACE,YAAY,qBAAqB,KAAK,MAAM,GAAG,EAAE,WAAW,YAAY,EAAE,YAAY,CAAC,CAAC,KAAK,IAAI,EAAE,WAAW,WAAW,KACzH,EACF,IACA,CAAC;CAEP,OAAO;EACL;EACA,cAAc;EACd;EACA;EACA;EACA;EACA;EACA;EACA;EACA,GAAI,WAAW,CAAC,kBAAkB,SAAS,IAAI,CAAC;EAChD,GAAI,SAAS,aAAa,CAAC,IAAI,QAAQ,UAAU,IAAI,CAAC;EACtD;EACA,GAAG;EACH,GAAG;EACH;CACF,CAAC,CAAC,KAAK,IAAI;AACb;;;;AAKA,SAAgB,kBAAkB,WAAmB,YAAwC;CAC3F,IAAI,YAAY;EAEd,IAAI,WAAW,SAAS,GAAG,KAAK,WAAW,SAAS,KAAK,GAAG,GAAG;GAC7D,MAAM,WAAW,KAAK,SAAS,WAAW,KAAK,QAAQ,SAAS,CAAC;GACjE,OAAO,KAAK,KAAK,YAAY,GAAG,SAAS,aAAa;EACxD;EACA,OAAO;CACT;CAGA,MAAM,MAAM,KAAK,QAAQ,SAAS;CAClC,MAAM,WAAW,KAAK,SAAS,WAAW,KAAK,QAAQ,SAAS,CAAC;CACjE,OAAO,KAAK,KAAK,KAAK,GAAG,SAAS,aAAa;AACjD;;;;AAKA,eAAsB,kBAAkB,YAAoB,SAAgC;CAC1F,MAAM,MAAM,KAAK,QAAQ,UAAU;CACnC,MAAM,GAAG,SAAS,MAAM,KAAK,EAAE,WAAW,KAAK,CAAC;CAChD,MAAM,GAAG,SAAS,UAAU,YAAY,SAAS,OAAO;AAC1D"}
@@ -3,6 +3,11 @@ import { SharedSchemaPlan } from "./dedupe.js";
3
3
  //#region src/core/codegen/context.d.ts
4
4
  /** Codegen output mode. "inline" emits self-contained code (CLI .compiled.ts). "lean" emits references to imports from "virtual:zod-compiler/runtime" (unplugin). */
5
5
  type CodegenMode = "inline" | "lean";
6
+ /** A Set declaration emitted while generating one validator. */
7
+ interface GeneratedSetConstant {
8
+ readonly name: string;
9
+ readonly initializer: string;
10
+ }
6
11
  interface CodeGenResult {
7
12
  code: string;
8
13
  functionDef: string;
@@ -97,6 +102,10 @@ interface CodeGenContext {
97
102
  effectFnCache?: Map<string, string>;
98
103
  /** Dedup cache for constant preamble declarations: initializer text → preamble var. */
99
104
  valueCache?: Map<string, string>;
105
+ /** Reports generated Sets so the file pipeline can share exact duplicates across validators. */
106
+ onSetConstant?: ((constant: GeneratedSetConstant) => void) | undefined;
107
+ /** Exact Set initializer → file-level name, populated by the pipeline's second codegen pass. */
108
+ sharedSetNames?: ReadonlyMap<string, string> | undefined;
100
109
  /** Name of the build path's FAIL sentinel, declared once per validator. */
101
110
  buildFailName?: string;
102
111
  /** Hosted build-function name per recursion target refId, so back-edges resolve. */
@@ -314,6 +323,8 @@ declare function emitEffectCallable(ctx: CodeGenContext, effect: {
314
323
  * a cycle.
315
324
  */
316
325
  declare function emitRfDelegate(ctx: CodeGenContext, refIndex: number): string;
326
+ /** Capture a pristine Zod method without allocating a bound function. */
327
+ declare function emitRfMethod(ctx: CodeGenContext, refIndex: number): string;
317
328
  /**
318
329
  * Resolve a regex pattern to a runtime variable name.
319
330
  * Lean mode short-circuits well-known patterns to virtual-module names so the
@@ -486,5 +497,5 @@ declare function rejectsUndefined(ir: SchemaIR): boolean;
486
497
  */
487
498
  declare function checkPriority(a: CheckIR | BigIntCheckIR | DateCheckIR | SetCheckIR, b: CheckIR | BigIntCheckIR | DateCheckIR | SetCheckIR): number;
488
499
  //#endregion
489
- export { CodeGenContext, CodeGenResult, CodegenMode, ENUM_INLINE_THRESHOLD, FastGen, FastGenerator, FastScope, KEY_MEMBERSHIP_INLINE_THRESHOLD, RecTargetGen, SlowGen, SlowGenerator, SourceFormLiteral, checkPriority, declareFastTemps, emitConstant, emitEffectCallable, emitEffectFn, emitRegex, emitRegexSourceString, emitRfDelegate, emitRuntimeHelper, emitSet, emitTemp, escapeString, extendPath, extendStaticPath, extendStaticPathIndex, fastSentinelWrapper, hasMutation, hasSourceForm, keyMembershipTest, literalToJs, outputAlwaysDefined, rejectsUndefined, tuplePadsShortInput };
500
+ export { CodeGenContext, CodeGenResult, CodegenMode, ENUM_INLINE_THRESHOLD, FastGen, FastGenerator, FastScope, GeneratedSetConstant, KEY_MEMBERSHIP_INLINE_THRESHOLD, RecTargetGen, SlowGen, SlowGenerator, SourceFormLiteral, checkPriority, declareFastTemps, emitConstant, emitEffectCallable, emitEffectFn, emitRegex, emitRegexSourceString, emitRfDelegate, emitRfMethod, emitRuntimeHelper, emitSet, emitTemp, escapeString, extendPath, extendStaticPath, extendStaticPathIndex, fastSentinelWrapper, hasMutation, hasSourceForm, keyMembershipTest, literalToJs, outputAlwaysDefined, rejectsUndefined, tuplePadsShortInput };
490
501
  //# sourceMappingURL=context.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"context.d.ts","names":[],"sources":["../../../src/core/codegen/context.ts"],"mappings":";;;;KAgBY;UAEK;EACf;EACA;;EAEA;;;;;;EAMA,aAAa;;;;;;;EAOb;;;;;;;;;;EAUA;;;;;;;EAOA;;;;;;;;EAQA;;;UAIe;;EAEf;;;;;EAKA;;;;;;EAMA;;EAEA,QAAQ;;;UAIO;EACf;EACA;EACA;;EAEA,YAAY;;EAEZ,MAAM;;EAEN,aAAa;;;;;;;;EAQb;;;;;;;;;EASA,aAAa,YAAY;;EAEzB,gBAAgB;;EAEhB,aAAa;;EAEb;;EAEA,gBAAgB;;;;;;;;;;EAUhB;;EAEA,gBAAgB,QAAQ;;EAExB,uBAAuB,QAAQ;;;;;;EAM/B,gBAAgB;;;UAMD;WACN;WACA;WACA;WACA;WACA,KAAK;;;;;;;WAOL;;;;;;;;;;;;;;;;WAiBA;;;;;;;;;EAUT,MACE,IAAI,UACJ;IACE;IACA;IACA;IACA;IAGA;;;EAKJ,KAAK;;EAGL,MAAM,gBAAgB,iBAAiB;;EAGvC,IAAI,gBAAgB;;;KAIV,cAAc,UAAU,WAAW,aAAa,IAAI,GAAG,GAAG;;;;;;UASrD;EACf;;;;;;;;;;;EAWA;;;iBAIc,iBAAiB,OAAO;;;;;;;;;;;;;;;;;;;;iBAuBxB,oBACd,GAAG,SACH,SAAS,UACT,kBACA;;UAkBe;WACN;WACA,KAAK;;;;;;;WAQL;;WAGA,OAAO;;;;;;;WAQP;;;;;EAMT,MAAM,IAAI,UAAU;IAAc;IAAgB;;;;;;;;;EASlD,OAAO,gBAAgB;;EAGvB,KAAK;;;;;;;EAQL,MAAM;;EAGN,MAAM,gBAAgB,iBAAiB;;;KAI7B,cAAc,UAAU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,KAAK,gBAAgB,gBAAgB;;;;;;;;;;;;;;;;;;;;cA4BhD;;;;;;;;;;iBAWG,kBACd,KAAK,gBACL,yBACA;;;;;;;;cAgBW;iBA8BG,aAAa;;KAKjB;;;;;;;;;;;;;;;iBAgBI,cAAc,GAAG,eAAe,KAAK;;;;;;;;;;iBAerC,YAAY,GAAG;;;;;;iBA+Bf,kBAAkB,KAAK,gBAAgB,cAAc;;;;;;;;;;;;iBAqBrD,WAAW,oBAAoB;;iBAS/B,iBAAiB,oBAAoB;;iBAKrC,sBAAsB,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;iBAsC1C,oBAAoB,IAAI;EAAa;;iBAIrC,YAAY,IAAI;;;;;;;;;;;;;;iBAuFhB,oBAAoB,IAAI;;;;;;;;;iBAYxB,iBAAiB,IAAI;;;;;iBAiDrB,cACd,GAAG,UAAU,gBAAgB,cAAc,YAC3C,GAAG,UAAU,gBAAgB,cAAc"}
@@ -100,6 +100,13 @@ function emitRfDelegate(ctx, refIndex) {
100
100
  if (!ctx.preamble.includes(decl)) ctx.preamble.push(decl);
101
101
  return name;
102
102
  }
103
+ /** Capture a pristine Zod method without allocating a bound function. */
104
+ function emitRfMethod(ctx, refIndex) {
105
+ const name = `__rfm_${refIndex}`;
106
+ const decl = `var ${name}=__rf[${refIndex}].safeParse;`;
107
+ if (!ctx.preamble.includes(decl)) ctx.preamble.push(decl);
108
+ return name;
109
+ }
103
110
  /**
104
111
  * Resolve a regex pattern to a runtime variable name.
105
112
  * Lean mode short-circuits well-known patterns to virtual-module names so the
@@ -169,7 +176,15 @@ function emitConstant(ctx, prefix, initializer) {
169
176
  }
170
177
  /** Declare a `new Set([...])` in the preamble and return its variable name. */
171
178
  function emitSet(ctx, prefix, values) {
172
- return emitConstant(ctx, `set_${prefix}`, `new Set(${JSON.stringify([...values])})`);
179
+ const initializer = `new Set(${JSON.stringify([...values])})`;
180
+ const sharedName = ctx.sharedSetNames?.get(initializer);
181
+ if (sharedName !== void 0) return sharedName;
182
+ const name = emitConstant(ctx, `set_${prefix}`, initializer);
183
+ ctx.onSetConstant?.({
184
+ name,
185
+ initializer
186
+ });
187
+ return name;
173
188
  }
174
189
  /**
175
190
  * Shape-key count at or below which the unknown-key pass compares with an
@@ -451,6 +466,6 @@ function checkPriority(a, b) {
451
466
  return (CHECK_PRIORITY[a.kind] ?? 99) - (CHECK_PRIORITY[b.kind] ?? 99);
452
467
  }
453
468
  //#endregion
454
- export { ENUM_INLINE_THRESHOLD, KEY_MEMBERSHIP_INLINE_THRESHOLD, checkPriority, declareFastTemps, emitConstant, emitEffectCallable, emitEffectFn, emitRegex, emitRegexSourceString, emitRfDelegate, emitRuntimeHelper, emitSet, emitTemp, escapeString, extendPath, extendStaticPath, extendStaticPathIndex, fastSentinelWrapper, hasMutation, hasSourceForm, keyMembershipTest, literalToJs, outputAlwaysDefined, rejectsUndefined, tuplePadsShortInput };
469
+ export { ENUM_INLINE_THRESHOLD, KEY_MEMBERSHIP_INLINE_THRESHOLD, checkPriority, declareFastTemps, emitConstant, emitEffectCallable, emitEffectFn, emitRegex, emitRegexSourceString, emitRfDelegate, emitRfMethod, emitRuntimeHelper, emitSet, emitTemp, escapeString, extendPath, extendStaticPath, extendStaticPathIndex, fastSentinelWrapper, hasMutation, hasSourceForm, keyMembershipTest, literalToJs, outputAlwaysDefined, rejectsUndefined, tuplePadsShortInput };
455
470
 
456
471
  //# sourceMappingURL=context.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","names":[],"sources":["../../../src/core/codegen/context.ts"],"sourcesContent":["import type {\n BigIntCheckIR,\n CheckIR,\n DateCheckIR,\n LiteralValue,\n SchemaIR,\n SetCheckIR,\n} from \"../types.js\";\nimport type { SharedSchemaPlan } from \"./dedupe.js\";\nimport {\n fastTestSource,\n lookupWellKnownRegex,\n wellKnownRegexSourceName,\n} from \"./well-known-regex.js\";\n\n/** Codegen output mode. \"inline\" emits self-contained code (CLI .compiled.ts). \"lean\" emits references to imports from \"virtual:zod-compiler/runtime\" (unplugin). */\nexport type CodegenMode = \"inline\" | \"lean\";\n\nexport interface CodeGenResult {\n code: string;\n functionDef: string;\n /** Number of fallback schemas referenced by __rf[N] in the generated code. 0 = no fallbacks. */\n refCount: number;\n /**\n * Helper names referenced by this schema in lean mode (e.g. \"__zcTS\", \"__zcReEmail\").\n * Used by the unplugin transform to construct the `import { ... } from \"virtual:zod-compiler/runtime\"` line.\n * Always empty in inline mode.\n */\n usedHelpers: Set<string>;\n /**\n * Name of the hosted fast-check boolean function in the preamble (null when\n * the schema has no Fast Path). generateIIFE passes it to __zcMkv so parse()\n * and parseAsync() can return valid input without allocating an\n * intermediate SafeParseResult.\n */\n fastFnName: string | null;\n /**\n * True when `fastFnName` is a TOTAL predicate: `fc(input) === true` iff the\n * schema accepts `input` (mutation-free schemas, where a fast-check failure\n * can never become a slow-path success). generateIIFE installs it as the\n * zero-allocation `.is()` guard. False for partial fast paths\n * (default/catch — `fc` only shortcuts present-and-valid input, so a `false`\n * result does NOT imply rejection) and for schemas with no fast path, such as\n * coercion; `.is()` then derives from `safeParse(input).success`.\n */\n fastTotal: boolean;\n /**\n * Hosted predicate installed as `.is()`, when it differs from `fastFnName`.\n * A schema that rebuilds its output has no by-reference shortcut (so\n * `fastFnName` is null) yet still has an exact acceptance predicate, because\n * stripping reshapes the payload and never the verdict.\n */\n isFnName?: string | null;\n /**\n * Compact mode only: the `__rf[N]` index this validator delegates its cold\n * error path to (the schema itself, captured as a fresh root RefEntry). When\n * set, the pipeline appends a `{ schema, accessPath: \"\" }` entry at this index\n * so `generateIIFE` materializes `__rf[N]` as the original Zod schema. Absent\n * for every non-compact (fully compiled) validator.\n */\n rootDelegateRefIndex?: number;\n}\n\n/** Hosted-validator names for one recursion target (see CodeGenContext.recTargets). */\nexport interface RecTargetGen {\n /** True for the root target (refId 0) — reuses the schema's own functions. */\n isRoot: boolean;\n /**\n * safeParse-shaped slow validator name: `safeParse_<name>` for the root,\n * `__rsp_N` for a non-root target. `slowRecursiveRef` calls this.\n */\n slowName: string;\n /**\n * Boolean fast-check name (`__fcr_N`). Allocated lazily for the root (mirrors\n * recFastName), eagerly for non-root targets. Absent until the fast path\n * reaches a ref to this target.\n */\n fastName?: string;\n /** Inner IR hosted as the standalone validator body (non-root targets only). */\n inner?: SchemaIR;\n}\n\n/** Shared mutable state for code generation. Fast and slow paths share the same instance. */\nexport interface CodeGenContext {\n preamble: string[];\n counter: number;\n fnName: string;\n /** Deduplicates regex patterns: same pattern string → same preamble variable name. */\n regexCache: Map<string, string>;\n /** Codegen output mode. */\n mode: CodegenMode;\n /** Names of helpers from \"virtual:zod-compiler/runtime\" referenced in this schema (lean mode only). */\n usedHelpers: Set<string>;\n /**\n * Name of the fast-path boolean helper for the ROOT recursion target\n * (refId 0), allocated on first fastRecursiveRef visit. generateValidator\n * wraps the root fast expression as `function <name>(input){return <expr>;}`\n * so recursive refs can call it. undefined = root has no recursion on the\n * fast path.\n */\n recFastName?: string;\n /**\n * Hosted-validator name table for recursion targets, keyed by refId. Entry 0\n * is the root (the schema's own `safeParse_<name>` / `recFastName`); entries\n * ≥ 1 are non-root targets hosted as standalone `__rsp_N` (slow) / `__fcr_N`\n * (fast) helpers. `recursiveRef`/`recursionTarget` generators look up the\n * call target here. Undefined when not generating a full validator (e.g. unit\n * tests calling a single generator) — treated as root-only.\n */\n recTargets?: Map<number, RecTargetGen>;\n /** Dedup cache for hosted zero-capture effect functions: source text → preamble var. */\n effectFnCache?: Map<string, string>;\n /** Dedup cache for constant preamble declarations: initializer text → preamble var. */\n valueCache?: Map<string, string>;\n /** Name of the build path's FAIL sentinel, declared once per validator. */\n buildFailName?: string;\n /** Hosted build-function name per recursion target refId, so back-edges resolve. */\n buildRecNames?: Map<number, string>;\n /**\n * Set by the build path when it emitted a `.default()` substitution. Such a\n * schema ACCEPTS an input its fast expression rejects — `fastDefault` demands a\n * present value, since the fast path's contract is `data === input` and a\n * substituted default is not the input — so the expression is no longer an\n * exact acceptance predicate and must not be installed as `.is()`. Stripping,\n * by contrast, reshapes only the payload, which is why a build-path schema\n * otherwise still hands its predicate over.\n */\n buildSubstitutesValue?: boolean;\n /** Memo for estimateFastCost (size-gated fast-check extraction). Lazily created. */\n fastSizeCache?: WeakMap<SchemaIR, number>;\n /** Memo for estimateRuntimeCost (cheapest-first check ordering). Lazily created. */\n fastRuntimeCostCache?: WeakMap<SchemaIR, number>;\n /**\n * File-level shared slow-walk plan. Set only when generating a mutation-free\n * schema (so shared walks stay on the deferred cold path); the slow-path\n * visit() consults it to replace a repeated sub-IR with a `__zcSw_N` call.\n */\n sharedSchemas?: SharedSchemaPlan;\n}\n\n// ─── Slow Path context ────────────────────────────────────────────────────────\n\n/** Context object for slow-path (error-collecting) generator functions. */\nexport interface SlowGen {\n readonly input: string;\n readonly output: string;\n readonly path: string;\n readonly issues: string;\n readonly ctx: CodeGenContext;\n /**\n * Schema-level static error message of the node being generated\n * (z.string({ error: \"...\" })). Default message for issues this node emits\n * when the individual check has no message of its own. Set by generateSlow()\n * from ir.typeMessage; never inherited by child nodes.\n */\n readonly typeMsg?: string | undefined;\n\n /**\n * Name of a boolean variable that this node sets to `true` when it aborts in\n * the zod sense (`payload.aborted`) — currently only a pipe/codec whose `in`\n * step fails (zod's `handlePipeResult` sets `left.aborted = true`). A `union`\n * allocates one per option and reads it during pruning so a pipe option whose\n * `in` failed counts as aborted even when its only issue is a non-aborting\n * `custom`/check-level code. Undefined when the node is not inside an\n * abort-tracking option, in which case the abort is a no-op.\n *\n * Unlike input/output/path/issues, this is NOT inherited by `visit()`: it is\n * cleared at every boundary unless a node explicitly forwards it (the\n * pass-through wrappers optional/nullable/readonly do), mirroring how zod\n * propagates `payload.aborted` through transparent wrappers but not across\n * container boundaries.\n */\n readonly aborted?: string | undefined;\n\n /**\n * Recursively generate validation for a child IR node.\n * input/output/path/issues are inherited from parent unless overridden;\n * `aborted` is the exception — it is only set when explicitly passed (see the\n * `aborted` field doc), so it never leaks into container children.\n * Union generators use `{ issues }` to redirect child errors to temporary arrays.\n * Container generators use `{ input, output, path }` for element traversal.\n */\n visit(\n ir: SchemaIR,\n overrides?: {\n input?: string;\n output?: string;\n path?: string;\n issues?: string;\n // `| undefined` (unlike the others): pass-through wrappers forward\n // `g.aborted` verbatim, which is undefined outside an abort-tracking option.\n aborted?: string | undefined;\n },\n ): string;\n\n /** Generate a unique temp variable name: `__${prefix}_${counter++}` */\n temp(prefix: string): string;\n\n /** Add a regex to preamble and return the variable name. */\n regex(prefix: string, pattern: string, flags?: string): string;\n\n /** Add a Set to preamble and return the variable name. */\n set(prefix: string, values: readonly unknown[]): string;\n}\n\n/** Slow-path generator function signature — registered in slowRegistry. */\nexport type SlowGenerator<T extends SchemaIR = SchemaIR> = (ir: T, g: SlowGen) => string;\n\n// ─── Fast Path context ────────────────────────────────────────────────────────\n\n/**\n * Per-emitted-function size accumulator for size-gated fast-check extraction.\n * Shared by every node inlined into the same function; a fresh instance starts\n * each hosted helper (and the root). See fast-size.ts / generateFast.\n */\nexport interface FastScope {\n used: number;\n /**\n * `var` temps that the function this scope is assembling must declare, in\n * allocation order. Populated by {@link FastGen.local}; every site that\n * materializes a function body from a fresh scope emits\n * {@link declareFastTemps} at the top of that body.\n *\n * Function-scoped (never module-scoped) is load-bearing: a recursive\n * validator re-enters itself while an outer frame still holds a live temp,\n * and each invocation needs its own binding.\n */\n temps: string[];\n}\n\n/** `var a,b;` declaration for a scope's temps, or \"\" when it allocated none. */\nexport function declareFastTemps(scope: FastScope): string {\n return scope.temps.length > 0 ? `var ${scope.temps.join(\",\")};` : \"\";\n}\n\n/**\n * Fast check for a wrapper that compares its input against a sentinel and\n * otherwise delegates to an inner schema — `optional` (`===undefined`),\n * `nullable` (`===null`) and `default` (`!==undefined`).\n *\n * Written naively these read the input TWICE: once for the sentinel test and\n * again inside the inner check (which may itself read it several more times —\n * `typeof x===\"string\"&&x.length>=3&&x.length<=20`). V8's load elimination\n * removes the repeats only while the access is monomorphic; on the polymorphic\n * and megamorphic call sites real payloads produce (an array of objects with\n * differing key order, anything out of `JSON.parse`) every repeat is a fresh\n * megamorphic lookup. Binding the value to a local once is worth 1.1-1.7x on\n * the whole object check when the optional key is present, and is neutral when\n * it is absent.\n *\n * Only hoisted when the input is a property access; a bare local (an array\n * element variable, a record value) is already a single load, so it keeps the\n * shorter form and byte-identical output.\n */\nexport function fastSentinelWrapper(\n g: FastGen,\n innerIR: SchemaIR,\n sentinel: string,\n joiner: \"&&\" | \"||\",\n): string | null {\n if (!isPropertyAccess(g.input)) {\n const inner = g.visit(innerIR);\n return inner === null ? null : `(${g.input}${sentinel}${joiner}(${inner}))`;\n }\n const value = g.local(\"w\");\n const inner = g.visit(innerIR, { input: value });\n if (inner === null) return null;\n return `((${value}=${g.input})${sentinel}${joiner}(${inner}))`;\n}\n\n/** True for an expression that performs a property load (`x[\"a\"]`, `x.a`, `x[0][1]`). */\nfunction isPropertyAccess(expr: string): boolean {\n return expr.includes(\"[\") || expr.includes(\".\");\n}\n\n/** Context object for fast-path (boolean expression) generator functions. */\nexport interface FastGen {\n readonly input: string;\n readonly ctx: CodeGenContext;\n\n /**\n * Whether the CURRENT node may be hoisted into its own boolean helper when it\n * (with the already-emitted siblings) would overflow the function size cap.\n * False for the root and for a helper's own top node — those are already their\n * own function — but their children are extractable. See generateFast.\n */\n readonly extractable: boolean;\n\n /** Accumulated size (≈ chars) of the function currently being assembled. */\n readonly scope: FastScope;\n\n /**\n * Set on the gen for a discriminated-union option only: the discriminator\n * key. Signals `fastObject` to omit its type-guard and skip re-checking that\n * property (the switch already matched its value). Never propagated to child\n * nodes — nested objects keep their own guard.\n */\n readonly discSkipKey?: string | undefined;\n\n /**\n * Recursively generate fast-check expression for a child IR node.\n * Returns null if any child is ineligible for fast path.\n */\n visit(ir: SchemaIR, overrides?: { input?: string; discSkipKey?: string }): string | null;\n\n /**\n * A FastGen for emitting a SEPARATE function body (a hand-built preamble\n * helper such as a discriminated-union switch or an array-element loop). It\n * carries a FRESH size accumulator, so the helper's own content is size-gated\n * against the cap independently of the caller — without this, a helper's body\n * accrues to the caller's scope while the helper itself grows unbounded.\n */\n scoped(input: string): FastGen;\n\n /** Generate a unique temp variable name. */\n temp(prefix: string): string;\n\n /**\n * Allocate a unique name AND record it on this scope so the enclosing\n * emitted function declares it as a `var` (see {@link FastScope.temps}).\n * Use for a value bound inside an expression — `(t=x[\"k\"])===undefined` —\n * where `temp()` alone would leave the name undeclared.\n */\n local(prefix: string): string;\n\n /** Add a regex to preamble and return the variable name. */\n regex(prefix: string, pattern: string, flags?: string): string;\n}\n\n/** Fast-path generator function signature — registered in fastRegistry. */\nexport type FastGenerator<T extends SchemaIR = SchemaIR> = (ir: T, g: FastGen) => string | null;\n\n// ─── Shared emit helpers (used by both slow-path and fast-path factories) ────\n\n/** Allocate a fresh `__${prefix}_${n}` identifier and bump the shared counter. */\nexport function emitTemp(ctx: CodeGenContext, prefix: string): string {\n return `__${prefix}_${ctx.counter++}`;\n}\n\n/**\n * Host a zero-capture effect function (refine predicate, transform,\n * overwrite) in the preamble and return its variable name. The inline\n * `(${source})(x)` form evaluates the function expression — allocating a\n * function object — on EVERY parse at every effect site, including inside\n * the \"zero-allocation\" fast chain. V8's escape analysis erases that in\n * optimized frames, but interpreter/baseline/deopt frames pay it, and the\n * full source text re-parses as bytecode at each site. Zero-capture sources\n * reference only their own parameters and safe globals by construction, so\n * a single preamble binding is semantically identical. Deduped per schema\n * by source text.\n */\nexport function emitEffectFn(ctx: CodeGenContext, source: string): string {\n ctx.effectFnCache ??= new Map();\n const cached = ctx.effectFnCache.get(source);\n if (cached !== undefined) return cached;\n const name = `__ef_${ctx.counter++}`;\n ctx.preamble.push(`var ${name}=(${source});`);\n ctx.effectFnCache.set(source, name);\n return name;\n}\n\n/**\n * Callable expression for a user callback — a refine predicate or a transform.\n *\n * A zero-capture callback is hosted from its source text; one that CAPTURES\n * outer variables is called by reference through `__rf[N]` — the user's own\n * function object, reached from the schema — instead of costing the schema its\n * compiled path. The reference is aliased into a preamble binding rather than\n * re-read per call, for the same reason call-invoked helpers are (a per-call\n * array element load is not a foldable callee).\n */\nexport function emitEffectCallable(\n ctx: CodeGenContext,\n effect: { refIndex?: number | undefined; source?: string | undefined },\n): string {\n if (effect.refIndex !== undefined) return emitConstant(ctx, \"rfn\", `__rf[${effect.refIndex}]`);\n if (effect.source === undefined) {\n throw new Error(\"effect has neither inlineable source nor a reference index\");\n }\n return emitEffectFn(ctx, effect.source);\n}\n\n/**\n * Pristine fallback delegate: declare `var __rfp_N=__rf[N].safeParse.bind(__rf[N]);`\n * in the preamble and return the variable name. Generated code must NEVER read\n * `__rf[N].safeParse` at parse time: `__zcMkv` installs the compiled safeParse as\n * an OWN property on the original schema object, and whenever `__rf[N]` is that\n * same object the read resolves to the compiled delegate itself — infinite\n * recursion (RangeError on every parse). The fallback entry and the __zcMkv\n * target ARE the same object in compile mode (schemaExpr is the compile()\n * argument identifier) and the CLI emitter ((__src_X as any).schema); in\n * autoDiscover mode they are two textually identical constructions that any\n * downstream CSE/dedup transform (babel-plugin-zod-hoist in a field incident)\n * collapses back into one. Capturing at IIFE evaluation — before the trailing\n * `return __zcMkv(...)` mutates anything — pins zod's own implementation; the\n * worst case under cross-validator merges is delegating to an equivalent\n * compiled validator (whose own delegates were captured even earlier), never\n * a cycle.\n */\nexport function emitRfDelegate(ctx: CodeGenContext, refIndex: number): string {\n const name = `__rfp_${refIndex}`;\n const decl = `var ${name}=__rf[${refIndex}].safeParse.bind(__rf[${refIndex}]);`;\n if (!ctx.preamble.includes(decl)) {\n ctx.preamble.push(decl);\n }\n return name;\n}\n\n/**\n * Resolve a regex pattern to a runtime variable name.\n * Lean mode short-circuits well-known patterns to virtual-module names so the\n * bundler can dedup across files; everything else is cached + declared in the\n * per-IIFE preamble exactly once per pattern.\n */\nexport function emitRegex(\n ctx: CodeGenContext,\n prefix: string,\n pattern: string,\n flags?: string,\n): string {\n if (ctx.mode === \"lean\" && !flags) {\n const wellKnown = lookupWellKnownRegex(pattern);\n if (wellKnown !== null) {\n ctx.usedHelpers.add(wellKnown);\n return wellKnown;\n }\n }\n const cacheKey = flags ? `${flags}\\u0000${pattern}` : pattern;\n const cached = ctx.regexCache.get(cacheKey);\n if (cached) return cached;\n const name = `__re_${prefix}_${ctx.counter++}`;\n const flagsArg = flags ? `,${escapeString(flags)}` : \"\";\n // Flag-less patterns may carry a faster behavior-equivalent rewrite (a\n // well-known table entry, repeat unrolling, or both); the regex OBJECT uses\n // it while issue sites keep reporting the original pattern (see slowString).\n const testSource = flags ? null : fastTestSource(pattern);\n ctx.preamble.push(`var ${name}=new RegExp(${escapeString(testSource ?? pattern)}${flagsArg});`);\n ctx.regexCache.set(cacheKey, name);\n return name;\n}\n\n/**\n * Resolve the ORIGINAL `/source/flags` pattern string of a regex for issue\n * reporting. Only needed when emitRegex swapped in a faster equivalent test\n * pattern (the runtime regex's toString() would leak the rewrite). Lean mode\n * references the shared `<name>Src` virtual export so the original pattern\n * stays a single bundle-wide string; inline mode declares it once per IIFE.\n */\nexport function emitRegexSourceString(ctx: CodeGenContext, pattern: string): string {\n if (ctx.mode === \"lean\") {\n const srcName = wellKnownRegexSourceName(pattern);\n if (srcName !== null) {\n ctx.usedHelpers.add(srcName);\n return srcName;\n }\n }\n const cacheKey = `src\\u0000${pattern}`;\n const cached = ctx.regexCache.get(cacheKey);\n if (cached) return cached;\n const name = `__res_${ctx.counter++}`;\n ctx.preamble.push(`var ${name}=${escapeString(`/${pattern}/`)};`);\n ctx.regexCache.set(cacheKey, name);\n return name;\n}\n\n/**\n * Declare a constant value in the preamble and return its variable name,\n * reusing an earlier declaration of the SAME initializer.\n *\n * Value tables are reached from both halves of a validator — an enum's `Set`\n * from its fast check and again from its slow walk, a strict shape's key table\n * likewise — and repeat across sibling properties that share a value list. One\n * declaration per USE emitted the payload two or four times: measured 17% of a\n * 20-value enum schema's generated bytes, 16% for an object with two identical\n * enums. Keyed by initializer text, so only identical payloads collapse.\n */\nexport function emitConstant(ctx: CodeGenContext, prefix: string, initializer: string): string {\n ctx.valueCache ??= new Map();\n const cached = ctx.valueCache.get(initializer);\n if (cached !== undefined) return cached;\n const name = `__${prefix}_${ctx.counter++}`;\n ctx.preamble.push(`var ${name}=${initializer};`);\n ctx.valueCache.set(initializer, name);\n return name;\n}\n\n/** Declare a `new Set([...])` in the preamble and return its variable name. */\nexport function emitSet(ctx: CodeGenContext, prefix: string, values: readonly unknown[]): string {\n return emitConstant(ctx, `set_${prefix}`, `new Set(${JSON.stringify([...values])})`);\n}\n\n/**\n * Shape-key count at or below which the unknown-key pass compares with an\n * inline `===` chain rather than a hashed lookup.\n *\n * This is deliberately NOT {@link ENUM_INLINE_THRESHOLD}: the two look alike but\n * are different workloads. An enum compares schema literals against arbitrary\n * INPUT strings, which may be long, share prefixes, and are not necessarily\n * internalized — so a hashed set earns its keep quickly. A shape-key test\n * compares them against keys arriving from `for-in`, i.e. the object's own\n * internalized key strings, so every arm of the chain is a pointer compare that\n * V8 predicts perfectly, while `table[k]` / `set.has(k)` pays a string hash and\n * probe per key.\n *\n * Measured over a strict object's for-in pass (JSON-parsed input, 8 rotated\n * shapes), `===` chain vs the previous `{k:1}` table: 3.7x at 6 keys, 3.8x at\n * 10, 3.1x at 20, 3.1x at 48 — the chain still leads at 64 (283 ns vs 690) and\n * only loses past ~96, where `Set.has` (not the table, which never wins at any\n * size) takes over. 64 sits below that crossover and above any realistic shape.\n */\nexport const KEY_MEMBERSHIP_INLINE_THRESHOLD = 64;\n\n/**\n * Boolean membership test for one key variable against a fixed key list.\n * Empty list recognizes nothing.\n *\n * `Set.has` is the large-shape fallback rather than a `{key:1}` object table:\n * the table is also `__proto__`-hostile (an own `__proto__` key cannot be set\n * by an object literal, so that key would silently read as unknown), which the\n * Set has no trouble with.\n */\nexport function keyMembershipTest(\n ctx: CodeGenContext,\n keys: readonly string[],\n keyVar: string,\n): string {\n if (keys.length === 0) return \"false\";\n if (keys.length <= KEY_MEMBERSHIP_INLINE_THRESHOLD) {\n return keys.map((k) => `${keyVar}===${escapeString(k)}`).join(\"||\");\n }\n return `${emitSet(ctx, \"ks\", keys)}.has(${keyVar})`;\n}\n\n/**\n * Enum values at or below this count use inline === checks instead of Set.has().\n * Measured on V8: for ≤5 values, an === chain beats Set.has by up to ~3x with\n * realistic (distinct-prefix, JSON-parsed) values — V8 internalizes strings on\n * successful comparison, making subsequent arms pointer-equality — and is no\n * worse than Set.has even with adversarial shared-prefix values.\n */\nexport const ENUM_INLINE_THRESHOLD = 5;\n\nconst CHECK_PRIORITY: Record<string, number> = {\n // Cheapest: length/size comparisons (O(1))\n min_length: 10,\n max_length: 11,\n length_equals: 12,\n min_size: 13,\n max_size: 14,\n // Number format checks (comparison + bitwise)\n number_format: 15,\n // Range comparisons\n greater_than: 20,\n less_than: 21,\n bigint_greater_than: 20,\n bigint_less_than: 21,\n date_greater_than: 22,\n date_less_than: 23,\n // Modulo\n multiple_of: 30,\n bigint_multiple_of: 30,\n // String prefix/suffix (O(prefix/suffix length))\n starts_with: 40,\n ends_with: 41,\n // String search (O(n·m) worst case)\n includes: 42,\n // Regex (most expensive)\n string_format: 50,\n};\n\nexport function escapeString(s: string | number): string {\n return JSON.stringify(s);\n}\n\n/** The {@link LiteralValue}s that {@link literalToJs} can spell. */\nexport type SourceFormLiteral = string | number | boolean | null | bigint | undefined;\n\n/**\n * Can {@link literalToJs} render this value as JS source that strict-equals it?\n *\n * Total by construction — it NAMES the value kinds that have a source form\n * rather than excluding the ones that don't, so every reference value falls out\n * on the false side. That matters because `literalToJs` used to end in a bare\n * `JSON.stringify`, which does not fail loudly on the values it cannot spell:\n * for a symbol it RETURNS `undefined` (the value, not a string), so\n * `z.literal(sym)` compiled to the comparison `x===undefined` — rejecting the\n * symbol it was built from and accepting `undefined`. An object is mis-rendered\n * the other way: `{}` stringifies to `\"{}\"`, and `x==={}` is never true, so the\n * very object the schema was built from was rejected. Both take the runtime\n * membership path instead (see the literal generator).\n */\nexport function hasSourceForm(v: LiteralValue): v is SourceFormLiteral {\n if (v === null) return true;\n const t = typeof v;\n return t === \"string\" || t === \"number\" || t === \"boolean\" || t === \"bigint\" || t === \"undefined\";\n}\n\n/**\n * JS source for a primitive literal value (literal schemas, discriminator\n * case labels). JSON.stringify covers string/number/boolean/null; bigint\n * needs the `n` suffix (JSON.stringify throws and String(5n) renders a\n * number literal that never strict-equals a bigint); undefined isn't JSON.\n *\n * The parameter type is deliberately NARROWER than {@link LiteralValue}: every\n * caller must first prove its value is spellable with {@link hasSourceForm}.\n */\nexport function literalToJs(v: SourceFormLiteral): string {\n if (typeof v === \"bigint\") return `${v}n`;\n if (v === undefined) return \"undefined\";\n // JSON.stringify maps NaN/±Infinity to \"null\"; emit them as JS expressions so a\n // non-finite numeric literal round-trips (z.literal(Infinity) must compare\n // against Infinity, not null). String(NaN)=\"NaN\", String(Infinity)=\"Infinity\",\n // String(-Infinity)=\"-Infinity\" — all valid JS that evaluate to the value.\n if (typeof v === \"number\" && !Number.isFinite(v)) return String(v);\n return JSON.stringify(v);\n}\n\n/**\n * Helpers that generated code invokes through `Function.prototype.call`, and\n * which therefore must be aliased into a module-local binding in lean mode.\n *\n * V8 folds a local `const` callee into a constant and inlines straight through\n * `x.call(...)`; an IMPORTED binding is a cell it will not fold, so the same\n * expression stays a generic property load plus a generic call — measured 4.5x\n * (5 keys) to 6.5x (20 keys) slower on the record fast path, 35.9 ns vs 7.2 ns\n * for a 5-key record. Aliasing the import into the IIFE recovers all of it\n * (7.4 ns). A DIRECT call to an imported function (`__zcFsr(v,s)`) is not\n * penalized — measured identical — and neither is an imported RegExp receiver,\n * so only the `.call` sites are listed here.\n */\nconst CALL_INVOKED_HELPERS: ReadonlySet<string> = new Set([\"__zcHop\"]);\n\n/**\n * Reference a shared runtime helper (e.g. __zcFsr) from generated code.\n * Lean mode: registers it for the `virtual:zod-compiler/runtime` import.\n * Inline mode: declares it once in the per-IIFE preamble.\n */\nexport function emitRuntimeHelper(ctx: CodeGenContext, name: string, decl: string): string {\n if (ctx.mode === \"lean\") {\n ctx.usedHelpers.add(name);\n if (CALL_INVOKED_HELPERS.has(name)) return emitConstant(ctx, \"lh\", name);\n } else if (!ctx.preamble.includes(decl)) {\n ctx.preamble.push(decl);\n }\n return name;\n}\n\n/**\n * Extend a path expression with one or more scalar segment expressions\n * (escaped string literals, numeric literals, or loop-variable names).\n *\n * Path expressions are only ever composed by these helpers starting from the\n * `[]` root, so any path that looks like an array literal IS one — the new\n * segment is spliced in to keep issue paths a single array allocation\n * (`[\"data\",\"items\",__i_7]`) instead of an allocation per nesting level\n * (`[\"data\"].concat(\"items\").concat(__i_7)`). Opaque expressions fall back\n * to .concat().\n */\nexport function extendPath(parentPath: string, segExpr: string): string {\n if (parentPath === \"[]\") return `[${segExpr}]`;\n if (parentPath.startsWith(\"[\") && parentPath.endsWith(\"]\")) {\n return `${parentPath.slice(0, -1)},${segExpr}]`;\n }\n return `${parentPath}.concat(${segExpr})`;\n}\n\n/** Extend a path expression with a static string key. */\nexport function extendStaticPath(parentPath: string, key: string): string {\n return extendPath(parentPath, escapeString(key));\n}\n\n/** Extend a path expression with a numeric index. */\nexport function extendStaticPathIndex(parentPath: string, index: number): string {\n return extendPath(parentPath, String(index));\n}\n\n/**\n * A superRefine callback receives zod's payload, whose `value` is public,\n * typed, writable API ($RefinementCtx extends ParsePayload) — so any node\n * carrying one MAY rewrite its value and must be treated as mutating. Which\n * callbacks actually do is undecidable here; the emitted fast check settles it\n * at runtime by refusing when the value changed (see ZC_SR_OK_DECL), so a\n * non-mutating callback still exits through the fast path.\n */\nfunction hasSuperRefine(checks: readonly { kind: string }[] | undefined): boolean {\n return checks !== undefined && checks.some((c) => c.kind === \"super_refine_effect\");\n}\n\n/**\n * Check if a SchemaIR tree produces output that is not the input itself —\n * either value-mutating operations (coerce, default, catch, overwrite) that\n * write back to the input expression, or a strip object that rebuilds a fresh\n * object from its known keys. Used by container generators to decide whether to\n * clone (so the rebuilt/mutated value never writes through to the caller's\n * input), by generateValidator to keep such schemas off the by-reference fast\n * path, and by the shared-walk dedup + intersection extractor to exclude them.\n */\n/**\n * Can this tuple's output be LONGER than its input?\n *\n * `handleTupleResult` assigns `final.value[i] = result.value` for every item it\n * runs, and $ZodTuple runs every item below `optStart` even when the input is\n * shorter — so a required slot past the end is written with the `undefined` its\n * schema returned, extending the array. `z.tuple([z.any(), z.any()])` therefore\n * answers `[\"x\"]` with `[\"x\", undefined]`, length 2. A required item that\n * REJECTS undefined can't produce that: the parse fails and the value is never\n * read. So the extension is possible exactly when some required item accepts\n * `undefined` — which also makes the tuple a mutating node, since its output is\n * then not its input.\n */\nexport function tuplePadsShortInput(ir: SchemaIR & { type: \"tuple\" }): boolean {\n return ir.items.some((item, index) => index < ir.optStart && !rejectsUndefined(item));\n}\n\nexport function hasMutation(ir: SchemaIR): boolean {\n switch (ir.type) {\n case \"string\":\n // url checks trim (and optionally normalize) the value; overwrite\n // effects (.trim(), .toLowerCase()) rewrite it.\n return (\n ir.coerce === true ||\n hasSuperRefine(ir.checks) ||\n ir.checks.some(\n (c) =>\n c.kind === \"overwrite_effect\" || (c.kind === \"string_format\" && c.format === \"url\"),\n )\n );\n case \"number\":\n return ir.coerce === true || hasSuperRefine(ir.checks);\n case \"boolean\":\n case \"bigint\":\n case \"date\":\n return ir.coerce === true;\n case \"default\":\n case \"catch\":\n case \"effect\":\n case \"fallback\":\n case \"stringBool\":\n return true;\n case \"object\":\n // A strip object produces a FRESH output (only the declared keys), so it\n // mutates: parents must clone before it writes back, it never takes the\n // by-reference fast path, and intersections of strip objects delegate to\n // zod (see extractIntersection's hasMutation guard) — matching zod's\n // parse-both-sides-then-merge semantics instead of over-stripping.\n return (\n ir.stripUnknownKeys === true ||\n hasSuperRefine(ir.checks) ||\n (ir.catchall !== undefined && hasMutation(ir.catchall)) ||\n Object.values(ir.properties).some((p) => hasMutation(p))\n );\n case \"array\":\n return hasSuperRefine(ir.checks) || hasMutation(ir.element);\n case \"tuple\":\n return (\n ir.items.some(hasMutation) ||\n (ir.rest !== null && hasMutation(ir.rest)) ||\n tuplePadsShortInput(ir)\n );\n case \"record\":\n return hasMutation(ir.valueType);\n // A freezing readonly produces a value that is not its input, exactly as a\n // strip object does — so it must never take a by-reference shortcut.\n case \"readonly\":\n return ir.freeze === true || hasMutation(ir.inner);\n case \"optional\":\n case \"nullable\":\n case \"recursionTarget\":\n case \"zodDelegate\":\n return hasMutation(ir.inner);\n case \"union\":\n case \"discriminatedUnion\":\n return ir.options.some(hasMutation);\n case \"intersection\":\n return hasMutation(ir.left) || hasMutation(ir.right);\n case \"pipe\":\n return hasMutation(ir.in) || hasMutation(ir.out);\n case \"set\":\n return hasMutation(ir.valueType);\n case \"map\":\n return hasMutation(ir.keyType) || hasMutation(ir.valueType);\n case \"file\":\n return false;\n default:\n return false;\n }\n}\n\n/**\n * Is a defaulted property's key guaranteed to appear in the stripped output?\n *\n * Distinct from {@link rejectsUndefined}, which asks whether `undefined` is\n * REJECTED — a `.default()` accepts it and yet still produces a defined value, so\n * only this question earns the key a slot in the output object literal. The two\n * answers coincide everywhere else.\n *\n * Sound for both branches of a default: the substituted value is defined\n * (`alwaysDefined`, checked against the schema at extraction time), and the inner\n * branch runs only when `input[key] !== undefined`, which implies `key in input`\n * — so zod's presence test keeps the key whatever the inner produced.\n */\nexport function outputAlwaysDefined(ir: SchemaIR): boolean {\n return ir.type === \"default\" ? ir.alwaysDefined === true : rejectsUndefined(ir);\n}\n\n/**\n * Does this schema reject `undefined` outright?\n *\n * Read as \"can this slot be ABSENT from the input\" by the tuple build, whose\n * output length depends on it — zod marks a defaulted or optional item\n * `optin: \"optional\"` and accepts a shorter array. Conservative: anything that\n * might accept, produce, or default to `undefined` answers false.\n */\nexport function rejectsUndefined(ir: SchemaIR): boolean {\n switch (ir.type) {\n // Coercion turns undefined into a value (`String(undefined)`), so a\n // coercing primitive is NOT a rejector.\n case \"string\":\n case \"number\":\n case \"boolean\":\n case \"bigint\":\n case \"date\":\n return ir.coerce !== true;\n case \"symbol\":\n case \"null\":\n case \"nan\":\n case \"never\":\n case \"enum\":\n case \"object\":\n case \"array\":\n case \"tuple\":\n case \"record\":\n case \"set\":\n case \"map\":\n case \"file\":\n case \"templateLiteral\":\n case \"discriminatedUnion\":\n case \"stringBool\":\n return true;\n case \"literal\":\n return !ir.values.includes(undefined);\n case \"union\":\n return ir.options.every(rejectsUndefined);\n case \"intersection\":\n return rejectsUndefined(ir.left) || rejectsUndefined(ir.right);\n case \"nullable\":\n case \"readonly\":\n case \"recursionTarget\":\n case \"zodDelegate\":\n return rejectsUndefined(ir.inner);\n default:\n // optional / any / unknown / undefined / void / default / catch /\n // fallback / effect / pipe / recursiveRef — each can yield undefined,\n // or is opaque enough that we must not assume otherwise.\n return false;\n }\n}\n\n/**\n * Sort comparator for CheckIR: cheapest/most-discriminating checks first.\n * Used by fast-path generators after filtering out refine_effect entries.\n */\nexport function checkPriority(\n a: CheckIR | BigIntCheckIR | DateCheckIR | SetCheckIR,\n b: CheckIR | BigIntCheckIR | DateCheckIR | SetCheckIR,\n): number {\n return (CHECK_PRIORITY[a.kind] ?? 99) - (CHECK_PRIORITY[b.kind] ?? 99);\n}\n"],"mappings":";;;AAuOA,SAAgB,iBAAiB,OAA0B;CACzD,OAAO,MAAM,MAAM,SAAS,IAAI,OAAO,MAAM,MAAM,KAAK,GAAG,EAAE,KAAK;AACpE;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,oBACd,GACA,SACA,UACA,QACe;CACf,IAAI,CAAC,iBAAiB,EAAE,KAAK,GAAG;EAC9B,MAAM,QAAQ,EAAE,MAAM,OAAO;EAC7B,OAAO,UAAU,OAAO,OAAO,IAAI,EAAE,QAAQ,WAAW,OAAO,GAAG,MAAM;CAC1E;CACA,MAAM,QAAQ,EAAE,MAAM,GAAG;CACzB,MAAM,QAAQ,EAAE,MAAM,SAAS,EAAE,OAAO,MAAM,CAAC;CAC/C,IAAI,UAAU,MAAM,OAAO;CAC3B,OAAO,KAAK,MAAM,GAAG,EAAE,MAAM,GAAG,WAAW,OAAO,GAAG,MAAM;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AK;EACL,KAAK;EACL,KAAK;EACL,KAAK,cACH,OAAO;EACT,KAAK,WACH,OAAO,CAAC,GAAG,OAAO,SAAS,KAAA,CAAS;EACtC,KAAK,SACH,OAAO,GAAG,QAAQ,MAAM,gBAAgB;EAC1C,KAAK,gBACH,OAAO,iBAAiB,GAAG,IAAI,KAAK,iBAAiB,GAAG,KAAK;EAC/D,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,eACH,OAAO,iBAAiB,GAAG,KAAK;EAClC,SAIE,OAAO;CACX;AACF;;;;;AAMA,SAAgB,cACd,GACA,GACQ;CACR,QAAQ,eAAe,EAAE,SAAS,OAAO,eAAe,EAAE,SAAS;AACrE"}
1
+ {"version":3,"file":"context.js","names":[],"sources":["../../../src/core/codegen/context.ts"],"sourcesContent":["import type {\n BigIntCheckIR,\n CheckIR,\n DateCheckIR,\n LiteralValue,\n SchemaIR,\n SetCheckIR,\n} from \"../types.js\";\nimport type { SharedSchemaPlan } from \"./dedupe.js\";\nimport {\n fastTestSource,\n lookupWellKnownRegex,\n wellKnownRegexSourceName,\n} from \"./well-known-regex.js\";\n\n/** Codegen output mode. \"inline\" emits self-contained code (CLI .compiled.ts). \"lean\" emits references to imports from \"virtual:zod-compiler/runtime\" (unplugin). */\nexport type CodegenMode = \"inline\" | \"lean\";\n\n/** A Set declaration emitted while generating one validator. */\nexport interface GeneratedSetConstant {\n readonly name: string;\n readonly initializer: string;\n}\n\nexport interface CodeGenResult {\n code: string;\n functionDef: string;\n /** Number of fallback schemas referenced by __rf[N] in the generated code. 0 = no fallbacks. */\n refCount: number;\n /**\n * Helper names referenced by this schema in lean mode (e.g. \"__zcTS\", \"__zcReEmail\").\n * Used by the unplugin transform to construct the `import { ... } from \"virtual:zod-compiler/runtime\"` line.\n * Always empty in inline mode.\n */\n usedHelpers: Set<string>;\n /**\n * Name of the hosted fast-check boolean function in the preamble (null when\n * the schema has no Fast Path). generateIIFE passes it to __zcMkv so parse()\n * and parseAsync() can return valid input without allocating an\n * intermediate SafeParseResult.\n */\n fastFnName: string | null;\n /**\n * True when `fastFnName` is a TOTAL predicate: `fc(input) === true` iff the\n * schema accepts `input` (mutation-free schemas, where a fast-check failure\n * can never become a slow-path success). generateIIFE installs it as the\n * zero-allocation `.is()` guard. False for partial fast paths\n * (default/catch — `fc` only shortcuts present-and-valid input, so a `false`\n * result does NOT imply rejection) and for schemas with no fast path, such as\n * coercion; `.is()` then derives from `safeParse(input).success`.\n */\n fastTotal: boolean;\n /**\n * Hosted predicate installed as `.is()`, when it differs from `fastFnName`.\n * A schema that rebuilds its output has no by-reference shortcut (so\n * `fastFnName` is null) yet still has an exact acceptance predicate, because\n * stripping reshapes the payload and never the verdict.\n */\n isFnName?: string | null;\n /**\n * Compact mode only: the `__rf[N]` index this validator delegates its cold\n * error path to (the schema itself, captured as a fresh root RefEntry). When\n * set, the pipeline appends a `{ schema, accessPath: \"\" }` entry at this index\n * so `generateIIFE` materializes `__rf[N]` as the original Zod schema. Absent\n * for every non-compact (fully compiled) validator.\n */\n rootDelegateRefIndex?: number;\n}\n\n/** Hosted-validator names for one recursion target (see CodeGenContext.recTargets). */\nexport interface RecTargetGen {\n /** True for the root target (refId 0) — reuses the schema's own functions. */\n isRoot: boolean;\n /**\n * safeParse-shaped slow validator name: `safeParse_<name>` for the root,\n * `__rsp_N` for a non-root target. `slowRecursiveRef` calls this.\n */\n slowName: string;\n /**\n * Boolean fast-check name (`__fcr_N`). Allocated lazily for the root (mirrors\n * recFastName), eagerly for non-root targets. Absent until the fast path\n * reaches a ref to this target.\n */\n fastName?: string;\n /** Inner IR hosted as the standalone validator body (non-root targets only). */\n inner?: SchemaIR;\n}\n\n/** Shared mutable state for code generation. Fast and slow paths share the same instance. */\nexport interface CodeGenContext {\n preamble: string[];\n counter: number;\n fnName: string;\n /** Deduplicates regex patterns: same pattern string → same preamble variable name. */\n regexCache: Map<string, string>;\n /** Codegen output mode. */\n mode: CodegenMode;\n /** Names of helpers from \"virtual:zod-compiler/runtime\" referenced in this schema (lean mode only). */\n usedHelpers: Set<string>;\n /**\n * Name of the fast-path boolean helper for the ROOT recursion target\n * (refId 0), allocated on first fastRecursiveRef visit. generateValidator\n * wraps the root fast expression as `function <name>(input){return <expr>;}`\n * so recursive refs can call it. undefined = root has no recursion on the\n * fast path.\n */\n recFastName?: string;\n /**\n * Hosted-validator name table for recursion targets, keyed by refId. Entry 0\n * is the root (the schema's own `safeParse_<name>` / `recFastName`); entries\n * ≥ 1 are non-root targets hosted as standalone `__rsp_N` (slow) / `__fcr_N`\n * (fast) helpers. `recursiveRef`/`recursionTarget` generators look up the\n * call target here. Undefined when not generating a full validator (e.g. unit\n * tests calling a single generator) — treated as root-only.\n */\n recTargets?: Map<number, RecTargetGen>;\n /** Dedup cache for hosted zero-capture effect functions: source text → preamble var. */\n effectFnCache?: Map<string, string>;\n /** Dedup cache for constant preamble declarations: initializer text → preamble var. */\n valueCache?: Map<string, string>;\n /** Reports generated Sets so the file pipeline can share exact duplicates across validators. */\n onSetConstant?: ((constant: GeneratedSetConstant) => void) | undefined;\n /** Exact Set initializer → file-level name, populated by the pipeline's second codegen pass. */\n sharedSetNames?: ReadonlyMap<string, string> | undefined;\n /** Name of the build path's FAIL sentinel, declared once per validator. */\n buildFailName?: string;\n /** Hosted build-function name per recursion target refId, so back-edges resolve. */\n buildRecNames?: Map<number, string>;\n /**\n * Set by the build path when it emitted a `.default()` substitution. Such a\n * schema ACCEPTS an input its fast expression rejects — `fastDefault` demands a\n * present value, since the fast path's contract is `data === input` and a\n * substituted default is not the input — so the expression is no longer an\n * exact acceptance predicate and must not be installed as `.is()`. Stripping,\n * by contrast, reshapes only the payload, which is why a build-path schema\n * otherwise still hands its predicate over.\n */\n buildSubstitutesValue?: boolean;\n /** Memo for estimateFastCost (size-gated fast-check extraction). Lazily created. */\n fastSizeCache?: WeakMap<SchemaIR, number>;\n /** Memo for estimateRuntimeCost (cheapest-first check ordering). Lazily created. */\n fastRuntimeCostCache?: WeakMap<SchemaIR, number>;\n /**\n * File-level shared slow-walk plan. Set only when generating a mutation-free\n * schema (so shared walks stay on the deferred cold path); the slow-path\n * visit() consults it to replace a repeated sub-IR with a `__zcSw_N` call.\n */\n sharedSchemas?: SharedSchemaPlan;\n}\n\n// ─── Slow Path context ────────────────────────────────────────────────────────\n\n/** Context object for slow-path (error-collecting) generator functions. */\nexport interface SlowGen {\n readonly input: string;\n readonly output: string;\n readonly path: string;\n readonly issues: string;\n readonly ctx: CodeGenContext;\n /**\n * Schema-level static error message of the node being generated\n * (z.string({ error: \"...\" })). Default message for issues this node emits\n * when the individual check has no message of its own. Set by generateSlow()\n * from ir.typeMessage; never inherited by child nodes.\n */\n readonly typeMsg?: string | undefined;\n\n /**\n * Name of a boolean variable that this node sets to `true` when it aborts in\n * the zod sense (`payload.aborted`) — currently only a pipe/codec whose `in`\n * step fails (zod's `handlePipeResult` sets `left.aborted = true`). A `union`\n * allocates one per option and reads it during pruning so a pipe option whose\n * `in` failed counts as aborted even when its only issue is a non-aborting\n * `custom`/check-level code. Undefined when the node is not inside an\n * abort-tracking option, in which case the abort is a no-op.\n *\n * Unlike input/output/path/issues, this is NOT inherited by `visit()`: it is\n * cleared at every boundary unless a node explicitly forwards it (the\n * pass-through wrappers optional/nullable/readonly do), mirroring how zod\n * propagates `payload.aborted` through transparent wrappers but not across\n * container boundaries.\n */\n readonly aborted?: string | undefined;\n\n /**\n * Recursively generate validation for a child IR node.\n * input/output/path/issues are inherited from parent unless overridden;\n * `aborted` is the exception — it is only set when explicitly passed (see the\n * `aborted` field doc), so it never leaks into container children.\n * Union generators use `{ issues }` to redirect child errors to temporary arrays.\n * Container generators use `{ input, output, path }` for element traversal.\n */\n visit(\n ir: SchemaIR,\n overrides?: {\n input?: string;\n output?: string;\n path?: string;\n issues?: string;\n // `| undefined` (unlike the others): pass-through wrappers forward\n // `g.aborted` verbatim, which is undefined outside an abort-tracking option.\n aborted?: string | undefined;\n },\n ): string;\n\n /** Generate a unique temp variable name: `__${prefix}_${counter++}` */\n temp(prefix: string): string;\n\n /** Add a regex to preamble and return the variable name. */\n regex(prefix: string, pattern: string, flags?: string): string;\n\n /** Add a Set to preamble and return the variable name. */\n set(prefix: string, values: readonly unknown[]): string;\n}\n\n/** Slow-path generator function signature — registered in slowRegistry. */\nexport type SlowGenerator<T extends SchemaIR = SchemaIR> = (ir: T, g: SlowGen) => string;\n\n// ─── Fast Path context ────────────────────────────────────────────────────────\n\n/**\n * Per-emitted-function size accumulator for size-gated fast-check extraction.\n * Shared by every node inlined into the same function; a fresh instance starts\n * each hosted helper (and the root). See fast-size.ts / generateFast.\n */\nexport interface FastScope {\n used: number;\n /**\n * `var` temps that the function this scope is assembling must declare, in\n * allocation order. Populated by {@link FastGen.local}; every site that\n * materializes a function body from a fresh scope emits\n * {@link declareFastTemps} at the top of that body.\n *\n * Function-scoped (never module-scoped) is load-bearing: a recursive\n * validator re-enters itself while an outer frame still holds a live temp,\n * and each invocation needs its own binding.\n */\n temps: string[];\n}\n\n/** `var a,b;` declaration for a scope's temps, or \"\" when it allocated none. */\nexport function declareFastTemps(scope: FastScope): string {\n return scope.temps.length > 0 ? `var ${scope.temps.join(\",\")};` : \"\";\n}\n\n/**\n * Fast check for a wrapper that compares its input against a sentinel and\n * otherwise delegates to an inner schema — `optional` (`===undefined`),\n * `nullable` (`===null`) and `default` (`!==undefined`).\n *\n * Written naively these read the input TWICE: once for the sentinel test and\n * again inside the inner check (which may itself read it several more times —\n * `typeof x===\"string\"&&x.length>=3&&x.length<=20`). V8's load elimination\n * removes the repeats only while the access is monomorphic; on the polymorphic\n * and megamorphic call sites real payloads produce (an array of objects with\n * differing key order, anything out of `JSON.parse`) every repeat is a fresh\n * megamorphic lookup. Binding the value to a local once is worth 1.1-1.7x on\n * the whole object check when the optional key is present, and is neutral when\n * it is absent.\n *\n * Only hoisted when the input is a property access; a bare local (an array\n * element variable, a record value) is already a single load, so it keeps the\n * shorter form and byte-identical output.\n */\nexport function fastSentinelWrapper(\n g: FastGen,\n innerIR: SchemaIR,\n sentinel: string,\n joiner: \"&&\" | \"||\",\n): string | null {\n if (!isPropertyAccess(g.input)) {\n const inner = g.visit(innerIR);\n return inner === null ? null : `(${g.input}${sentinel}${joiner}(${inner}))`;\n }\n const value = g.local(\"w\");\n const inner = g.visit(innerIR, { input: value });\n if (inner === null) return null;\n return `((${value}=${g.input})${sentinel}${joiner}(${inner}))`;\n}\n\n/** True for an expression that performs a property load (`x[\"a\"]`, `x.a`, `x[0][1]`). */\nfunction isPropertyAccess(expr: string): boolean {\n return expr.includes(\"[\") || expr.includes(\".\");\n}\n\n/** Context object for fast-path (boolean expression) generator functions. */\nexport interface FastGen {\n readonly input: string;\n readonly ctx: CodeGenContext;\n\n /**\n * Whether the CURRENT node may be hoisted into its own boolean helper when it\n * (with the already-emitted siblings) would overflow the function size cap.\n * False for the root and for a helper's own top node — those are already their\n * own function — but their children are extractable. See generateFast.\n */\n readonly extractable: boolean;\n\n /** Accumulated size (≈ chars) of the function currently being assembled. */\n readonly scope: FastScope;\n\n /**\n * Set on the gen for a discriminated-union option only: the discriminator\n * key. Signals `fastObject` to omit its type-guard and skip re-checking that\n * property (the switch already matched its value). Never propagated to child\n * nodes — nested objects keep their own guard.\n */\n readonly discSkipKey?: string | undefined;\n\n /**\n * Recursively generate fast-check expression for a child IR node.\n * Returns null if any child is ineligible for fast path.\n */\n visit(ir: SchemaIR, overrides?: { input?: string; discSkipKey?: string }): string | null;\n\n /**\n * A FastGen for emitting a SEPARATE function body (a hand-built preamble\n * helper such as a discriminated-union switch or an array-element loop). It\n * carries a FRESH size accumulator, so the helper's own content is size-gated\n * against the cap independently of the caller — without this, a helper's body\n * accrues to the caller's scope while the helper itself grows unbounded.\n */\n scoped(input: string): FastGen;\n\n /** Generate a unique temp variable name. */\n temp(prefix: string): string;\n\n /**\n * Allocate a unique name AND record it on this scope so the enclosing\n * emitted function declares it as a `var` (see {@link FastScope.temps}).\n * Use for a value bound inside an expression — `(t=x[\"k\"])===undefined` —\n * where `temp()` alone would leave the name undeclared.\n */\n local(prefix: string): string;\n\n /** Add a regex to preamble and return the variable name. */\n regex(prefix: string, pattern: string, flags?: string): string;\n}\n\n/** Fast-path generator function signature — registered in fastRegistry. */\nexport type FastGenerator<T extends SchemaIR = SchemaIR> = (ir: T, g: FastGen) => string | null;\n\n// ─── Shared emit helpers (used by both slow-path and fast-path factories) ────\n\n/** Allocate a fresh `__${prefix}_${n}` identifier and bump the shared counter. */\nexport function emitTemp(ctx: CodeGenContext, prefix: string): string {\n return `__${prefix}_${ctx.counter++}`;\n}\n\n/**\n * Host a zero-capture effect function (refine predicate, transform,\n * overwrite) in the preamble and return its variable name. The inline\n * `(${source})(x)` form evaluates the function expression — allocating a\n * function object — on EVERY parse at every effect site, including inside\n * the \"zero-allocation\" fast chain. V8's escape analysis erases that in\n * optimized frames, but interpreter/baseline/deopt frames pay it, and the\n * full source text re-parses as bytecode at each site. Zero-capture sources\n * reference only their own parameters and safe globals by construction, so\n * a single preamble binding is semantically identical. Deduped per schema\n * by source text.\n */\nexport function emitEffectFn(ctx: CodeGenContext, source: string): string {\n ctx.effectFnCache ??= new Map();\n const cached = ctx.effectFnCache.get(source);\n if (cached !== undefined) return cached;\n const name = `__ef_${ctx.counter++}`;\n ctx.preamble.push(`var ${name}=(${source});`);\n ctx.effectFnCache.set(source, name);\n return name;\n}\n\n/**\n * Callable expression for a user callback — a refine predicate or a transform.\n *\n * A zero-capture callback is hosted from its source text; one that CAPTURES\n * outer variables is called by reference through `__rf[N]` — the user's own\n * function object, reached from the schema — instead of costing the schema its\n * compiled path. The reference is aliased into a preamble binding rather than\n * re-read per call, for the same reason call-invoked helpers are (a per-call\n * array element load is not a foldable callee).\n */\nexport function emitEffectCallable(\n ctx: CodeGenContext,\n effect: { refIndex?: number | undefined; source?: string | undefined },\n): string {\n if (effect.refIndex !== undefined) return emitConstant(ctx, \"rfn\", `__rf[${effect.refIndex}]`);\n if (effect.source === undefined) {\n throw new Error(\"effect has neither inlineable source nor a reference index\");\n }\n return emitEffectFn(ctx, effect.source);\n}\n\n/**\n * Pristine fallback delegate: declare `var __rfp_N=__rf[N].safeParse.bind(__rf[N]);`\n * in the preamble and return the variable name. Generated code must NEVER read\n * `__rf[N].safeParse` at parse time: `__zcMkv` installs the compiled safeParse as\n * an OWN property on the original schema object, and whenever `__rf[N]` is that\n * same object the read resolves to the compiled delegate itself — infinite\n * recursion (RangeError on every parse). The fallback entry and the __zcMkv\n * target ARE the same object in compile mode (schemaExpr is the compile()\n * argument identifier) and the CLI emitter ((__src_X as any).schema); in\n * autoDiscover mode they are two textually identical constructions that any\n * downstream CSE/dedup transform (babel-plugin-zod-hoist in a field incident)\n * collapses back into one. Capturing at IIFE evaluation — before the trailing\n * `return __zcMkv(...)` mutates anything — pins zod's own implementation; the\n * worst case under cross-validator merges is delegating to an equivalent\n * compiled validator (whose own delegates were captured even earlier), never\n * a cycle.\n */\nexport function emitRfDelegate(ctx: CodeGenContext, refIndex: number): string {\n const name = `__rfp_${refIndex}`;\n const decl = `var ${name}=__rf[${refIndex}].safeParse.bind(__rf[${refIndex}]);`;\n if (!ctx.preamble.includes(decl)) {\n ctx.preamble.push(decl);\n }\n return name;\n}\n\n/** Capture a pristine Zod method without allocating a bound function. */\nexport function emitRfMethod(ctx: CodeGenContext, refIndex: number): string {\n const name = `__rfm_${refIndex}`;\n const decl = `var ${name}=__rf[${refIndex}].safeParse;`;\n if (!ctx.preamble.includes(decl)) {\n ctx.preamble.push(decl);\n }\n return name;\n}\n\n/**\n * Resolve a regex pattern to a runtime variable name.\n * Lean mode short-circuits well-known patterns to virtual-module names so the\n * bundler can dedup across files; everything else is cached + declared in the\n * per-IIFE preamble exactly once per pattern.\n */\nexport function emitRegex(\n ctx: CodeGenContext,\n prefix: string,\n pattern: string,\n flags?: string,\n): string {\n if (ctx.mode === \"lean\" && !flags) {\n const wellKnown = lookupWellKnownRegex(pattern);\n if (wellKnown !== null) {\n ctx.usedHelpers.add(wellKnown);\n return wellKnown;\n }\n }\n const cacheKey = flags ? `${flags}\\u0000${pattern}` : pattern;\n const cached = ctx.regexCache.get(cacheKey);\n if (cached) return cached;\n const name = `__re_${prefix}_${ctx.counter++}`;\n const flagsArg = flags ? `,${escapeString(flags)}` : \"\";\n // Flag-less patterns may carry a faster behavior-equivalent rewrite (a\n // well-known table entry, repeat unrolling, or both); the regex OBJECT uses\n // it while issue sites keep reporting the original pattern (see slowString).\n const testSource = flags ? null : fastTestSource(pattern);\n ctx.preamble.push(`var ${name}=new RegExp(${escapeString(testSource ?? pattern)}${flagsArg});`);\n ctx.regexCache.set(cacheKey, name);\n return name;\n}\n\n/**\n * Resolve the ORIGINAL `/source/flags` pattern string of a regex for issue\n * reporting. Only needed when emitRegex swapped in a faster equivalent test\n * pattern (the runtime regex's toString() would leak the rewrite). Lean mode\n * references the shared `<name>Src` virtual export so the original pattern\n * stays a single bundle-wide string; inline mode declares it once per IIFE.\n */\nexport function emitRegexSourceString(ctx: CodeGenContext, pattern: string): string {\n if (ctx.mode === \"lean\") {\n const srcName = wellKnownRegexSourceName(pattern);\n if (srcName !== null) {\n ctx.usedHelpers.add(srcName);\n return srcName;\n }\n }\n const cacheKey = `src\\u0000${pattern}`;\n const cached = ctx.regexCache.get(cacheKey);\n if (cached) return cached;\n const name = `__res_${ctx.counter++}`;\n ctx.preamble.push(`var ${name}=${escapeString(`/${pattern}/`)};`);\n ctx.regexCache.set(cacheKey, name);\n return name;\n}\n\n/**\n * Declare a constant value in the preamble and return its variable name,\n * reusing an earlier declaration of the SAME initializer.\n *\n * Value tables are reached from both halves of a validator — an enum's `Set`\n * from its fast check and again from its slow walk, a strict shape's key table\n * likewise — and repeat across sibling properties that share a value list. One\n * declaration per USE emitted the payload two or four times: measured 17% of a\n * 20-value enum schema's generated bytes, 16% for an object with two identical\n * enums. Keyed by initializer text, so only identical payloads collapse.\n */\nexport function emitConstant(ctx: CodeGenContext, prefix: string, initializer: string): string {\n ctx.valueCache ??= new Map();\n const cached = ctx.valueCache.get(initializer);\n if (cached !== undefined) return cached;\n const name = `__${prefix}_${ctx.counter++}`;\n ctx.preamble.push(`var ${name}=${initializer};`);\n ctx.valueCache.set(initializer, name);\n return name;\n}\n\n/** Declare a `new Set([...])` in the preamble and return its variable name. */\nexport function emitSet(ctx: CodeGenContext, prefix: string, values: readonly unknown[]): string {\n const initializer = `new Set(${JSON.stringify([...values])})`;\n const sharedName = ctx.sharedSetNames?.get(initializer);\n if (sharedName !== undefined) return sharedName;\n const name = emitConstant(ctx, `set_${prefix}`, initializer);\n ctx.onSetConstant?.({ name, initializer });\n return name;\n}\n\n/**\n * Shape-key count at or below which the unknown-key pass compares with an\n * inline `===` chain rather than a hashed lookup.\n *\n * This is deliberately NOT {@link ENUM_INLINE_THRESHOLD}: the two look alike but\n * are different workloads. An enum compares schema literals against arbitrary\n * INPUT strings, which may be long, share prefixes, and are not necessarily\n * internalized — so a hashed set earns its keep quickly. A shape-key test\n * compares them against keys arriving from `for-in`, i.e. the object's own\n * internalized key strings, so every arm of the chain is a pointer compare that\n * V8 predicts perfectly, while `table[k]` / `set.has(k)` pays a string hash and\n * probe per key.\n *\n * Measured over a strict object's for-in pass (JSON-parsed input, 8 rotated\n * shapes), `===` chain vs the previous `{k:1}` table: 3.7x at 6 keys, 3.8x at\n * 10, 3.1x at 20, 3.1x at 48 — the chain still leads at 64 (283 ns vs 690) and\n * only loses past ~96, where `Set.has` (not the table, which never wins at any\n * size) takes over. 64 sits below that crossover and above any realistic shape.\n */\nexport const KEY_MEMBERSHIP_INLINE_THRESHOLD = 64;\n\n/**\n * Boolean membership test for one key variable against a fixed key list.\n * Empty list recognizes nothing.\n *\n * `Set.has` is the large-shape fallback rather than a `{key:1}` object table:\n * the table is also `__proto__`-hostile (an own `__proto__` key cannot be set\n * by an object literal, so that key would silently read as unknown), which the\n * Set has no trouble with.\n */\nexport function keyMembershipTest(\n ctx: CodeGenContext,\n keys: readonly string[],\n keyVar: string,\n): string {\n if (keys.length === 0) return \"false\";\n if (keys.length <= KEY_MEMBERSHIP_INLINE_THRESHOLD) {\n return keys.map((k) => `${keyVar}===${escapeString(k)}`).join(\"||\");\n }\n return `${emitSet(ctx, \"ks\", keys)}.has(${keyVar})`;\n}\n\n/**\n * Enum values at or below this count use inline === checks instead of Set.has().\n * Measured on V8: for ≤5 values, an === chain beats Set.has by up to ~3x with\n * realistic (distinct-prefix, JSON-parsed) values — V8 internalizes strings on\n * successful comparison, making subsequent arms pointer-equality — and is no\n * worse than Set.has even with adversarial shared-prefix values.\n */\nexport const ENUM_INLINE_THRESHOLD = 5;\n\nconst CHECK_PRIORITY: Record<string, number> = {\n // Cheapest: length/size comparisons (O(1))\n min_length: 10,\n max_length: 11,\n length_equals: 12,\n min_size: 13,\n max_size: 14,\n // Number format checks (comparison + bitwise)\n number_format: 15,\n // Range comparisons\n greater_than: 20,\n less_than: 21,\n bigint_greater_than: 20,\n bigint_less_than: 21,\n date_greater_than: 22,\n date_less_than: 23,\n // Modulo\n multiple_of: 30,\n bigint_multiple_of: 30,\n // String prefix/suffix (O(prefix/suffix length))\n starts_with: 40,\n ends_with: 41,\n // String search (O(n·m) worst case)\n includes: 42,\n // Regex (most expensive)\n string_format: 50,\n};\n\nexport function escapeString(s: string | number): string {\n return JSON.stringify(s);\n}\n\n/** The {@link LiteralValue}s that {@link literalToJs} can spell. */\nexport type SourceFormLiteral = string | number | boolean | null | bigint | undefined;\n\n/**\n * Can {@link literalToJs} render this value as JS source that strict-equals it?\n *\n * Total by construction — it NAMES the value kinds that have a source form\n * rather than excluding the ones that don't, so every reference value falls out\n * on the false side. That matters because `literalToJs` used to end in a bare\n * `JSON.stringify`, which does not fail loudly on the values it cannot spell:\n * for a symbol it RETURNS `undefined` (the value, not a string), so\n * `z.literal(sym)` compiled to the comparison `x===undefined` — rejecting the\n * symbol it was built from and accepting `undefined`. An object is mis-rendered\n * the other way: `{}` stringifies to `\"{}\"`, and `x==={}` is never true, so the\n * very object the schema was built from was rejected. Both take the runtime\n * membership path instead (see the literal generator).\n */\nexport function hasSourceForm(v: LiteralValue): v is SourceFormLiteral {\n if (v === null) return true;\n const t = typeof v;\n return t === \"string\" || t === \"number\" || t === \"boolean\" || t === \"bigint\" || t === \"undefined\";\n}\n\n/**\n * JS source for a primitive literal value (literal schemas, discriminator\n * case labels). JSON.stringify covers string/number/boolean/null; bigint\n * needs the `n` suffix (JSON.stringify throws and String(5n) renders a\n * number literal that never strict-equals a bigint); undefined isn't JSON.\n *\n * The parameter type is deliberately NARROWER than {@link LiteralValue}: every\n * caller must first prove its value is spellable with {@link hasSourceForm}.\n */\nexport function literalToJs(v: SourceFormLiteral): string {\n if (typeof v === \"bigint\") return `${v}n`;\n if (v === undefined) return \"undefined\";\n // JSON.stringify maps NaN/±Infinity to \"null\"; emit them as JS expressions so a\n // non-finite numeric literal round-trips (z.literal(Infinity) must compare\n // against Infinity, not null). String(NaN)=\"NaN\", String(Infinity)=\"Infinity\",\n // String(-Infinity)=\"-Infinity\" — all valid JS that evaluate to the value.\n if (typeof v === \"number\" && !Number.isFinite(v)) return String(v);\n return JSON.stringify(v);\n}\n\n/**\n * Helpers that generated code invokes through `Function.prototype.call`, and\n * which therefore must be aliased into a module-local binding in lean mode.\n *\n * V8 folds a local `const` callee into a constant and inlines straight through\n * `x.call(...)`; an IMPORTED binding is a cell it will not fold, so the same\n * expression stays a generic property load plus a generic call — measured 4.5x\n * (5 keys) to 6.5x (20 keys) slower on the record fast path, 35.9 ns vs 7.2 ns\n * for a 5-key record. Aliasing the import into the IIFE recovers all of it\n * (7.4 ns). A DIRECT call to an imported function (`__zcFsr(v,s)`) is not\n * penalized — measured identical — and neither is an imported RegExp receiver,\n * so only the `.call` sites are listed here.\n */\nconst CALL_INVOKED_HELPERS: ReadonlySet<string> = new Set([\"__zcHop\"]);\n\n/**\n * Reference a shared runtime helper (e.g. __zcFsr) from generated code.\n * Lean mode: registers it for the `virtual:zod-compiler/runtime` import.\n * Inline mode: declares it once in the per-IIFE preamble.\n */\nexport function emitRuntimeHelper(ctx: CodeGenContext, name: string, decl: string): string {\n if (ctx.mode === \"lean\") {\n ctx.usedHelpers.add(name);\n if (CALL_INVOKED_HELPERS.has(name)) return emitConstant(ctx, \"lh\", name);\n } else if (!ctx.preamble.includes(decl)) {\n ctx.preamble.push(decl);\n }\n return name;\n}\n\n/**\n * Extend a path expression with one or more scalar segment expressions\n * (escaped string literals, numeric literals, or loop-variable names).\n *\n * Path expressions are only ever composed by these helpers starting from the\n * `[]` root, so any path that looks like an array literal IS one — the new\n * segment is spliced in to keep issue paths a single array allocation\n * (`[\"data\",\"items\",__i_7]`) instead of an allocation per nesting level\n * (`[\"data\"].concat(\"items\").concat(__i_7)`). Opaque expressions fall back\n * to .concat().\n */\nexport function extendPath(parentPath: string, segExpr: string): string {\n if (parentPath === \"[]\") return `[${segExpr}]`;\n if (parentPath.startsWith(\"[\") && parentPath.endsWith(\"]\")) {\n return `${parentPath.slice(0, -1)},${segExpr}]`;\n }\n return `${parentPath}.concat(${segExpr})`;\n}\n\n/** Extend a path expression with a static string key. */\nexport function extendStaticPath(parentPath: string, key: string): string {\n return extendPath(parentPath, escapeString(key));\n}\n\n/** Extend a path expression with a numeric index. */\nexport function extendStaticPathIndex(parentPath: string, index: number): string {\n return extendPath(parentPath, String(index));\n}\n\n/**\n * A superRefine callback receives zod's payload, whose `value` is public,\n * typed, writable API ($RefinementCtx extends ParsePayload) — so any node\n * carrying one MAY rewrite its value and must be treated as mutating. Which\n * callbacks actually do is undecidable here; the emitted fast check settles it\n * at runtime by refusing when the value changed (see ZC_SR_OK_DECL), so a\n * non-mutating callback still exits through the fast path.\n */\nfunction hasSuperRefine(checks: readonly { kind: string }[] | undefined): boolean {\n return checks !== undefined && checks.some((c) => c.kind === \"super_refine_effect\");\n}\n\n/**\n * Check if a SchemaIR tree produces output that is not the input itself —\n * either value-mutating operations (coerce, default, catch, overwrite) that\n * write back to the input expression, or a strip object that rebuilds a fresh\n * object from its known keys. Used by container generators to decide whether to\n * clone (so the rebuilt/mutated value never writes through to the caller's\n * input), by generateValidator to keep such schemas off the by-reference fast\n * path, and by the shared-walk dedup + intersection extractor to exclude them.\n */\n/**\n * Can this tuple's output be LONGER than its input?\n *\n * `handleTupleResult` assigns `final.value[i] = result.value` for every item it\n * runs, and $ZodTuple runs every item below `optStart` even when the input is\n * shorter — so a required slot past the end is written with the `undefined` its\n * schema returned, extending the array. `z.tuple([z.any(), z.any()])` therefore\n * answers `[\"x\"]` with `[\"x\", undefined]`, length 2. A required item that\n * REJECTS undefined can't produce that: the parse fails and the value is never\n * read. So the extension is possible exactly when some required item accepts\n * `undefined` — which also makes the tuple a mutating node, since its output is\n * then not its input.\n */\nexport function tuplePadsShortInput(ir: SchemaIR & { type: \"tuple\" }): boolean {\n return ir.items.some((item, index) => index < ir.optStart && !rejectsUndefined(item));\n}\n\nexport function hasMutation(ir: SchemaIR): boolean {\n switch (ir.type) {\n case \"string\":\n // url checks trim (and optionally normalize) the value; overwrite\n // effects (.trim(), .toLowerCase()) rewrite it.\n return (\n ir.coerce === true ||\n hasSuperRefine(ir.checks) ||\n ir.checks.some(\n (c) =>\n c.kind === \"overwrite_effect\" || (c.kind === \"string_format\" && c.format === \"url\"),\n )\n );\n case \"number\":\n return ir.coerce === true || hasSuperRefine(ir.checks);\n case \"boolean\":\n case \"bigint\":\n case \"date\":\n return ir.coerce === true;\n case \"default\":\n case \"catch\":\n case \"effect\":\n case \"fallback\":\n case \"stringBool\":\n return true;\n case \"object\":\n // A strip object produces a FRESH output (only the declared keys), so it\n // mutates: parents must clone before it writes back, it never takes the\n // by-reference fast path, and intersections of strip objects delegate to\n // zod (see extractIntersection's hasMutation guard) — matching zod's\n // parse-both-sides-then-merge semantics instead of over-stripping.\n return (\n ir.stripUnknownKeys === true ||\n hasSuperRefine(ir.checks) ||\n (ir.catchall !== undefined && hasMutation(ir.catchall)) ||\n Object.values(ir.properties).some((p) => hasMutation(p))\n );\n case \"array\":\n return hasSuperRefine(ir.checks) || hasMutation(ir.element);\n case \"tuple\":\n return (\n ir.items.some(hasMutation) ||\n (ir.rest !== null && hasMutation(ir.rest)) ||\n tuplePadsShortInput(ir)\n );\n case \"record\":\n return hasMutation(ir.valueType);\n // A freezing readonly produces a value that is not its input, exactly as a\n // strip object does — so it must never take a by-reference shortcut.\n case \"readonly\":\n return ir.freeze === true || hasMutation(ir.inner);\n case \"optional\":\n case \"nullable\":\n case \"recursionTarget\":\n case \"zodDelegate\":\n return hasMutation(ir.inner);\n case \"union\":\n case \"discriminatedUnion\":\n return ir.options.some(hasMutation);\n case \"intersection\":\n return hasMutation(ir.left) || hasMutation(ir.right);\n case \"pipe\":\n return hasMutation(ir.in) || hasMutation(ir.out);\n case \"set\":\n return hasMutation(ir.valueType);\n case \"map\":\n return hasMutation(ir.keyType) || hasMutation(ir.valueType);\n case \"file\":\n return false;\n default:\n return false;\n }\n}\n\n/**\n * Is a defaulted property's key guaranteed to appear in the stripped output?\n *\n * Distinct from {@link rejectsUndefined}, which asks whether `undefined` is\n * REJECTED — a `.default()` accepts it and yet still produces a defined value, so\n * only this question earns the key a slot in the output object literal. The two\n * answers coincide everywhere else.\n *\n * Sound for both branches of a default: the substituted value is defined\n * (`alwaysDefined`, checked against the schema at extraction time), and the inner\n * branch runs only when `input[key] !== undefined`, which implies `key in input`\n * — so zod's presence test keeps the key whatever the inner produced.\n */\nexport function outputAlwaysDefined(ir: SchemaIR): boolean {\n return ir.type === \"default\" ? ir.alwaysDefined === true : rejectsUndefined(ir);\n}\n\n/**\n * Does this schema reject `undefined` outright?\n *\n * Read as \"can this slot be ABSENT from the input\" by the tuple build, whose\n * output length depends on it — zod marks a defaulted or optional item\n * `optin: \"optional\"` and accepts a shorter array. Conservative: anything that\n * might accept, produce, or default to `undefined` answers false.\n */\nexport function rejectsUndefined(ir: SchemaIR): boolean {\n switch (ir.type) {\n // Coercion turns undefined into a value (`String(undefined)`), so a\n // coercing primitive is NOT a rejector.\n case \"string\":\n case \"number\":\n case \"boolean\":\n case \"bigint\":\n case \"date\":\n return ir.coerce !== true;\n case \"symbol\":\n case \"null\":\n case \"nan\":\n case \"never\":\n case \"enum\":\n case \"object\":\n case \"array\":\n case \"tuple\":\n case \"record\":\n case \"set\":\n case \"map\":\n case \"file\":\n case \"templateLiteral\":\n case \"discriminatedUnion\":\n case \"stringBool\":\n return true;\n case \"literal\":\n return !ir.values.includes(undefined);\n case \"union\":\n return ir.options.every(rejectsUndefined);\n case \"intersection\":\n return rejectsUndefined(ir.left) || rejectsUndefined(ir.right);\n case \"nullable\":\n case \"readonly\":\n case \"recursionTarget\":\n case \"zodDelegate\":\n return rejectsUndefined(ir.inner);\n default:\n // optional / any / unknown / undefined / void / default / catch /\n // fallback / effect / pipe / recursiveRef — each can yield undefined,\n // or is opaque enough that we must not assume otherwise.\n return false;\n }\n}\n\n/**\n * Sort comparator for CheckIR: cheapest/most-discriminating checks first.\n * Used by fast-path generators after filtering out refine_effect entries.\n */\nexport function checkPriority(\n a: CheckIR | BigIntCheckIR | DateCheckIR | SetCheckIR,\n b: CheckIR | BigIntCheckIR | DateCheckIR | SetCheckIR,\n): number {\n return (CHECK_PRIORITY[a.kind] ?? 99) - (CHECK_PRIORITY[b.kind] ?? 99);\n}\n"],"mappings":";;;AAiPA,SAAgB,iBAAiB,OAA0B;CACzD,OAAO,MAAM,MAAM,SAAS,IAAI,OAAO,MAAM,MAAM,KAAK,GAAG,EAAE,KAAK;AACpE;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,oBACd,GACA,SACA,UACA,QACe;CACf,IAAI,CAAC,iBAAiB,EAAE,KAAK,GAAG;EAC9B,MAAM,QAAQ,EAAE,MAAM,OAAO;EAC7B,OAAO,UAAU,OAAO,OAAO,IAAI,EAAE,QAAQ,WAAW,OAAO,GAAG,MAAM;CAC1E;CACA,MAAM,QAAQ,EAAE,MAAM,GAAG;CACzB,MAAM,QAAQ,EAAE,MAAM,SAAS,EAAE,OAAO,MAAM,CAAC;CAC/C,IAAI,UAAU,MAAM,OAAO;CAC3B,OAAO,KA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AAO;EACT,SACE,OAAO;CACX;AACF;;;;;;;;;;;;;;AAeA,SAAgB,oBAAoB,IAAuB;CACzD,OAAO,GAAG,SAAS,YAAY,GAAG,kBAAkB,OAAO,iBAAiB,EAAE;AAChF;;;;;;;;;AAUA,SAAgB,iBAAiB,IAAuB;CACtD,QAAQ,GAAG,MAAX;EAGE,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,QACH,OAAO,GAAG,WAAW;EACvB,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,cACH,OAAO;EACT,KAAK,WACH,OAAO,CAAC,GAAG,OAAO,SAAS,KAAA,CAAS;EACtC,KAAK,SACH,OAAO,GAAG,QAAQ,MAAM,gBAAgB;EAC1C,KAAK,gBACH,OAAO,iBAAiB,GAAG,IAAI,KAAK,iBAAiB,GAAG,KAAK;EAC/D,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,eACH,OAAO,iBAAiB,GAAG,KAAK;EAClC,SAIE,OAAO;CACX;AACF;;;;;AAMA,SAAgB,cACd,GACA,GACQ;CACR,QAAQ,eAAe,EAAE,SAAS,OAAO,eAAe,EAAE,SAAS;AACrE"}
@@ -1,6 +1,6 @@
1
1
  import { SchemaIR } from "../types.js";
2
2
  import { SharedSchemaPlan } from "./dedupe.js";
3
- import { CodeGenResult, CodegenMode } from "./context.js";
3
+ import { CodeGenResult, CodegenMode, GeneratedSetConstant } from "./context.js";
4
4
  //#region src/core/codegen/index.d.ts
5
5
  interface GenerateValidatorOptions {
6
6
  refCount?: number;
@@ -20,6 +20,10 @@ interface GenerateValidatorOptions {
20
20
  * {@link CodeGenResult.rootDelegateRefIndex}.
21
21
  */
22
22
  compact?: boolean | undefined;
23
+ /** Internal file-pipeline hook for sharing exact Set initializers across validators. */
24
+ onSetConstant?: ((constant: GeneratedSetConstant) => void) | undefined;
25
+ /** Internal exact-initializer plan used by the file pipeline's final generation pass. */
26
+ sharedSetNames?: ReadonlyMap<string, string> | undefined;
23
27
  }
24
28
  /**
25
29
  * Generate optimized validation code from SchemaIR.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/core/codegen/index.ts"],"mappings":";;;;UAUiB;EACf;;EAEA,OAAO;;;;;EAKP,gBAAgB;;;;;;;;;EAShB;;;;;;;;;;;iBAYc,kBACd,IAAI,UACJ,cACA,UAAU,2BACT"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/core/codegen/index.ts"],"mappings":";;;;UAgBiB;EACf;;EAEA,OAAO;;;;;EAKP,gBAAgB;;;;;;;;;EAShB;;EAEA,kBAAkB,UAAU;;EAE5B,iBAAiB;;;;;;;;;;;iBAYH,kBACd,IAAI,UACJ,cACA,UAAU,2BACT"}
@@ -1,4 +1,4 @@
1
- import { declareFastTemps, emitRfDelegate, hasMutation } from "./context.js";
1
+ import { declareFastTemps, emitRfDelegate, emitRfMethod, hasMutation } from "./context.js";
2
2
  import { createSlowGen, generateSlow } from "./slow-path.js";
3
3
  import { createFastGen, generateFast } from "./fast-path.js";
4
4
  import { fastResultIsInput, generateBuild, rebuildsOutput } from "./build-path.js";
@@ -21,7 +21,9 @@ function generateValidator(ir, name, options) {
21
21
  fnName,
22
22
  regexCache: /* @__PURE__ */ new Map(),
23
23
  mode,
24
- usedHelpers: /* @__PURE__ */ new Set()
24
+ usedHelpers: /* @__PURE__ */ new Set(),
25
+ onSetConstant: options?.onSetConstant,
26
+ sharedSetNames: options?.sharedSetNames
25
27
  };
26
28
  if (options?.sharedSchemas !== void 0) ctx.sharedSchemas = options.sharedSchemas;
27
29
  if (ir.type === "fallback" && ir.refIndex !== void 0) {
@@ -100,14 +102,14 @@ function generateValidator(ir, name, options) {
100
102
  const buildIsFnName = ctx.buildSubstitutesValue === true ? null : fastFnName;
101
103
  const baseRefCount = options?.refCount ?? 0;
102
104
  if (options?.compact === true && fastExpr !== null && fastExpr !== "true" && !hasMutation(ir) && !hasNonRootTargets) {
103
- const delegate = emitRfDelegate(ctx, baseRefCount);
105
+ const delegate = emitRfMethod(ctx, baseRefCount);
104
106
  ctx.usedHelpers.add("__zcFinZ");
105
107
  return {
106
108
  code: ["/* zod-compiler */", ...ctx.preamble].join("\n"),
107
109
  functionDef: [
108
110
  `function ${fnName}(input){`,
109
111
  `if(${fastExpr}){return{success:true,data:input};}`,
110
- `return __zcFinZ(${delegate},input);`,
112
+ `return __zcFinZ(${delegate},__rf[${baseRefCount}],input);`,
111
113
  `}`
112
114
  ].join("\n"),
113
115
  refCount: baseRefCount + 1,
@@ -118,7 +120,7 @@ function generateValidator(ir, name, options) {
118
120
  };
119
121
  }
120
122
  if (options?.compact === true && buildFnName !== null && ctx.buildFailName !== void 0 && !hasNonRootTargets) {
121
- const delegate = emitRfDelegate(ctx, baseRefCount);
123
+ const delegate = emitRfMethod(ctx, baseRefCount);
122
124
  ctx.usedHelpers.add("__zcFinZ");
123
125
  const built = `__bd_${ctx.counter++}`;
124
126
  return {
@@ -127,7 +129,7 @@ function generateValidator(ir, name, options) {
127
129
  `function ${fnName}(input){`,
128
130
  `var ${built}=${buildFnName}(input);`,
129
131
  `if(${built}!==${ctx.buildFailName}){return{success:true,data:${built}};}`,
130
- `return __zcFinZ(${delegate},input);`,
132
+ `return __zcFinZ(${delegate},__rf[${baseRefCount}],input);`,
131
133
  `}`
132
134
  ].join("\n"),
133
135
  refCount: baseRefCount + 1,