schema-truth 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +143 -2
  2. package/dist/ajv-DTP2FXRr.js +105 -0
  3. package/dist/ajv.d.ts +24 -0
  4. package/dist/ajv.js +1 -0
  5. package/dist/arktype-BdvvaBQX.js +746 -0
  6. package/dist/arktype.d.ts +10 -0
  7. package/dist/arktype.js +1 -0
  8. package/dist/cli/ajv.d.ts +1 -0
  9. package/dist/cli/ajv.js +15 -0
  10. package/dist/cli/arktype.d.ts +1 -0
  11. package/dist/cli/arktype.js +15 -0
  12. package/dist/cli/effect.d.ts +1 -0
  13. package/dist/cli/effect.js +15 -0
  14. package/dist/cli/typebox.d.ts +1 -0
  15. package/dist/cli/typebox.js +15 -0
  16. package/dist/cli/valibot.d.ts +1 -0
  17. package/dist/cli/valibot.js +15 -0
  18. package/dist/cli/yup.d.ts +1 -0
  19. package/dist/cli/yup.js +15 -0
  20. package/dist/cli/zod.d.ts +1 -0
  21. package/dist/cli/zod.js +15 -0
  22. package/dist/cli-CL2mSark.js +124 -0
  23. package/dist/effect-mUknRPv_.js +645 -0
  24. package/dist/effect.d.ts +12 -0
  25. package/dist/effect.js +1 -0
  26. package/dist/helper-Cfvb5UDq.js +1115 -0
  27. package/dist/index-C2L8Ty0-.d.ts +65 -0
  28. package/dist/index-DbV3dEmN.d.ts +551 -0
  29. package/dist/index.d.ts +303 -0
  30. package/dist/index.js +10 -0
  31. package/dist/parser-CyJ2auea.js +36 -0
  32. package/dist/typebox-BdWJv3ND.js +544 -0
  33. package/dist/typebox.d.ts +21 -0
  34. package/dist/typebox.js +1 -0
  35. package/dist/utils-WNBq1HR0.js +1017 -0
  36. package/dist/valibot-CaJIynCH.js +664 -0
  37. package/dist/valibot.d.ts +9 -0
  38. package/dist/valibot.js +1 -0
  39. package/dist/yup-CM2TSFig.js +92 -0
  40. package/dist/yup.d.ts +17 -0
  41. package/dist/yup.js +1 -0
  42. package/dist/zod-BsXLZfwK.js +777 -0
  43. package/dist/zod.d.ts +9 -0
  44. package/dist/zod.js +1 -0
  45. package/package.json +112 -4
@@ -0,0 +1,777 @@
1
+ import { B as isSchemaObject, D as isComposite, F as isPrimitive, H as isStringWireLocation, M as isNullable, N as isObjectPrototypeProperty, Ot as UNSAFE_GENERATED_MARKER, P as isPlainObject, S as hasFixedLength, T as hasType, V as isShapelessMember, X as DEFAULT_ROOT_NAME, b as hasConditional, c as normalizeTypes, g as zodErrorPart, h as zodError, j as isNullTypeMember, k as isDefaultOnlyMember, m as zodBaseError, o as issueMessageExpression, ot as ISO_4217_CURRENCY_CODES, s as makeSafeKey, y as hasCombinator } from "./utils-WNBq1HR0.js";
2
+ import { A as emitOptionsOf, F as schemaNamer, H as findCodeExtensionKeysInSchema, L as hasRootSelfReference, M as planDocument, N as renderDefinitions, P as rootNameOf, S as wireNullText, T as timePattern, a as regexLiteral, b as unionPrimitiveTypes, c as parameterReaders, g as isPrimitiveUnion, h as isNullTextRead, i as typeDeclaration, l as withoutParameterSerialization, m as isNullMatchedFirst, o as refTarget, p as impliedWireType, s as hasParameterSerialization, t as zodWrap, u as notPredicate, x as wireArrayOnce, z as itemsSchemaOf } from "./helper-Cfvb5UDq.js";
3
+ //#region src/generator/zod/type.ts
4
+ /** The TypeScript type declared beside a recursive Zod schema. */
5
+ function type(schema, rootName = DEFAULT_ROOT_NAME) {
6
+ return typeDeclaration(schema, {
7
+ inferRoot: (name) => `z.infer<typeof ${name}>`,
8
+ readonly: false
9
+ }, rootName);
10
+ }
11
+ //#endregion
12
+ //#region src/generator/zod/integer.ts
13
+ /** Whether a node is a 64-bit integer: a value beyond 2^53 that Zod reads as a bigint. */
14
+ function isInt64(schema) {
15
+ return schema.format === "int64" || schema.format === "uint64";
16
+ }
17
+ /**
18
+ * What reads a 64-bit integer into a bigint ahead of the check. On the string wire the text
19
+ * is coerced; in a JSON body the value is a safe-integer number, or the string of digits
20
+ * that is the only lossless way to carry a larger one, and nothing else.
21
+ */
22
+ function int64Input(isWire, baseErrorArg = "") {
23
+ if (isWire) return `z.coerce.bigint(${baseErrorArg})`;
24
+ const errorPart = baseErrorArg ? `,${baseErrorArg}` : "";
25
+ return String.raw`z.union([z.bigint(),z.number().int(),z.string().regex(/^-?\d+$/)]${errorPart}).transform((val)=>BigInt(val))`;
26
+ }
27
+ /**
28
+ * Generates a Zod schema for integer types (int / int32 / uint32 / int64 / bigint), with
29
+ * min/max/multipleOf constraints and `x-*-message` vendor extensions translated
30
+ * to Zod v4 `{error: "msg"}` parameters.
31
+ */
32
+ function integer(schema) {
33
+ const errorMessage = schema["x-error-message"];
34
+ const requiredMessage = schema["x-required-message"];
35
+ const isCoerce = schema["x-coerce"] === true;
36
+ const baseErrorArg = zodBaseError(errorMessage, isCoerce ? void 0 : requiredMessage);
37
+ const isBigint = schema.format === "bigint";
38
+ const isInt32 = schema.format === "int32" || schema.format === "uint32";
39
+ const is64 = isInt64(schema);
40
+ const bigintBase = isCoerce && isBigint;
41
+ const numberPipe = isCoerce && isInt32;
42
+ const numberChain = isCoerce && !isBigint && !is64 && !isInt32;
43
+ const base = bigintBase ? `z.coerce.bigint(${baseErrorArg})` : isInt32 ? `z.${schema.format === "uint32" ? "uint32" : "int32"}(${baseErrorArg})` : is64 ? `z.${schema.format === "uint64" ? "uint64" : "int64"}(${baseErrorArg})` : isBigint ? `z.bigint(${baseErrorArg})` : `z.int(${baseErrorArg})`;
44
+ const lit = (n) => {
45
+ if (schema.format === "bigint") return `BigInt(${n})`;
46
+ if (is64) return `${n}n`;
47
+ return `${n}`;
48
+ };
49
+ const minimumMessage = schema["x-minimum-message"] ?? errorMessage;
50
+ const exclusiveMinMessage = schema["x-exclusiveMinimum-message"] ?? errorMessage;
51
+ const minErrorArg = minimumMessage ? zodError(minimumMessage) : "";
52
+ const minErrorPart = minErrorArg ? `,${minErrorArg}` : "";
53
+ const exMinErrorArg = exclusiveMinMessage ? zodError(exclusiveMinMessage) : "";
54
+ const exMinErrorPart = exMinErrorArg ? `,${exMinErrorArg}` : "";
55
+ const minimum = (() => {
56
+ if (schema.minimum === void 0 && schema.exclusiveMinimum === void 0) return;
57
+ const value = schema.minimum ?? schema.exclusiveMinimum;
58
+ if (value === 0 && schema.exclusiveMinimum === true) return `.positive(${exMinErrorArg})`;
59
+ if (value === 0 && schema.exclusiveMinimum === false) return `.nonnegative(${minErrorArg})`;
60
+ if ((schema.exclusiveMinimum === true || schema.minimum === void 0) && typeof value === "number") return `.gt(${lit(value)}${exMinErrorPart})`;
61
+ if (typeof schema.minimum === "number") return `.min(${lit(schema.minimum)}${minErrorPart})`;
62
+ })();
63
+ const maximumMessage = schema["x-maximum-message"] ?? errorMessage;
64
+ const exclusiveMaxMessage = schema["x-exclusiveMaximum-message"] ?? errorMessage;
65
+ const maxErrorArg = maximumMessage ? zodError(maximumMessage) : "";
66
+ const maxErrorPart = maxErrorArg ? `,${maxErrorArg}` : "";
67
+ const exMaxErrorArg = exclusiveMaxMessage ? zodError(exclusiveMaxMessage) : "";
68
+ const exMaxErrorPart = exMaxErrorArg ? `,${exMaxErrorArg}` : "";
69
+ const maximum = (() => {
70
+ if (schema.maximum === void 0 && schema.exclusiveMaximum === void 0) return;
71
+ const value = schema.maximum ?? schema.exclusiveMaximum;
72
+ if (value === 0 && schema.exclusiveMaximum === true) return `.negative(${exMaxErrorArg})`;
73
+ if (value === 0 && schema.exclusiveMaximum === false) return `.nonpositive(${maxErrorArg})`;
74
+ if ((schema.exclusiveMaximum === true || schema.maximum === void 0) && typeof value === "number") return `.lt(${lit(value)}${exMaxErrorPart})`;
75
+ if (typeof schema.maximum === "number") return `.max(${lit(schema.maximum)}${maxErrorPart})`;
76
+ })();
77
+ const multipleOfMessage = schema["x-multipleOf-message"] ?? errorMessage;
78
+ const multipleOfErrorArg = zodErrorPart(multipleOfMessage);
79
+ const multipleOf = typeof schema.multipleOf === "number" ? `.multipleOf(${lit(schema.multipleOf)}${multipleOfErrorArg})` : void 0;
80
+ const innerChain = [
81
+ base,
82
+ minimum,
83
+ maximum,
84
+ multipleOf
85
+ ].filter((v) => v !== void 0).join("");
86
+ if (numberChain) {
87
+ const constraints = [
88
+ minimum,
89
+ maximum,
90
+ multipleOf
91
+ ].filter((v) => v !== void 0).join("");
92
+ return `z.coerce.number(${baseErrorArg}).int(${errorMessage ? zodError(errorMessage) : ""})${constraints}`;
93
+ }
94
+ if (numberPipe) return `z.coerce.number(${baseErrorArg}).pipe(${innerChain})`;
95
+ if (is64) return `${int64Input(isCoerce, baseErrorArg)}.pipe(${innerChain})`;
96
+ return innerChain;
97
+ }
98
+ //#endregion
99
+ //#region src/generator/zod/enum.ts
100
+ /**
101
+ * Generates a Zod enum schema. String enums map to `z.enum`, number/integer/
102
+ * boolean enums to `z.union([z.literal(...), ...])`, array enums to `z.tuple`
103
+ * or `z.union`, single values to `z.literal`.
104
+ *
105
+ * `x-error-message` (whole-enum) is applied **only to the outermost
106
+ * wrapper** (z.enum / z.union / z.tuple, or the bare z.literal in the
107
+ * single-value case). Inner z.literal entries inside a wrapper never
108
+ * receive a duplicate `error:` arg — Zod's outer wrapper already shadows
109
+ * inner messages on validation failure, so the inner copy was dead.
110
+ *
111
+ * Per-literal `x-enum-error-messages` was removed entirely: a rejected
112
+ * value by definition isn't in the enum, so a per-literal
113
+ * `value === 'admin'` branch can never match. Whole-enum messages
114
+ * come from `x-error-message`; finer-grained business rules belong in
115
+ * handler code, not the schema.
116
+ */
117
+ function lit(v, isBigint) {
118
+ if (v === null) return "null";
119
+ if (typeof v === "string") return `'${v.replaceAll("'", "\\'")}'`;
120
+ if (typeof v === "number" && isBigint) return `${v}n`;
121
+ if (typeof v === "number" || typeof v === "boolean") return String(v);
122
+ return JSON.stringify(v) ?? "null";
123
+ }
124
+ function _enum(schema) {
125
+ const isBigint = isInt64(schema);
126
+ if (!schema.enum || schema.enum.length === 0) return "z.any()";
127
+ const errorMessage = schema["x-enum-message"] ?? schema["x-error-message"];
128
+ const errorArg = zodErrorPart(errorMessage);
129
+ const valueSchema = (v) => {
130
+ if (Array.isArray(v)) return `z.tuple([${v.map(valueSchema).join(",")}])`;
131
+ if (isPlainObject(v)) return `z.strictObject({${Object.entries(v).map(([k, val]) => `${makeSafeKey(k)}:${valueSchema(val)}`).join(",")}})`;
132
+ return `z.literal(${lit(v, isBigint)})`;
133
+ };
134
+ const innerLit = (v) => valueSchema(v);
135
+ const outerLit = (v) => isComposite(v) ? valueSchema(v) : `z.literal(${lit(v, isBigint)}${errorArg})`;
136
+ const innerTuple = (arr) => `z.tuple([${arr.map(innerLit).join(",")}])`;
137
+ const outerTuple = (arr) => `z.tuple([${arr.map(innerLit).join(",")}]${errorArg})`;
138
+ if (hasType(schema, "number") || hasType(schema, "integer") || hasType(schema, "boolean")) return schema.enum.length > 1 ? `z.union([${schema.enum.map(innerLit).join(",")}]${errorArg})` : outerLit(schema.enum[0]);
139
+ if (hasType(schema, "array")) {
140
+ if (schema.enum.length === 1 && Array.isArray(schema.enum[0])) return outerTuple(schema.enum[0]);
141
+ return `z.union([${schema.enum.map((v) => Array.isArray(v) ? innerTuple(v) : innerLit(v)).join(",")}]${errorArg})`;
142
+ }
143
+ if (schema.enum.every((v) => typeof v === "string")) {
144
+ if (schema.enum.length > 1) return `z.enum(${JSON.stringify(schema.enum)}${errorArg})`;
145
+ return outerLit(schema.enum[0]);
146
+ }
147
+ if (schema.enum.length > 1) return `z.union([${schema.enum.map(innerLit).join(",")}]${errorArg})`;
148
+ return outerLit(schema.enum[0]);
149
+ }
150
+ //#endregion
151
+ //#region src/generator/zod/number.ts
152
+ /**
153
+ * Generates a Zod schema for number types (number / float32 / float64), with
154
+ * min/max/multipleOf constraints and `x-*-message` vendor extensions translated
155
+ * to Zod v4 `{error: "msg"}` parameters.
156
+ */
157
+ function number(schema) {
158
+ const errorMessage = schema["x-error-message"];
159
+ const requiredMessage = schema["x-required-message"];
160
+ const isCoerce = schema["x-coerce"] === true;
161
+ const baseErrorArg = zodBaseError(errorMessage, isCoerce ? void 0 : requiredMessage);
162
+ const isFloat32 = schema.format === "float" || schema.format === "float32";
163
+ const isFloat64 = schema.format === "float64";
164
+ const wirePipe = isCoerce && (isFloat32 || isFloat64);
165
+ const base = isCoerce && !isFloat32 && !isFloat64 ? `z.coerce.number(${baseErrorArg})` : isFloat32 ? `z.float32(${baseErrorArg})` : isFloat64 ? `z.float64(${baseErrorArg})` : `z.number(${baseErrorArg})`;
166
+ const minimumMessage = schema["x-minimum-message"];
167
+ const exclusiveMinMessage = schema["x-exclusiveMinimum-message"];
168
+ const minErrorArg = minimumMessage ? zodError(minimumMessage) : "";
169
+ const minErrorPart = minErrorArg ? `,${minErrorArg}` : "";
170
+ const exMinErrorArg = exclusiveMinMessage ? zodError(exclusiveMinMessage) : "";
171
+ const exMinErrorPart = exMinErrorArg ? `,${exMinErrorArg}` : "";
172
+ const minimum = (() => {
173
+ if (schema.minimum !== void 0) {
174
+ if (schema.minimum === 0 && schema.exclusiveMinimum === true) return `.positive(${exMinErrorArg})`;
175
+ if (schema.minimum === 0 && schema.exclusiveMinimum === false) return `.nonnegative(${minErrorArg})`;
176
+ if (schema.exclusiveMinimum === true) return `.gt(${schema.minimum}${exMinErrorPart})`;
177
+ return `.min(${schema.minimum}${minErrorPart})`;
178
+ }
179
+ if (typeof schema.exclusiveMinimum === "number") return `.gt(${schema.exclusiveMinimum}${exMinErrorPart})`;
180
+ })();
181
+ const maximumMessage = schema["x-maximum-message"];
182
+ const exclusiveMaxMessage = schema["x-exclusiveMaximum-message"];
183
+ const maxErrorArg = maximumMessage ? zodError(maximumMessage) : "";
184
+ const maxErrorPart = maxErrorArg ? `,${maxErrorArg}` : "";
185
+ const exMaxErrorArg = exclusiveMaxMessage ? zodError(exclusiveMaxMessage) : "";
186
+ const exMaxErrorPart = exMaxErrorArg ? `,${exMaxErrorArg}` : "";
187
+ const maximum = (() => {
188
+ if (schema.maximum !== void 0) {
189
+ if (schema.maximum === 0 && schema.exclusiveMaximum === true) return `.negative(${exMaxErrorArg})`;
190
+ if (schema.maximum === 0 && schema.exclusiveMaximum === false) return `.nonpositive(${maxErrorArg})`;
191
+ if (schema.exclusiveMaximum === true) return `.lt(${schema.maximum}${exMaxErrorPart})`;
192
+ return `.max(${schema.maximum}${maxErrorPart})`;
193
+ }
194
+ if (typeof schema.exclusiveMaximum === "number") return `.lt(${schema.exclusiveMaximum}${exMaxErrorPart})`;
195
+ })();
196
+ const multipleOfMessage = schema["x-multipleOf-message"];
197
+ const multipleOfErrorArg = multipleOfMessage ? `,${zodError(multipleOfMessage)}` : baseErrorArg ? `,${baseErrorArg}` : "";
198
+ const innerChain = [
199
+ base,
200
+ minimum,
201
+ maximum,
202
+ schema.multipleOf !== void 0 ? `.multipleOf(${schema.multipleOf}${multipleOfErrorArg})` : void 0
203
+ ].filter((v) => v !== void 0).join("");
204
+ return wirePipe ? `z.coerce.number(${baseErrorArg}).pipe(${innerChain})` : innerChain;
205
+ }
206
+ //#endregion
207
+ //#region src/generator/zod/object.ts
208
+ /**
209
+ * A parameter object answers an `Object.prototype` name it was not sent with the inherited
210
+ * member. Copied onto a null-prototype object, it holds only what the request carried.
211
+ */
212
+ const OWN_PROPERTIES_PREPROCESS = "(val)=>(typeof val===\"object\"&&val!==null&&!Array.isArray(val)?Object.assign(Object.create(null),val):val)";
213
+ /**
214
+ * Generate a Zod object schema for a JSON Schema object node.
215
+ *
216
+ * Dispatches `additionalProperties` to `z.looseObject` (true), `z.strictObject`
217
+ * (false), `z.record` (Schema), or default `z.object`. Combinators
218
+ * (oneOf/anyOf/allOf/not) delegate to the main `zod` entry. JSON Schema 2020-12
219
+ * keywords (`minProperties`, `maxProperties`, `propertyNames`,
220
+ * `patternProperties`, `dependentRequired`) are emitted as `.refine(...)`
221
+ * chains.
222
+ */
223
+ function object(schema, rootName, isZod, options) {
224
+ if (hasCombinator(schema)) return zod(schema, rootName, isZod, options);
225
+ const errorMessage = schema["x-error-message"];
226
+ const errorArg = zodErrorPart(errorMessage);
227
+ const minPropsMessage = schema["x-minProperties-message"];
228
+ const minErrorArg = zodErrorPart(minPropsMessage);
229
+ const maxPropsMessage = schema["x-maxProperties-message"];
230
+ const maxErrorArg = zodErrorPart(maxPropsMessage);
231
+ const patternPropsMessage = schema["x-patternProperties-message"];
232
+ const patternErrorArg = zodErrorPart(patternPropsMessage);
233
+ const propNamesMessage = schema["x-propertyNames-message"];
234
+ const propNamesErrorArg = zodErrorPart(propNamesMessage);
235
+ const depReqMessage = schema["x-dependentRequired-message"];
236
+ const depReqErrorArg = depReqMessage ? `,${zodError(depReqMessage)}` : errorArg;
237
+ const depSchMessage = schema["x-dependentSchemas-message"];
238
+ const depSchErrorArg = depSchMessage ? `,${zodError(depSchMessage)}` : errorArg;
239
+ if (typeof schema.additionalProperties === "object") return `${`z.record(z.string(),${zod(schema.additionalProperties, rootName, isZod, options)})`}${schema.propertyNames?.pattern ? `.refine((val)=>Object.keys(val).every((key)=>new RegExp(${JSON.stringify(schema.propertyNames.pattern)}).test(key))${propNamesErrorArg})` : schema.propertyNames?.enum ? `.refine((val)=>Object.keys(val).every((key)=>${JSON.stringify(schema.propertyNames.enum)}.includes(key))${propNamesErrorArg})` : ""}${schema.patternProperties ? Object.entries(schema.patternProperties).map(([pattern, propSchema]) => {
240
+ const z = zod(propSchema, rootName, isZod, options);
241
+ return `.refine((val)=>Object.entries(val).every(([key,value])=>!new RegExp(${JSON.stringify(pattern)}).test(key)||${z}.safeParse(value).success)${patternErrorArg})`;
242
+ }).join("") : ""}`;
243
+ if (!schema.properties) {
244
+ if (schema.additionalProperties === true) return "z.any()";
245
+ return "z.object({})";
246
+ }
247
+ const conditionalKeysReferenced = hasConditional(schema);
248
+ const objectType = schema.additionalProperties === true ? "looseObject" : schema.additionalProperties === false || schema.unevaluatedProperties === false ? "strictObject" : conditionalKeysReferenced ? "looseObject" : "object";
249
+ const required = new Set(schema.required);
250
+ const props = Object.entries(schema.properties).map(([key, propSchema]) => {
251
+ const parsed = zod(propSchema, rootName, isZod, options);
252
+ if (!parsed) return null;
253
+ return `${makeSafeKey(key)}:${parsed}${required.has(key) ? "" : ".exactOptional()"}`;
254
+ }).filter((v) => v !== null);
255
+ const strictMessage = schema["x-additionalProperties-message"] ?? (schema.unevaluatedProperties === false ? schema["x-unevaluatedProperties-message"] : void 0);
256
+ const objectParams = objectType === "strictObject" && strictMessage ? `,{error:(issue)=>issue.code==='unrecognized_keys'?${JSON.stringify(strictMessage)}:${errorMessage ? JSON.stringify(errorMessage) : "undefined"}}` : "";
257
+ const rawBase = `z.${objectType}({${props.join(",")}}${objectParams})`;
258
+ const propsMessage = schema["x-properties-message"];
259
+ const objectExpr = `${propsMessage ? (() => {
260
+ const msgExpr = issueMessageExpression(propsMessage);
261
+ return `(()=>{const Schema=${rawBase};return z.unknown().check((ctx)=>{const result=Schema.safeParse(ctx.value);if(!result.success){for(const issue of result.error.issues){if(issue.path.length>0){ctx.issues.push({...issue,message:${msgExpr}})}else{ctx.issues.push(issue)}}}}).pipe(Schema)})()`;
262
+ })() : rawBase}${typeof schema.minProperties === "number" ? `.refine((val)=>Object.keys(val).length>=${schema.minProperties}${minErrorArg})` : ""}${typeof schema.maxProperties === "number" ? `.refine((val)=>Object.keys(val).length<=${schema.maxProperties}${maxErrorArg})` : ""}${schema.propertyNames?.pattern ? `.refine((val)=>Object.keys(val).every((key)=>new RegExp(${JSON.stringify(schema.propertyNames.pattern)}).test(key))${propNamesErrorArg})` : schema.propertyNames?.enum ? `.refine((val)=>Object.keys(val).every((key)=>${JSON.stringify(schema.propertyNames.enum)}.includes(key))${propNamesErrorArg})` : ""}${schema.patternProperties ? Object.entries(schema.patternProperties).map(([pattern, propSchema]) => {
263
+ const z = zod(propSchema, rootName, isZod, options);
264
+ return `.refine((val)=>Object.entries(val).every(([key,value])=>!new RegExp(${JSON.stringify(pattern)}).test(key)||${z}.safeParse(value).success)${patternErrorArg})`;
265
+ }).join("") : ""}${schema.dependentRequired ? Object.entries(schema.dependentRequired).map(([key, deps]) => {
266
+ return `.refine((val)=>!('${key}' in val)||(${deps.map((d) => `'${d}' in val`).join("&&")})${depReqErrorArg})`;
267
+ }).join("") : ""}${schema.dependentSchemas ? Object.entries(schema.dependentSchemas).map(([key, subSchema]) => {
268
+ return `.refine((val)=>!('${key}' in val)||${zod(subSchema, rootName, isZod, options)}.safeParse(val).success${depSchErrorArg})`;
269
+ }).join("") : ""}${(() => {
270
+ if (!schema.if) return "";
271
+ const ifS = zod(schema.if, rootName, isZod, options);
272
+ const thenS = schema.then ? zod(schema.then, rootName, isZod, options) : void 0;
273
+ const elseS = schema.else ? zod(schema.else, rootName, isZod, options) : void 0;
274
+ if (!thenS && !elseS) return "";
275
+ const ifMessage = schema["x-if-message"];
276
+ const thenMessage = schema["x-then-message"] ?? ifMessage;
277
+ const elseMessage = schema["x-else-message"] ?? ifMessage;
278
+ const parts = [];
279
+ if (thenS) {
280
+ const arg = zodErrorPart(thenMessage);
281
+ parts.push(`.refine((val)=>!${ifS}.safeParse(val).success||${thenS}.safeParse(val).success${arg})`);
282
+ }
283
+ if (elseS) {
284
+ const arg = zodErrorPart(elseMessage);
285
+ parts.push(`.refine((val)=>${ifS}.safeParse(val).success||${elseS}.safeParse(val).success${arg})`);
286
+ }
287
+ return parts.join("");
288
+ })()}`;
289
+ const hasInheritedName = Object.keys(schema.properties).some(isObjectPrototypeProperty);
290
+ return isStringWireLocation(options?.paramIn) && hasInheritedName ? `z.preprocess(${OWN_PROPERTIES_PREPROCESS},${objectExpr})` : objectExpr;
291
+ }
292
+ //#endregion
293
+ //#region src/generator/zod/parameter.ts
294
+ /**
295
+ * Wraps the root expression of a parameter's schema in what reads the parameter's
296
+ * serialization: `allowEmptyValue`, a JSON `content`, or its `style` / `explode`.
297
+ *
298
+ * @see https://spec.openapis.org/oas/v3.2.0.html#style-examples
299
+ */
300
+ function parameter(schema, inner, options) {
301
+ return parameterReaders(schema, options, "val").reduceRight((acc, step) => `z.preprocess(${step},${acc})`, inner);
302
+ }
303
+ //#endregion
304
+ //#region src/generator/zod/string.ts
305
+ /** The formats Zod checks with a top-level validator, keyed by the lower-cased format. */
306
+ const FORMAT_STRING = {
307
+ email: "email()",
308
+ guid: "guid()",
309
+ uuid: "uuid()",
310
+ uuidv4: "uuidv4()",
311
+ uuidv6: "uuidv6()",
312
+ uuidv7: "uuidv7()",
313
+ uri: "url()",
314
+ url: "url()",
315
+ httpurl: "httpUrl()",
316
+ hostname: "hostname()",
317
+ hex: "hex()",
318
+ e164: "e164()",
319
+ ksuid: "ksuid()",
320
+ xid: "xid()",
321
+ emoji: "emoji()",
322
+ base64: "base64()",
323
+ base64url: "base64url()",
324
+ nanoid: "nanoid()",
325
+ cuid: "cuid()",
326
+ cuid2: "cuid2()",
327
+ ulid: "ulid()",
328
+ ipv4: "ipv4()",
329
+ ipv6: "ipv6()",
330
+ mac: "mac()",
331
+ cidrv4: "cidrv4()",
332
+ cidrv6: "cidrv6()",
333
+ date: "iso.date()",
334
+ "date-time": "iso.datetime()",
335
+ duration: "iso.duration()",
336
+ binary: "file()",
337
+ jwt: "jwt()"
338
+ };
339
+ /** The formats that normalise the value rather than check it, keyed by the lower-cased format. */
340
+ const TRANSFORM_FORMATS = {
341
+ trim: ".trim()",
342
+ tolowercase: ".toLowerCase()",
343
+ touppercase: ".toUpperCase()"
344
+ };
345
+ const LUHN_CHECK = `(val)=>{let sum=0;for(let i=0;i<val.length;i++){let digit=Number(val[val.length-1-i]);if(i%2===1){digit*=2;if(digit>9)digit-=9}sum+=digit}return sum%10===0}`;
346
+ const IBAN_CHECK = `(val)=>{let rest=0;for(const char of val.slice(4)+val.slice(0,4)){const n=Number.parseInt(char,36);rest=(n>9?rest*100+n:rest*10+n)%97}return rest===1}`;
347
+ /**
348
+ * The checks chained onto `z.string()` for a format Zod has no validator of its own for,
349
+ * or `undefined` when the format is not one of them.
350
+ */
351
+ function formatChecks(schema, format) {
352
+ const errorMessage = schema["x-error-message"];
353
+ const errorPart = zodErrorPart(errorMessage);
354
+ if (format === "time" && schema["x-isoOffset"] !== false) {
355
+ const precision = schema["x-isoPrecision"];
356
+ return `.regex(${timePattern(typeof precision === "number" ? precision : void 0, true)}${errorPart})`;
357
+ }
358
+ if (format === "creditcard") return `${String.raw`.regex(/^\d{12,19}$/${errorPart})`}.refine(${LUHN_CHECK}${errorPart})`;
359
+ if (format === "iban") return `${String.raw`.regex(/^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/${errorPart})`}.refine(${IBAN_CHECK}${errorPart})`;
360
+ if (format === "currencycode") return `.regex(/^(?:${ISO_4217_CURRENCY_CODES.join("|")})$/${errorPart})`;
361
+ }
362
+ /** The Zod format call of a node, as `z.` would be followed by, or `undefined`. */
363
+ function formatCall(schema, format) {
364
+ if (format === "time") return schema["x-isoOffset"] === false ? "iso.time()" : void 0;
365
+ return FORMAT_STRING[format];
366
+ }
367
+ const EMAIL_PATTERN_MAP = {
368
+ html5: "z.regexes.html5Email",
369
+ rfc5322: "z.regexes.rfc5322Email",
370
+ browser: "z.regexes.browserEmail",
371
+ unicode: "z.regexes.unicodeEmail"
372
+ };
373
+ function buildFormatOptions(schema, format) {
374
+ const parts = [];
375
+ if (format === "email") {
376
+ const emailPattern = schema["x-emailPattern"];
377
+ const emailRegex = schema["x-emailRegex"];
378
+ if (typeof emailPattern === "string" && EMAIL_PATTERN_MAP[emailPattern] !== void 0) parts.push(`pattern:${EMAIL_PATTERN_MAP[emailPattern]}`);
379
+ else if (typeof emailRegex === "string") parts.push(`pattern:${regexLiteral(emailRegex)}`);
380
+ return parts;
381
+ }
382
+ if (format === "uuid") {
383
+ const uuidVersion = schema["x-uuidVersion"];
384
+ if (typeof uuidVersion === "string") parts.push(`version:${JSON.stringify(uuidVersion)}`);
385
+ return parts;
386
+ }
387
+ if (format === "uri" || format === "url" || format === "httpurl") {
388
+ const urlProtocol = schema["x-urlProtocol"];
389
+ if (typeof urlProtocol === "string") parts.push(`protocol:${regexLiteral(urlProtocol)}`);
390
+ const urlHostname = schema["x-urlHostname"];
391
+ if (typeof urlHostname === "string") parts.push(`hostname:${regexLiteral(urlHostname)}`);
392
+ if (schema["x-urlNormalize"] === true) parts.push("normalize:true");
393
+ else if (schema["x-urlNormalize"] === false) parts.push("normalize:false");
394
+ return parts;
395
+ }
396
+ if (format === "date-time") {
397
+ const precision = schema["x-isoPrecision"];
398
+ if (typeof precision === "number") parts.push(`precision:${precision}`);
399
+ if (schema["x-isoOffset"] !== false) parts.push("offset:true");
400
+ const local = schema["x-isoLocal"];
401
+ if (typeof local === "boolean") parts.push(`local:${local}`);
402
+ return parts;
403
+ }
404
+ if (format === "time") {
405
+ const precision = schema["x-isoPrecision"];
406
+ if (typeof precision === "number") parts.push(`precision:${precision}`);
407
+ return parts;
408
+ }
409
+ if (format === "jwt") {
410
+ const alg = schema["x-jwtAlg"];
411
+ if (typeof alg === "string") parts.push(`alg:${JSON.stringify(alg)}`);
412
+ return parts;
413
+ }
414
+ if (format === "mac") {
415
+ const delimiter = schema["x-macDelimiter"];
416
+ if (typeof delimiter === "string") parts.push(`delimiter:${JSON.stringify(delimiter)}`);
417
+ return parts;
418
+ }
419
+ return parts;
420
+ }
421
+ function hashBase(schema, baseErrorArg) {
422
+ if (schema.format !== "hash") return void 0;
423
+ const algo = schema["x-hashAlg"];
424
+ if (algo === void 0) return baseErrorArg ? `z.string(${baseErrorArg})` : "z.string()";
425
+ const enc = schema["x-hashEnc"];
426
+ const errorPart = baseErrorArg ? baseErrorArg.slice(1, -1) : "";
427
+ const opts = [enc !== void 0 ? `enc:${JSON.stringify(enc)}` : void 0, errorPart || void 0].filter((v) => v !== void 0);
428
+ const optsStr = opts.length > 0 ? `,{${opts.join(",")}}` : "";
429
+ return `z.hash(${JSON.stringify(algo)}${optsStr})`;
430
+ }
431
+ function mergeOptions(formatOptions, baseErrorArg) {
432
+ if (formatOptions.length === 0) return baseErrorArg;
433
+ const errorPart = baseErrorArg ? baseErrorArg.slice(1, -1) : "";
434
+ return `{${(errorPart ? [...formatOptions, errorPart] : [...formatOptions]).join(",")}}`;
435
+ }
436
+ function stringbool(schema) {
437
+ const flag = schema["x-stringbool"];
438
+ if (flag === void 0 || flag === false) return void 0;
439
+ const opts = typeof flag === "object" ? flag : {};
440
+ const parts = [];
441
+ if (Array.isArray(opts.truthy)) parts.push(`truthy:[${opts.truthy.map((s) => JSON.stringify(s)).join(",")}]`);
442
+ if (Array.isArray(opts.falsy)) parts.push(`falsy:[${opts.falsy.map((s) => JSON.stringify(s)).join(",")}]`);
443
+ if (opts.case === "sensitive" || opts.case === "insensitive") parts.push(`case:${JSON.stringify(opts.case)}`);
444
+ const error = opts.error ?? schema["x-error-message"];
445
+ if (typeof error === "string") parts.push(`error:${JSON.stringify(error)}`);
446
+ return parts.length === 0 ? "z.stringbool()" : `z.stringbool({${parts.join(",")}})`;
447
+ }
448
+ function string(schema) {
449
+ const stringboolExpr = stringbool(schema);
450
+ if (stringboolExpr !== void 0) return stringboolExpr;
451
+ const errorMessage = schema["x-error-message"];
452
+ const requiredMessage = schema["x-required-message"];
453
+ const coerce = schema["x-coerce"] === true;
454
+ const baseErrorArg = zodBaseError(errorMessage, coerce ? void 0 : requiredMessage);
455
+ const patternMessage = schema["x-pattern-message"];
456
+ const patternErrorPart = zodErrorPart(patternMessage);
457
+ const minLengthMessage = schema["x-minLength-message"];
458
+ const minErrorPart = zodErrorPart(minLengthMessage);
459
+ const maxLengthMessage = schema["x-maxLength-message"];
460
+ const maxErrorPart = zodErrorPart(maxLengthMessage);
461
+ const fixedLengthErrorPart = zodErrorPart(minLengthMessage ?? maxLengthMessage);
462
+ const hash = hashBase(schema, baseErrorArg);
463
+ const formatName = schema.format?.toLowerCase();
464
+ const format = formatName !== void 0 ? formatCall(schema, formatName) : void 0;
465
+ const checks = formatName !== void 0 ? formatChecks(schema, formatName) : void 0;
466
+ const transformFormat = formatName !== void 0 ? TRANSFORM_FORMATS[formatName] : void 0;
467
+ const coercePrefix = coerce && !format && !hash ? "coerce." : "";
468
+ const formatOptions = format && formatName !== void 0 ? buildFormatOptions(schema, formatName) : [];
469
+ const baseCallArg = format ? mergeOptions(formatOptions, baseErrorArg) : baseErrorArg;
470
+ const formatBase = hash ?? (format ? `z.${format.replace(/\(\)$/u, `(${baseCallArg})`)}` : void 0);
471
+ const pattern = schema.pattern ? `.regex(${regexLiteral(schema.pattern)}${patternErrorPart})` : void 0;
472
+ const isFixedLength = hasFixedLength(schema);
473
+ const trim = schema["x-trim"] === true || transformFormat === ".trim()" ? ".trim()" : void 0;
474
+ const toLowerCase = schema["x-toLowerCase"] === true || transformFormat === ".toLowerCase()" ? ".toLowerCase()" : void 0;
475
+ const toUpperCase = schema["x-toUpperCase"] === true || transformFormat === ".toUpperCase()" ? ".toUpperCase()" : void 0;
476
+ const normalize = typeof schema["x-normalize"] === "string" ? `.normalize(${JSON.stringify(schema["x-normalize"])})` : void 0;
477
+ const startsWith = typeof schema["x-startsWith"] === "string" ? `.startsWith(${JSON.stringify(schema["x-startsWith"])})` : void 0;
478
+ const endsWith = typeof schema["x-endsWith"] === "string" ? `.endsWith(${JSON.stringify(schema["x-endsWith"])})` : void 0;
479
+ const includes = typeof schema["x-includes"] === "string" ? `.includes(${JSON.stringify(schema["x-includes"])})` : void 0;
480
+ const lowercaseValidate = schema["x-lowercase"] === true ? ".lowercase()" : void 0;
481
+ const uppercaseValidate = schema["x-uppercase"] === true ? ".uppercase()" : void 0;
482
+ const transforms = [
483
+ trim,
484
+ toLowerCase,
485
+ toUpperCase,
486
+ normalize
487
+ ].filter((v) => v !== void 0).join("");
488
+ const restChecks = [
489
+ checks,
490
+ startsWith,
491
+ endsWith,
492
+ includes,
493
+ pattern,
494
+ isFixedLength ? `.length(${schema.minLength}${fixedLengthErrorPart})` : void 0,
495
+ !isFixedLength && schema.minLength !== void 0 ? `.min(${schema.minLength}${minErrorPart})` : void 0,
496
+ !isFixedLength && schema.maxLength !== void 0 ? `.max(${schema.maxLength}${maxErrorPart})` : void 0,
497
+ lowercaseValidate,
498
+ uppercaseValidate
499
+ ].filter((v) => v !== void 0).join("");
500
+ if (formatBase === void 0) return `z.${coercePrefix}string(${baseCallArg})${transforms}${restChecks}`;
501
+ if (transforms !== "") return `z.string(${baseErrorArg})${transforms}.pipe(${formatBase}${restChecks})`;
502
+ return `${formatBase}${restChecks}`;
503
+ }
504
+ //#endregion
505
+ //#region src/generator/zod/zod.ts
506
+ /**
507
+ * Zod v4 issue codes, in the order `zod/v4/core/errors.d.ts` declares them. The
508
+ * `x-allOf-message` wrapper matches each in turn and replaces its message.
509
+ */
510
+ const ZOD_ISSUE_CODES = [
511
+ "invalid_type",
512
+ "too_big",
513
+ "too_small",
514
+ "invalid_format",
515
+ "not_multiple_of",
516
+ "unrecognized_keys",
517
+ "invalid_union",
518
+ "invalid_key",
519
+ "invalid_element",
520
+ "invalid_value",
521
+ "custom"
522
+ ];
523
+ /**
524
+ * The `not` predicate of an inner schema, as the source of a `(val) => ...` arrow, or
525
+ * `undefined` when the inner schema has none this generator can express.
526
+ */
527
+ function zodNotPredicate(inner) {
528
+ if (inner.$ref) return void 0;
529
+ const shared = notPredicate(inner, "val");
530
+ if (shared !== void 0) return shared;
531
+ if (Array.isArray(inner.enum)) return `(val) => !${JSON.stringify(inner.enum)}.includes(val)`;
532
+ if (inner.oneOf || inner.anyOf || inner.allOf) return `(val) => !${zod(inner)}.safeParse(val).success`;
533
+ }
534
+ function elementMessageWrap(inner, msg) {
535
+ return `(()=>{const Schema=${inner};return z.unknown().check((ctx)=>{const result=Schema.safeParse(ctx.value);if(!result.success){for(const issue of result.error.issues){if(issue.path.length>0){ctx.issues.push({...issue,message:${issueMessageExpression(msg)}})}else{ctx.issues.push(issue)}}}}).pipe(Schema)})()`;
536
+ }
537
+ /**
538
+ * Generate Zod schema code from JSON Schema.
539
+ *
540
+ * @example
541
+ * ```ts
542
+ * zod({ type: 'string' }, 'MySchema') // 'z.string()'
543
+ * ```
544
+ */
545
+ function zod(schema, rootName = DEFAULT_ROOT_NAME, isZod = false, options) {
546
+ if (hasParameterSerialization(options)) return parameter(schema, zod(schema, rootName, isZod, withoutParameterSerialization(options)), options);
547
+ const expression = node(schema, rootName, isZod, options);
548
+ if (!(isStringWireLocation(options?.paramIn) && schema["x-coerce"] !== false) || !isNullTextRead(schema)) return expression;
549
+ const nullFirst = isNullMatchedFirst(schema) ? expression : `${expression}.nullable()`;
550
+ return `z.preprocess(${wireNullText("val")},${nullFirst})`;
551
+ }
552
+ function node(schema, rootName, isZod, options) {
553
+ const isStringWireParam = isStringWireLocation(options?.paramIn);
554
+ const isWireCoerced = isStringWireParam && schema["x-coerce"] !== false;
555
+ const withForcedCoerce = (s) => isStringWireParam && s["x-coerce"] !== false ? {
556
+ ...s,
557
+ "x-coerce": true
558
+ } : s;
559
+ const codeExtOpts = options?.unsafeCodeExtensions === true ? { unsafeCodeExtensions: true } : {};
560
+ const zodWrap$1 = (zodStr, s) => zodWrap(zodStr, s, codeExtOpts);
561
+ const readonly = (v) => options?.readonly ? `${v}.readonly()` : v;
562
+ const wireArray = (v) => isStringWireParam ? `z.preprocess(${wireArrayOnce("val")},${v})` : v;
563
+ const literalInput = (values) => {
564
+ if (values.every((v) => typeof v === "number")) {
565
+ if (isInt64(schema)) return int64Input(isWireCoerced);
566
+ if (isWireCoerced) return "z.coerce.number()";
567
+ }
568
+ if (isWireCoerced && values.every((v) => typeof v === "boolean")) return "z.stringbool()";
569
+ };
570
+ const ref = (s, rn, iz) => {
571
+ if (s.$ref === void 0) return "z.any()";
572
+ const target = refTarget(s.$ref, rn, iz, options?.openapi);
573
+ if (target.kind === "lazy") return `z.lazy(() => ${target.name})`;
574
+ if (target.kind === "value") return target.name;
575
+ return target.kind === "unknown" ? "z.unknown()" : "z.any()";
576
+ };
577
+ if (schema.$ref) {
578
+ const items = itemsSchemaOf(schema.items);
579
+ if (schema.type === "array" && items?.$ref) return `z.array(${zodWrap$1(ref(items, rootName, isZod), items)})`;
580
+ return zodWrap$1(ref(schema, rootName, isZod), schema);
581
+ }
582
+ const impliedType = isWireCoerced ? impliedWireType(schema) : void 0;
583
+ if (impliedType !== void 0) return node({
584
+ ...schema,
585
+ type: impliedType
586
+ }, rootName, isZod, options);
587
+ if (schema.oneOf) {
588
+ if (schema.oneOf.length === 0) return zodWrap$1("z.any()", schema);
589
+ const schemas = schema.oneOf.map((s) => zod(s, rootName, isZod, options));
590
+ const oneOfMessage = schema["x-oneOf-message"];
591
+ const errorPart = zodErrorPart(oneOfMessage);
592
+ const discriminator = schema.discriminator?.propertyName;
593
+ const hasRefOrAllOf = schema.oneOf.some((s) => s.$ref !== void 0 || s.allOf !== void 0);
594
+ return zodWrap$1(discriminator && !hasRefOrAllOf ? `z.discriminatedUnion('${discriminator}',[${schemas.join(",")}]${errorPart})` : isWireCoerced ? `z.union([${schemas.join(",")}]${errorPart})` : `z.xor([${schemas.join(",")}]${errorPart})`, schema);
595
+ }
596
+ if (schema.anyOf) {
597
+ if (schema.anyOf.length === 0) return zodWrap$1("z.any()", schema);
598
+ const schemas = schema.anyOf.map((s) => zod(s, rootName, isZod, options));
599
+ const anyOfMessage = schema["x-implication-message"] ?? schema["x-anyOf-message"];
600
+ const errorPart = zodErrorPart(anyOfMessage);
601
+ return zodWrap$1(`z.union([${schemas.join(",")}]${errorPart})`, schema);
602
+ }
603
+ if (schema.allOf) {
604
+ if (schema.allOf.length === 0) return zodWrap$1("z.any()", schema);
605
+ const nullable = isNullable(schema) || schema.allOf.some(isNullTypeMember);
606
+ const defaultValue = schema.allOf.find(isDefaultOnlyMember)?.default;
607
+ const schemas = schema.allOf.filter((s) => !isShapelessMember(s)).map((s) => zod(s, rootName, isZod, options));
608
+ if (schemas.length === 0) return zodWrap$1("z.any()", {
609
+ ...schema,
610
+ nullable
611
+ });
612
+ const intersected = schemas.length === 1 ? schemas[0] : schemas.reduce((acc, s) => `z.intersection(${acc},${s})`);
613
+ const allOfMessage = schema["x-allOf-message"];
614
+ const baseResult = allOfMessage ? (() => {
615
+ const msgExpr = issueMessageExpression(allOfMessage);
616
+ const branches = ZOD_ISSUE_CODES.map((c, i) => `${i === 0 ? "" : "else "}if(issue.code==='${c}'){ctx.issues.push({...issue,input:issue.input,message:${msgExpr}})}`).join("");
617
+ return `(()=>{const Schema=${intersected};return z.unknown().check((ctx)=>{const result=Schema.safeParse(ctx.value);if(!result.success){for(const issue of result.error.issues){${branches}}}}).pipe(Schema)})()`;
618
+ })() : intersected;
619
+ const mergedDefault = defaultValue !== void 0 ? defaultValue : schema.default;
620
+ return zodWrap$1(baseResult, {
621
+ ...schema,
622
+ nullable,
623
+ ...mergedDefault !== void 0 && { default: mergedDefault }
624
+ });
625
+ }
626
+ if (schema.not) {
627
+ const notMessage = schema["x-not-message"];
628
+ const errorPart = zodErrorPart(notMessage);
629
+ const { not: inner, ...withoutNot } = schema;
630
+ if (typeof inner !== "object" || inner === null) return zodWrap$1("z.any()", schema);
631
+ const predicate = inner.$ref ? `(val) => !${ref(inner, "", false)}.safeParse(val).success` : zodNotPredicate(inner);
632
+ if (withoutNot.type !== void 0) {
633
+ const base = zod(withoutNot, rootName, isZod, options);
634
+ return predicate ? `${base}.refine(${predicate}${errorPart})` : base;
635
+ }
636
+ if (predicate) return zodWrap$1(`z.any().refine(${predicate}${errorPart})`, schema);
637
+ return zodWrap$1("z.any()", schema);
638
+ }
639
+ if (schema.const !== void 0) {
640
+ const value = schema.const;
641
+ const constMessage = schema["x-const-message"] ?? schema["x-error-message"];
642
+ const errorPart = zodErrorPart(constMessage);
643
+ const literal = typeof value === "number" && isInt64(schema) ? `z.literal(${value}n${errorPart})` : isPrimitive(value) ? `z.literal(${JSON.stringify(value)}${errorPart})` : `z.custom<${JSON.stringify(value)}>()`;
644
+ const input = literalInput([value]);
645
+ return zodWrap$1(input ? `${input}.pipe(${literal})` : literal, schema);
646
+ }
647
+ if (schema.enum) {
648
+ const values = schema.enum.filter((value) => value !== null);
649
+ const input = values.length > 0 ? literalInput(values) : void 0;
650
+ if (input === void 0) return zodWrap$1(_enum(schema), schema);
651
+ const hasNull = values.length < schema.enum.length;
652
+ const piped = `${input}.pipe(${_enum({
653
+ ...schema,
654
+ enum: values
655
+ })})`;
656
+ return zodWrap$1(hasNull && !isNullable(schema) ? `${piped}.nullable()` : piped, schema);
657
+ }
658
+ if (schema.properties) return readonly(zodWrap$1(object(schema, rootName, isZod, options), schema));
659
+ const types = normalizeTypes(schema.type);
660
+ const primitive = (t) => {
661
+ if (t === "string") return string(schema);
662
+ if (t === "number") return number(withForcedCoerce(schema));
663
+ if (t === "integer") return integer(withForcedCoerce(schema));
664
+ if (t !== "boolean") return void 0;
665
+ const errorMessage = schema["x-error-message"];
666
+ const errorArg = errorMessage ? zodError(errorMessage) : "";
667
+ if (isStringWireParam) return `z.stringbool(${errorArg ? `{error:${errorArg.replaceAll(/^{error:|}$/g, "")}}` : ""})`;
668
+ return `z.${schema["x-coerce"] === true ? "coerce." : ""}boolean(${errorArg})`;
669
+ };
670
+ if (isPrimitiveUnion(types, isWireCoerced)) return zodWrap$1(`z.union([${unionPrimitiveTypes(types, isWireCoerced).map(primitive).filter((m) => m !== void 0).join(",")}])`, schema);
671
+ for (const t of [
672
+ "string",
673
+ "number",
674
+ "integer",
675
+ "boolean"
676
+ ]) {
677
+ if (!types.includes(t)) continue;
678
+ const expression = primitive(t);
679
+ if (expression !== void 0) return zodWrap$1(expression, schema);
680
+ }
681
+ if (types.includes("array")) {
682
+ const errorMessage = schema["x-error-message"];
683
+ const baseError = zodErrorPart(errorMessage);
684
+ const lengthMessage = schema["x-length-message"];
685
+ const minItemsMessage = schema["x-minItems-message"] ?? lengthMessage;
686
+ const minError = zodErrorPart(minItemsMessage);
687
+ const maxItemsMessage = schema["x-maxItems-message"] ?? lengthMessage;
688
+ const maxError = zodErrorPart(maxItemsMessage);
689
+ const fixedItemsError = zodErrorPart(minItemsMessage ?? maxItemsMessage);
690
+ const uniqueMessage = schema["x-uniqueItems-message"];
691
+ const uniqueError = zodErrorPart(uniqueMessage);
692
+ if (schema.prefixItems?.length) {
693
+ const items = schema.prefixItems.map((s) => zod(s, rootName, isZod, options));
694
+ const u = schema.unevaluatedItems;
695
+ const unevaluatedItemsMessage = schema["x-unevaluatedItems-message"];
696
+ const unevaluatedItemsError = zodErrorPart(unevaluatedItemsMessage);
697
+ const rest = isSchemaObject(u) ? zod(u, rootName, isZod, options) : void 0;
698
+ const tupleExpr = `z.tuple(${rest ? `[${items.join(",")}],${rest}` : `[${items.join(",")}]`}${u === false && unevaluatedItemsMessage ? unevaluatedItemsError : baseError})`;
699
+ const prefixItemsMessage = schema["x-prefixItems-message"];
700
+ return readonly(zodWrap$1(wireArray(prefixItemsMessage ? elementMessageWrap(tupleExpr, prefixItemsMessage) : tupleExpr), schema));
701
+ }
702
+ const itemSchema = itemsSchemaOf(schema.items);
703
+ const item = itemSchema ? zod(itemSchema, rootName, isZod, options) : "z.any()";
704
+ const itemsMessage = schema["x-items-message"];
705
+ const arrayBase = `z.array(${item}${baseError})`;
706
+ const base = itemsMessage ? elementMessageWrap(arrayBase, itemsMessage) : arrayBase;
707
+ const unique = schema.uniqueItems === true ? `.refine((val)=>new Set(val).size===val.length${uniqueError})` : "";
708
+ const containsChain = (() => {
709
+ const c = schema.contains;
710
+ if (!c) return "";
711
+ const containsZod = zod(c, rootName, isZod, options);
712
+ const minC = schema.minContains;
713
+ const maxC = schema.maxContains;
714
+ const fallback = schema["x-contains-message"] ?? errorMessage;
715
+ const parts = [];
716
+ if (minC === void 0 && maxC === void 0) {
717
+ const containsArg = zodErrorPart(fallback);
718
+ parts.push(`.refine((val)=>{const Schema=${containsZod};return val.some((item)=>Schema.safeParse(item).success)}${containsArg})`);
719
+ } else {
720
+ const effectiveMin = minC ?? 1;
721
+ if (effectiveMin > 0) {
722
+ const minContainsMessage = schema["x-minContains-message"] ?? fallback;
723
+ const minContainsArg = zodErrorPart(minContainsMessage);
724
+ parts.push(`.refine((val)=>{const Schema=${containsZod};return val.filter((item)=>Schema.safeParse(item).success).length>=${effectiveMin}}${minContainsArg})`);
725
+ }
726
+ if (maxC !== void 0) {
727
+ const maxContainsMessage = schema["x-maxContains-message"] ?? fallback;
728
+ const maxContainsArg = zodErrorPart(maxContainsMessage);
729
+ parts.push(`.refine((val)=>{const Schema=${containsZod};return val.filter((item)=>Schema.safeParse(item).success).length<=${maxC}}${maxContainsArg})`);
730
+ }
731
+ }
732
+ return parts.join("");
733
+ })();
734
+ const { minItems, maxItems } = schema;
735
+ return readonly(zodWrap$1(wireArray(typeof minItems === "number" && typeof maxItems === "number" ? minItems === maxItems ? `${base}.length(${minItems}${fixedItemsError})${unique}${containsChain}` : `${base}.min(${minItems}${minError}).max(${maxItems}${maxError})${unique}${containsChain}` : typeof minItems === "number" ? `${base}.min(${minItems}${minError})${unique}${containsChain}` : typeof maxItems === "number" ? `${base}.max(${maxItems}${maxError})${unique}${containsChain}` : `${base}${unique}${containsChain}`), schema));
736
+ }
737
+ if (types.includes("object")) return readonly(zodWrap$1(object(schema, rootName, isZod, options), schema));
738
+ if (types.includes("date")) {
739
+ const errorMessage = schema["x-error-message"];
740
+ const errorArg = errorMessage ? zodError(errorMessage) : "";
741
+ return zodWrap$1(`z.${schema["x-coerce"] === true || isStringWireParam ? "coerce." : ""}date(${errorArg})`, schema);
742
+ }
743
+ if (types.length === 1 && types[0] === "null") {
744
+ const errorMessage = schema["x-error-message"];
745
+ return zodWrap$1(`z.null(${errorMessage ? zodError(errorMessage) : ""})`, schema);
746
+ }
747
+ return zodWrap$1("z.any()", schema);
748
+ }
749
+ //#endregion
750
+ //#region src/generator/zod/index.ts
751
+ /**
752
+ * A whole JSON Schema document as a Zod module: imports, `$defs` in dependency order,
753
+ * the root export, and the inferred type.
754
+ */
755
+ function schemaToZod(schema, options) {
756
+ const exportType = options?.exportType ?? true;
757
+ const emitOptions = emitOptionsOf(options);
758
+ const codeExtensionsPresent = emitOptions.unsafeCodeExtensions === true && findCodeExtensionKeysInSchema(schema).length > 0;
759
+ const toName = schemaNamer(emitOptions.openapi);
760
+ const plan = planDocument(schema, rootNameOf(schema, toName));
761
+ const { rootName } = plan;
762
+ const needsTypeDef = plan.hasDefinitions || hasRootSelfReference(schema);
763
+ const typeDefsCode = needsTypeDef ? [`type _${rootName} = ${type(plan.root, rootName)}`, renderDefinitions(plan, toName, (def, name) => `type _${name} = ${type(def, name)}`)].filter(Boolean).join("\n\n") : "";
764
+ const schemaDefsCode = renderDefinitions(plan, toName, (def, name) => `const ${name}: z.ZodType<_${name}> = ${zod(def, name, true, emitOptions)}`);
765
+ const rootSchema = zod(plan.root, rootName, true, emitOptions);
766
+ const rootExport = needsTypeDef ? `export const ${rootName}: z.ZodType<_${rootName}> = ${rootSchema}` : `export const ${rootName} = ${rootSchema}`;
767
+ return [
768
+ ...codeExtensionsPresent ? [UNSAFE_GENERATED_MARKER] : [],
769
+ `import * as z from 'zod'`,
770
+ typeDefsCode,
771
+ schemaDefsCode,
772
+ rootExport,
773
+ ...exportType ? [`export type ${rootName} = z.infer<typeof ${rootName}>`] : []
774
+ ].filter(Boolean).join("\n\n");
775
+ }
776
+ //#endregion
777
+ export { zod as n, schemaToZod as t };