schema-truth 0.0.0-stage → 0.8.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.
Files changed (45) hide show
  1. package/README.md +143 -2
  2. package/dist/ajv-DS9gtNZC.js +105 -0
  3. package/dist/ajv.d.ts +24 -0
  4. package/dist/ajv.js +1 -0
  5. package/dist/arktype-CRZ8vXZ5.js +803 -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-eAY8LqwP.js +124 -0
  23. package/dist/effect-BkWovUi3.js +678 -0
  24. package/dist/effect.d.ts +12 -0
  25. package/dist/effect.js +1 -0
  26. package/dist/helper-CbeedY35.js +1798 -0
  27. package/dist/index-DYzAccyT.d.ts +69 -0
  28. package/dist/index-G7UqNQ4w.d.ts +603 -0
  29. package/dist/index.d.ts +332 -0
  30. package/dist/index.js +10 -0
  31. package/dist/parser-CyJ2auea.js +36 -0
  32. package/dist/typebox-wYeJqy7T.js +563 -0
  33. package/dist/typebox.d.ts +21 -0
  34. package/dist/typebox.js +1 -0
  35. package/dist/utils-Bky98UmP.js +1146 -0
  36. package/dist/valibot-DQUEDYKt.js +705 -0
  37. package/dist/valibot.d.ts +9 -0
  38. package/dist/valibot.js +1 -0
  39. package/dist/yup-BMpa9Co1.js +92 -0
  40. package/dist/yup.d.ts +17 -0
  41. package/dist/yup.js +1 -0
  42. package/dist/zod-Dq9LtqPL.js +816 -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,705 @@
1
+ import { At as UNSAFE_GENERATED_MARKER, B as isSchemaObject, F as isPrimitive, H as isStringWireLocation, M as isNullable, N as isObjectPrototypeProperty, S as hasFixedLength, T as hasType, V as isShapelessMember, X as DEFAULT_ROOT_NAME, at as INTEGER_TEXT_PATTERN, b as hasConditional, c as normalizeTypes, f as valibotError, j as isNullTypeMember, k as isDefaultOnlyMember, o as issueMessageExpression, p as valibotErrorPart, pt as NUMBER_RANGES, s as makeSafeKey, x as hasFixedItemCount, y as hasCombinator } from "./utils-Bky98UmP.js";
2
+ import { B as emitOptionsOf, C as isPrimitiveUnion, D as stringboolTruthyPattern, E as stringboolPattern, F as jsLiteral, G as schemaNamer, H as planDocument, J as isOptionalByDefault, M as formatPattern, N as regexSource, O as unionPrimitiveTypes, Q as findCodeExtensionKeysInSchema, S as isNullTextRead, T as ownProperties, U as renderDefinitions, W as rootNameOf, Y as itemsSchemaOf, at as regexLiteral, b as integerWirePattern, c as withPolymorphicBases, d as propertyEmitOptions, et as constraintMessage, f as withoutParameterSerialization, g as hoistNestedRefs, h as valueListLiteral, i as isEvaluatedKeyExpression, j as wireNumericKind, k as wireArrayOnce, l as hasParameterSerialization, m as notPredicate, n as valibotWrap, nt as foldAllOfMembers, o as typeDeclaration, p as isBigintFormat, q as hasRootSelfReference, r as evaluatedProperties, rt as isKeywordOnlyMember, s as refTarget, tt as constraintPredicate, u as parameterReaders, w as numberWirePattern, y as impliedWireType, z as definitionsOf } from "./helper-CbeedY35.js";
3
+ //#region src/generator/valibot/type.ts
4
+ /** The TypeScript type declared beside a recursive Valibot schema: its output type. */
5
+ function type(schema, rootName = DEFAULT_ROOT_NAME) {
6
+ return typeDeclaration(schema, {
7
+ inferRoot: (name) => `v.InferOutput<typeof ${name}>`,
8
+ readonly: false
9
+ }, rootName);
10
+ }
11
+ //#endregion
12
+ //#region src/generator/valibot/number.ts
13
+ /** The `v.minValue` / `v.maxValue` / `v.gtValue` / `v.ltValue` / `v.multipleOf` actions of a numeric node. */
14
+ function numberActions(schema, lit = (n) => `${n}`) {
15
+ const minimumMessage = schema["x-minimum-message"];
16
+ const minErrorPart = valibotErrorPart(minimumMessage);
17
+ const maximumMessage = schema["x-maximum-message"];
18
+ const maxErrorPart = valibotErrorPart(maximumMessage);
19
+ const exMinMessage = schema["x-exclusiveMinimum-message"];
20
+ const exMinErrorPart = valibotErrorPart(exMinMessage);
21
+ const exMaxMessage = schema["x-exclusiveMaximum-message"];
22
+ const exMaxErrorPart = valibotErrorPart(exMaxMessage);
23
+ const multipleOfMessage = schema["x-multipleOf-message"];
24
+ const multipleOfErrorPart = valibotErrorPart(multipleOfMessage);
25
+ return [
26
+ (() => {
27
+ if (schema.minimum !== void 0) return schema.exclusiveMinimum === true ? `v.gtValue(${lit(schema.minimum)}${exMinErrorPart})` : `v.minValue(${lit(schema.minimum)}${minErrorPart})`;
28
+ if (typeof schema.exclusiveMinimum === "number") return `v.gtValue(${lit(schema.exclusiveMinimum)}${exMinErrorPart})`;
29
+ })(),
30
+ (() => {
31
+ if (schema.maximum !== void 0) return schema.exclusiveMaximum === true ? `v.ltValue(${lit(schema.maximum)}${exMaxErrorPart})` : `v.maxValue(${lit(schema.maximum)}${maxErrorPart})`;
32
+ if (typeof schema.exclusiveMaximum === "number") return `v.ltValue(${lit(schema.exclusiveMaximum)}${exMaxErrorPart})`;
33
+ })(),
34
+ schema.multipleOf !== void 0 ? `v.multipleOf(${lit(schema.multipleOf)}${multipleOfErrorPart})` : void 0
35
+ ].filter((v) => v !== void 0);
36
+ }
37
+ /** The `v.minValue` / `v.maxValue` pair of a fixed-width numeric `format`, if it has one. */
38
+ function rangeActions(format) {
39
+ const range = format === void 0 ? void 0 : NUMBER_RANGES[format];
40
+ if (range === void 0) return [];
41
+ return [`v.minValue(${range.minimum})`, `v.maxValue(${range.maximum})`];
42
+ }
43
+ /**
44
+ * The Valibot schema of a number node. On the string wire the text has to match the JSON
45
+ * number grammar before `Number` reads it, then it is checked finite; `float` / `float32`
46
+ * carries its range.
47
+ */
48
+ function number(schema, options) {
49
+ const errorMessage = schema["x-error-message"];
50
+ const requiredMessage = schema["x-required-message"];
51
+ const baseErrorArg = errorMessage ? valibotError(errorMessage) : requiredMessage ? valibotError(requiredMessage) : "";
52
+ const isFloat32 = schema.format === "float" || schema.format === "float32";
53
+ const actions = [
54
+ ...options?.wire === true ? ["v.finite()"] : [],
55
+ ...rangeActions(isFloat32 ? "float32" : void 0),
56
+ ...numberActions(schema)
57
+ ];
58
+ const base = `v.number(${baseErrorArg})`;
59
+ if (options?.wire === true) {
60
+ const regexError = baseErrorArg === "" ? "" : `,${baseErrorArg}`;
61
+ return `v.pipe(v.string(),v.regex(${numberWirePattern()}${regexError}),v.transform((input)=>Number(input)),${base},${actions.join(",")})`;
62
+ }
63
+ if (actions.length > 0) return `v.pipe(${base},${actions.join(",")})`;
64
+ return errorMessage ? base : "v.number()";
65
+ }
66
+ //#endregion
67
+ //#region src/generator/valibot/integer.ts
68
+ /** Whether a node is a 64-bit integer: a value beyond 2^53 that is read as a bigint. */
69
+ function isInt64(schema) {
70
+ return schema.format === "int64" || schema.format === "uint64";
71
+ }
72
+ /**
73
+ * The pipe that reads a 64-bit integer into a bigint ahead of its checks. On the string
74
+ * wire the text is a sign and digits; in a JSON body the value is a bigint, a safe-integer
75
+ * number, or the string of digits that is the only lossless way to carry a larger one.
76
+ */
77
+ function int64Input(isWire, baseErrorArg = "") {
78
+ const digits = regexSource(INTEGER_TEXT_PATTERN);
79
+ if (isWire) return [
80
+ `v.string(${baseErrorArg})`,
81
+ `v.regex(${digits})`,
82
+ "v.transform((input)=>BigInt(input))"
83
+ ];
84
+ return [`v.union([v.bigint(),v.pipe(v.number(),v.integer()),v.pipe(v.string(),v.regex(${digits}))]${baseErrorArg ? `,${baseErrorArg}` : ""})`, "v.transform((input)=>BigInt(input))"];
85
+ }
86
+ /**
87
+ * The Valibot schema of an integer node. `int64` / `uint64` are bigints wherever they
88
+ * come from, `bigint` is one too, `int32` / `uint32` carry their range, and on the
89
+ * string wire the text has to match the integer grammar before `Number` reads it, and is
90
+ * then checked a safe integer.
91
+ */
92
+ function integer(schema, options) {
93
+ const isWire = options?.wire === true;
94
+ const errorMessage = schema["x-error-message"];
95
+ const requiredMessage = schema["x-required-message"];
96
+ const baseErrorArg = errorMessage ? valibotError(errorMessage) : requiredMessage ? valibotError(requiredMessage) : "";
97
+ if (schema.format === "bigint") {
98
+ const actions = numberActions(schema, (n) => `BigInt(${n})`);
99
+ const base = `v.bigint(${baseErrorArg})`;
100
+ const items = isWire ? [
101
+ "v.string()",
102
+ `v.regex(${regexSource(INTEGER_TEXT_PATTERN)})`,
103
+ "v.transform((input)=>BigInt(input))",
104
+ base
105
+ ] : [base];
106
+ if (items.length === 1 && actions.length === 0) return errorMessage ? base : "v.bigint()";
107
+ return `v.pipe(${[...items, ...actions].join(",")})`;
108
+ }
109
+ if (isInt64(schema)) {
110
+ const actions = [...rangeActions(schema.format), ...numberActions(schema, (n) => `${n}n`)];
111
+ return `v.pipe(${[...int64Input(isWire, baseErrorArg), ...actions].join(",")})`;
112
+ }
113
+ const actions = [
114
+ isWire ? `v.safeInteger(${errorMessage ? baseErrorArg : ""})` : `v.integer(${errorMessage ? baseErrorArg : ""})`,
115
+ ...rangeActions(schema.format),
116
+ ...numberActions(schema)
117
+ ];
118
+ const regexError = baseErrorArg === "" ? "" : `,${baseErrorArg}`;
119
+ return `v.pipe(${[
120
+ ...isWire ? [
121
+ "v.string()",
122
+ `v.regex(${integerWirePattern()}${regexError})`,
123
+ "v.transform((input)=>Number(input))"
124
+ ] : [],
125
+ `v.number(${baseErrorArg})`,
126
+ ...actions
127
+ ].join(",")})`;
128
+ }
129
+ //#endregion
130
+ //#region src/generator/valibot/enum.ts
131
+ function lit(v, isBigint) {
132
+ if (v === null) return "null";
133
+ if (typeof v === "string") return `'${v.replaceAll("'", "\\'")}'`;
134
+ if (typeof v === "number" && isBigint) return `${v}n`;
135
+ if (typeof v === "number" || typeof v === "boolean") return String(v);
136
+ return JSON.stringify(v) ?? "null";
137
+ }
138
+ /**
139
+ * Generates a Valibot enum schema. String enums map to `v.picklist`,
140
+ * number/integer/boolean enums to `v.union([v.literal(...), ...])`,
141
+ * array enums to `v.tuple` or `v.union`, single values to `v.literal`. The members of
142
+ * an int64 / uint64 enum are bigint literals, as the value they match is.
143
+ *
144
+ * `x-error-message` (whole-enum) is applied **only to the outermost
145
+ * wrapper**. Inner v.literal entries inside a wrapper never receive a
146
+ * duplicate `error:` arg — the outer wrapper already shadows inner
147
+ * messages on validation failure.
148
+ *
149
+ * Per-literal `x-enum-error-messages` was removed entirely: a rejected
150
+ * value by definition isn't in the enum, so a per-literal branch can
151
+ * never match. Whole-enum messages come from `x-error-message`;
152
+ * finer-grained business rules belong in handler code, not the schema.
153
+ */
154
+ function _enum(schema) {
155
+ if (!schema.enum || schema.enum.length === 0) return "v.any()";
156
+ const isBigint = isInt64(schema);
157
+ const errorMessage = schema["x-enum-message"] ?? schema["x-error-message"];
158
+ const errorArg = valibotErrorPart(errorMessage);
159
+ const litSchema = (v, errPart) => {
160
+ if (v === null) return `v.null(${errPart.replace(/^,/, "")})`;
161
+ if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") return `v.literal(${lit(v, isBigint)}${errPart})`;
162
+ return `v.custom<${JSON.stringify(v)}>((input) => JSON.stringify(input) === ${JSON.stringify(JSON.stringify(v))}${errPart})`;
163
+ };
164
+ const innerLit = (v) => litSchema(v, "");
165
+ const outerLit = (v) => litSchema(v, errorArg);
166
+ const innerTuple = (arr) => `v.tuple([${arr.map(innerLit).join(",")}])`;
167
+ const outerTuple = (arr) => `v.tuple([${arr.map(innerLit).join(",")}]${errorArg})`;
168
+ if (hasType(schema, "number") || hasType(schema, "integer") || hasType(schema, "boolean")) return schema.enum.length > 1 ? `v.union([${schema.enum.map(innerLit).join(",")}]${errorArg})` : outerLit(schema.enum[0]);
169
+ if (hasType(schema, "array")) {
170
+ if (schema.enum.length === 1 && Array.isArray(schema.enum[0])) return outerTuple(schema.enum[0]);
171
+ return `v.union([${schema.enum.map((v) => Array.isArray(v) ? innerTuple(v) : innerLit(v)).join(",")}]${errorArg})`;
172
+ }
173
+ if (schema.enum.every((v) => typeof v === "string")) {
174
+ if (schema.enum.length > 1) return `v.picklist(${JSON.stringify(schema.enum)}${errorArg})`;
175
+ return outerLit(schema.enum[0]);
176
+ }
177
+ if (schema.enum.length > 1) return `v.union([${schema.enum.map(innerLit).join(",")}]${errorArg})`;
178
+ return outerLit(schema.enum[0]);
179
+ }
180
+ //#endregion
181
+ //#region src/generator/valibot/object.ts
182
+ /**
183
+ * Generate a Valibot object schema for a JSON Schema object node.
184
+ *
185
+ * Dispatches `additionalProperties` to `v.looseObject` (true), `v.strictObject`
186
+ * (false), `v.record` (Schema), or default `v.object`. Combinators
187
+ * (oneOf/anyOf/allOf/not) delegate to the main `valibot` entry. JSON Schema
188
+ * 2020-12 keywords (`minProperties`, `maxProperties`, `propertyNames`,
189
+ * `patternProperties`, `dependentRequired`) are emitted as `v.check(...)`
190
+ * actions composed via `v.pipe(...)`.
191
+ *
192
+ * NOTE: `v.pipe(base, v.readonly())` is appended by the dispatcher
193
+ * (`valibot.ts:readonly`), so this function does NOT add it itself.
194
+ */
195
+ function object(schema, rootName, isValibot, options) {
196
+ if (hasCombinator(schema)) return valibot(schema, rootName, isValibot, options);
197
+ const errorMessage = schema["x-error-message"];
198
+ const errorArg = valibotErrorPart(errorMessage);
199
+ const minimumMessage = schema["x-minProperties-message"];
200
+ const minErrorArg = valibotErrorPart(minimumMessage);
201
+ const maximumMessage = schema["x-maxProperties-message"];
202
+ const maxErrorArg = valibotErrorPart(maximumMessage);
203
+ const patternPropsMessage = schema["x-patternProperties-message"];
204
+ const patternErrorArg = valibotErrorPart(patternPropsMessage);
205
+ const propNamesMessage = schema["x-propertyNames-message"];
206
+ const propNamesErrorArg = valibotErrorPart(propNamesMessage);
207
+ const depReqMessage = schema["x-dependentRequired-message"];
208
+ const depReqErrorArg = depReqMessage ? `,${valibotError(depReqMessage)}` : errorArg;
209
+ const depSchMessage = schema["x-dependentSchemas-message"];
210
+ const depSchErrorArg = depSchMessage ? `,${valibotError(depSchMessage)}` : errorArg;
211
+ const addlPropsMessage = schema["x-additionalProperties-message"];
212
+ const unevalPropsMessage = schema.unevaluatedProperties === false ? schema["x-unevaluatedProperties-message"] : void 0;
213
+ const strictExtrasMessage = addlPropsMessage ?? unevalPropsMessage;
214
+ const propertyNamesCheck = () => {
215
+ if (schema.propertyNames?.pattern) return `v.check((input)=>Object.keys(input).every((key)=>new RegExp(${JSON.stringify(schema.propertyNames.pattern)}).test(key))${propNamesErrorArg})`;
216
+ if (schema.propertyNames?.enum) return `v.check((input)=>Object.keys(input).every((key)=>${JSON.stringify(schema.propertyNames.enum)}.includes(key))${propNamesErrorArg})`;
217
+ return "";
218
+ };
219
+ const patternPropertiesChecks = () => schema.patternProperties ? Object.entries(schema.patternProperties).map(([pattern, propSchema]) => {
220
+ const s = valibot(propSchema, rootName, isValibot, options);
221
+ return `v.check((input)=>Object.entries(input).every(([key,value])=>!new RegExp(${JSON.stringify(pattern)}).test(key)||v.safeParse(${s},value).success)${patternErrorArg})`;
222
+ }) : [];
223
+ if (typeof schema.additionalProperties === "object") {
224
+ const record = `v.record(v.string(),${valibot(schema.additionalProperties, rootName, isValibot, options)})`;
225
+ const actions = [propertyNamesCheck(), ...patternPropertiesChecks()].filter((a) => a !== "");
226
+ return actions.length > 0 ? `v.pipe(${record},${actions.join(",")})` : record;
227
+ }
228
+ if (!schema.properties) {
229
+ if (schema.patternProperties) {
230
+ const record = `v.record(v.string(),v.unknown())`;
231
+ const actions = [propertyNamesCheck(), ...patternPropertiesChecks()].filter((a) => a !== "");
232
+ return actions.length > 0 ? `v.pipe(${record},${actions.join(",")})` : record;
233
+ }
234
+ if (schema.additionalProperties === true) return "v.any()";
235
+ return "v.object({})";
236
+ }
237
+ const conditionalKeysReferenced = hasConditional(schema);
238
+ const objectKind = schema.additionalProperties === true ? "looseObject" : schema.additionalProperties === false || schema.unevaluatedProperties === false ? "strictObject" : conditionalKeysReferenced ? "looseObject" : "object";
239
+ const required = new Set(schema.required);
240
+ const hasOwnDefault = Object.values(schema.properties).some((propSchema) => isOptionalByDefault(propSchema, options?.definitions));
241
+ const props = Object.entries(schema.properties).map(([key, propSchema]) => {
242
+ const parsed = valibot(propSchema, rootName, isValibot, propertyEmitOptions(key, propSchema, options) ?? options);
243
+ if (!parsed) return null;
244
+ const safeKey = makeSafeKey(key);
245
+ return required.has(key) || isOptionalByDefault(propSchema, options?.definitions) ? `${safeKey}:${parsed}` : `${safeKey}:v.optional(${parsed})`;
246
+ }).filter((p) => p !== null);
247
+ const strictMessageArg = objectKind === "strictObject" ? valibotErrorPart(strictExtrasMessage) : "";
248
+ const rawBase = required.size === 0 && !hasOwnDefault && props.every((p) => p.includes("v.optional(")) ? `v.partial(v.${objectKind}({${props.map((p) => p.replace(/^(.+?):v\.optional\((.+)\)$/u, "$1:$2")).join(",")}}${strictMessageArg}))` : `v.${objectKind}({${props.join(",")}}${strictMessageArg})`;
249
+ const propsMessage = schema["x-properties-message"];
250
+ const partialBase = propsMessage ? (() => {
251
+ const msgExpr = issueMessageExpression(propsMessage);
252
+ return `v.pipe(v.unknown(),v.rawCheck(({dataset,addIssue})=>{if(!dataset.typed)return;const result=v.safeParse(${rawBase},dataset.value);if(!result.success){for(const issue of result.issues){if(issue.path&&issue.path.length>0){addIssue({message:${msgExpr},path:issue.path})}else{addIssue(issue)}}}}))`;
253
+ })() : rawBase;
254
+ const minPropertiesCheck = typeof schema.minProperties === "number" ? `v.check((input)=>Object.keys(input).length>=${schema.minProperties}${minErrorArg})` : "";
255
+ const maxPropertiesCheck = typeof schema.maxProperties === "number" ? `v.check((input)=>Object.keys(input).length<=${schema.maxProperties}${maxErrorArg})` : "";
256
+ const dependentRequiredChecks = schema.dependentRequired ? Object.entries(schema.dependentRequired).map(([key, deps]) => {
257
+ return `v.check((input)=>!('${key}' in input)||(${deps.map((d) => `'${d}' in input`).join("&&")})${depReqErrorArg})`;
258
+ }) : [];
259
+ const dependentSchemasChecks = schema.dependentSchemas ? Object.entries(schema.dependentSchemas).map(([key, subSchema]) => {
260
+ return `v.check((input)=>!('${key}' in input)||v.safeParse(${valibot(subSchema, rootName, isValibot, options)},input).success${depSchErrorArg})`;
261
+ }) : [];
262
+ const additionalPropertiesCheck = "";
263
+ const ifThenElseChecks = (() => {
264
+ if (!schema.if) return [];
265
+ const ifSchema = valibot(schema.if, rootName, isValibot, options);
266
+ const thenSchema = schema.then ? valibot(schema.then, rootName, isValibot, options) : void 0;
267
+ const elseSchema = schema.else ? valibot(schema.else, rootName, isValibot, options) : void 0;
268
+ if (!thenSchema && !elseSchema) return [];
269
+ const ifMessage = schema["x-if-message"];
270
+ const thenMessage = schema["x-then-message"] ?? ifMessage;
271
+ const elseMessage = schema["x-else-message"] ?? ifMessage;
272
+ const parts = [];
273
+ if (thenSchema) {
274
+ const arg = valibotErrorPart(thenMessage);
275
+ parts.push(`v.check((input)=>!v.safeParse(${ifSchema},input).success||v.safeParse(${thenSchema},input).success${arg})`);
276
+ }
277
+ if (elseSchema) {
278
+ const arg = valibotErrorPart(elseMessage);
279
+ parts.push(`v.check((input)=>v.safeParse(${ifSchema},input).success||v.safeParse(${elseSchema},input).success${arg})`);
280
+ }
281
+ return parts;
282
+ })();
283
+ const actions = [
284
+ minPropertiesCheck,
285
+ maxPropertiesCheck,
286
+ propertyNamesCheck(),
287
+ ...patternPropertiesChecks(),
288
+ ...dependentRequiredChecks,
289
+ ...dependentSchemasChecks,
290
+ additionalPropertiesCheck,
291
+ ...ifThenElseChecks
292
+ ].filter((a) => a !== "");
293
+ const objectExpr = actions.length > 0 ? `v.pipe(${partialBase},${actions.join(",")})` : partialBase;
294
+ const hasInheritedName = Object.keys(schema.properties).some(isObjectPrototypeProperty);
295
+ return isStringWireLocation(options?.paramIn) && hasInheritedName ? `v.pipe(v.unknown(),v.transform(${ownProperties("input")}),${objectExpr})` : objectExpr;
296
+ }
297
+ //#endregion
298
+ //#region src/generator/valibot/string.ts
299
+ /** The formats Valibot checks with an action of its own, keyed by the lower-cased format. */
300
+ const FORMAT_ACTION = {
301
+ email: "v.email()",
302
+ emoji: "v.emoji()",
303
+ base64: "v.base64()",
304
+ nanoid: "v.nanoid()",
305
+ cuid2: "v.cuid2()",
306
+ ulid: "v.ulid()",
307
+ mac: "v.mac()",
308
+ hex: "v.hexadecimal()",
309
+ ipv4: "v.ipv4()",
310
+ ipv6: "v.ipv6()",
311
+ ip: "v.ip()",
312
+ uri: "v.url()",
313
+ url: "v.url()",
314
+ httpurl: "v.url()",
315
+ creditcard: "v.creditCard()"
316
+ };
317
+ /** The formats that normalise the value rather than check it, keyed by the lower-cased format. */
318
+ const TRANSFORM_FORMATS = {
319
+ trim: "v.trim()",
320
+ tolowercase: "v.toLowerCase()",
321
+ touppercase: "v.toUpperCase()"
322
+ };
323
+ /** An `http` / `https` URL, which `v.url()` alone does not require. */
324
+ const HTTP_URL_PATTERN = String.raw`/^https?:\/\//`;
325
+ /**
326
+ * The actions that check a string `format`: Valibot's own where it has one, otherwise the
327
+ * regex every target shares. `[]` for a format with neither.
328
+ */
329
+ function formatActions(schema, format, errorArg) {
330
+ const withError = (action) => errorArg ? action.replace(/\(\)$/u, `(${errorArg})`) : action;
331
+ const action = FORMAT_ACTION[format];
332
+ if (action !== void 0) return format === "httpurl" ? [withError(action), `v.regex(${HTTP_URL_PATTERN}${errorArg ? `,${errorArg}` : ""})`] : [withError(action)];
333
+ const pattern = formatPattern(schema, format);
334
+ return pattern === void 0 ? [] : [`v.regex(${pattern}${errorArg ? `,${errorArg}` : ""})`];
335
+ }
336
+ /**
337
+ * The Valibot schema of a string node. `minLength` / `maxLength` count code points, as
338
+ * JSON Schema does, so they are `v.minCodePoints` / `v.maxCodePoints` / `v.codePoints`
339
+ * rather than `v.minLength`, which counts UTF-16 units, or `v.minGraphemes`, which
340
+ * counts user-perceived characters.
341
+ */
342
+ function string(schema) {
343
+ const errorMessage = schema["x-error-message"];
344
+ const requiredMessage = schema["x-required-message"];
345
+ const baseErrorArg = errorMessage ? valibotError(errorMessage) : requiredMessage ? valibotError(requiredMessage) : "";
346
+ const formatName = schema.format?.toLowerCase();
347
+ if (formatName === "binary") return errorMessage ? `v.file(${baseErrorArg})` : "v.file()";
348
+ const patternMessage = schema["x-pattern-message"];
349
+ const patternErrorPart = valibotErrorPart(patternMessage);
350
+ const lengthMessage = schema["x-minLength-message"] ?? schema["x-maxLength-message"];
351
+ const lengthErrorPart = valibotErrorPart(lengthMessage);
352
+ const minimumMessage = schema["x-minLength-message"];
353
+ const minErrorPart = valibotErrorPart(minimumMessage);
354
+ const maximumMessage = schema["x-maxLength-message"];
355
+ const maxErrorPart = valibotErrorPart(maximumMessage);
356
+ const format = formatName === void 0 ? [] : formatActions(schema, formatName, errorMessage ? baseErrorArg : "");
357
+ const transformFormat = formatName === void 0 ? void 0 : TRANSFORM_FORMATS[formatName];
358
+ const isFixedLength = hasFixedLength(schema);
359
+ const actions = [
360
+ schema["x-trim"] === true || transformFormat === "v.trim()" ? "v.trim()" : void 0,
361
+ schema["x-toLowerCase"] === true || transformFormat === "v.toLowerCase()" ? "v.toLowerCase()" : void 0,
362
+ schema["x-toUpperCase"] === true || transformFormat === "v.toUpperCase()" ? "v.toUpperCase()" : void 0,
363
+ typeof schema["x-normalize"] === "string" ? `v.normalize(${JSON.stringify(schema["x-normalize"])})` : void 0,
364
+ typeof schema["x-startsWith"] === "string" ? `v.startsWith(${JSON.stringify(schema["x-startsWith"])})` : void 0,
365
+ typeof schema["x-endsWith"] === "string" ? `v.endsWith(${JSON.stringify(schema["x-endsWith"])})` : void 0,
366
+ typeof schema["x-includes"] === "string" ? `v.includes(${JSON.stringify(schema["x-includes"])})` : void 0,
367
+ ...format,
368
+ schema.pattern ? `v.regex(${regexLiteral(schema.pattern)}${patternErrorPart})` : void 0,
369
+ isFixedLength ? `v.codePoints(${schema.minLength}${lengthErrorPart})` : void 0,
370
+ !isFixedLength && schema.minLength !== void 0 ? `v.minCodePoints(${schema.minLength}${minErrorPart})` : void 0,
371
+ !isFixedLength && schema.maxLength !== void 0 ? `v.maxCodePoints(${schema.maxLength}${maxErrorPart})` : void 0
372
+ ].filter((v) => v !== void 0);
373
+ if (actions.length > 0) return `v.pipe(v.string(${baseErrorArg}),${actions.join(",")})`;
374
+ return errorMessage ? `v.string(${baseErrorArg})` : "v.string()";
375
+ }
376
+ //#endregion
377
+ //#region src/generator/valibot/valibot.ts
378
+ /** `inner` with `prefix` ahead of it in one pipe: an existing pipe is opened, not nested. */
379
+ function prependPipe(prefix, inner) {
380
+ if (inner.startsWith("v.pipe(") && inner.endsWith(")")) {
381
+ const body = inner.slice(7, -1);
382
+ return `v.pipe(${prefix.join(",")},${body})`;
383
+ }
384
+ return `v.pipe(${prefix.join(",")},${inner})`;
385
+ }
386
+ /** `inner` with `actions` after it in one pipe: an existing pipe is opened, not nested. */
387
+ function appendPipe(inner, actions) {
388
+ if (inner.startsWith("v.pipe(") && inner.endsWith(")")) return `v.pipe(${inner.slice(7, -1)},${actions.join(",")})`;
389
+ return `v.pipe(${inner},${actions.join(",")})`;
390
+ }
391
+ /**
392
+ * `inner` read after `readers`, each a `(input) => ...` arrow over the raw value, in one
393
+ * pipe: a schema may follow a transform, so an inner pipe is opened rather than nested.
394
+ */
395
+ function preprocess(readers, inner) {
396
+ if (readers.length === 0) return inner;
397
+ return prependPipe(["v.unknown()", ...readers.map((reader) => `v.transform(${reader})`)], inner);
398
+ }
399
+ /** The pipe items reading the boolean spellings of the wire into a boolean, as `z.stringbool()` reads them. */
400
+ function stringboolItems(errorArg) {
401
+ return [
402
+ `v.string(${errorArg})`,
403
+ `v.regex(${stringboolPattern()}${errorArg ? `,${errorArg}` : ""})`,
404
+ `v.transform((input)=>${stringboolTruthyPattern()}.test(input))`
405
+ ];
406
+ }
407
+ /** The boolean spellings of the wire, read into a boolean as `z.stringbool()` reads them. */
408
+ function stringbool(errorArg) {
409
+ return `v.pipe(${stringboolItems(errorArg).join(",")})`;
410
+ }
411
+ function elementMessageWrap(inner, msg) {
412
+ return `v.pipe(v.unknown(),v.rawCheck(({dataset,addIssue})=>{if(!dataset.typed)return;const result=v.safeParse(${inner},dataset.value);if(!result.success){for(const issue of result.issues){if(issue.path&&issue.path.length>0){addIssue({message:${issueMessageExpression(msg)},path:issue.path})}else{addIssue(issue)}}}}))`;
413
+ }
414
+ /**
415
+ * An `allOf` with `unevaluatedProperties` beside it: the members' objects strip what they
416
+ * do not declare, so the keys no member evaluates are checked on the input before it is
417
+ * parsed. `inner` as given when the keyword is absent or every key is evaluated.
418
+ */
419
+ function unevaluatedPropertiesCheck(inner, schema, rootName, isValibot, options) {
420
+ const unevaluated = schema.unevaluatedProperties;
421
+ if (unevaluated !== false && (typeof unevaluated !== "object" || unevaluated === null)) return inner;
422
+ const evaluated = evaluatedProperties(schema, options?.definitions);
423
+ if (evaluated === void 0) return inner;
424
+ const isEvaluated = isEvaluatedKeyExpression(evaluated, "k");
425
+ const message = schema["x-unevaluatedProperties-message"];
426
+ return `v.pipe(v.unknown(),v.rawCheck(({dataset,addIssue})=>{if(!dataset.typed)return;const o=dataset.value;if(typeof o!=='object'||o===null||Array.isArray(o))return;${unevaluated === false ? `for(const k of Object.keys(o)){if(${isEvaluated})continue;addIssue({message:${message === void 0 ? `'Unevaluated property: '+k` : JSON.stringify(message)}})}` : `const Unevaluated=${valibot(unevaluated, rootName, isValibot, options)};for(const [k,val] of Object.entries(o)){if(${isEvaluated})continue;const result=v.safeParse(Unevaluated,val);if(!result.success){for(const issue of result.issues){addIssue({message:${message === void 0 ? "issue.message" : JSON.stringify(message)}})}}}`}}),${inner})`;
427
+ }
428
+ /**
429
+ * Generate Valibot schema code from JSON Schema.
430
+ *
431
+ * @example
432
+ * ```ts
433
+ * valibot({ type: 'string' }, 'MySchema') // 'v.string()'
434
+ * ```
435
+ */
436
+ function valibot(schema, rootName = DEFAULT_ROOT_NAME, isValibot = false, options) {
437
+ if (hasParameterSerialization(options)) {
438
+ const inner = valibot(schema, rootName, isValibot, withoutParameterSerialization(options));
439
+ return preprocess(parameterReaders(schema, options, "input"), inner);
440
+ }
441
+ return node(schema, rootName, isValibot, options);
442
+ }
443
+ /** A keyword-only `allOf` member: the keywords apply when the value has their type. */
444
+ function keywordConstraint(schema) {
445
+ return `v.pipe(v.any(),v.check((input) => ${constraintPredicate(schema, "input")}${valibotErrorPart(constraintMessage(schema))}))`;
446
+ }
447
+ function node(schema, rootName, isValibot, options) {
448
+ const isStringWireParam = isStringWireLocation(options?.paramIn);
449
+ const isWireCoerced = isStringWireParam && schema["x-coerce"] !== false;
450
+ const codeExtOpts = options?.unsafeCodeExtensions === true ? { unsafeCodeExtensions: true } : {};
451
+ const wireOptions = (s) => {
452
+ if (!isStringWireParam || s["x-coerce"] === false) return {};
453
+ return {
454
+ stringWire: true,
455
+ ...isNullTextRead(s) && { nullText: true }
456
+ };
457
+ };
458
+ const valibotWrap$1 = (valibotStr, s) => valibotWrap(valibotStr, s, {
459
+ ...codeExtOpts,
460
+ ...wireOptions(s),
461
+ ...options?.definitions !== void 0 && { definitions: options.definitions }
462
+ });
463
+ const readonly = (v) => options?.readonly ? `v.pipe(${v},v.readonly())` : v;
464
+ const wireArray = (v) => isStringWireParam ? preprocess([wireArrayOnce("input")], v) : v;
465
+ const literalInput = (values) => {
466
+ if (values.every((v) => typeof v === "number")) {
467
+ if (isInt64(schema)) return int64Input(isWireCoerced);
468
+ if (isWireCoerced) return [
469
+ "v.string()",
470
+ `v.regex(${wireNumericKind(schema, values) === "integer" ? integerWirePattern() : numberWirePattern()})`,
471
+ "v.transform((input)=>Number(input))"
472
+ ];
473
+ }
474
+ if (isWireCoerced && values.every((v) => typeof v === "boolean")) return stringboolItems("");
475
+ };
476
+ if (schema.$ref) {
477
+ const ref = (s) => {
478
+ if (s.$ref === void 0) return "v.any()";
479
+ const target = refTarget(s.$ref, rootName, isValibot, options?.openapi);
480
+ if (target.kind === "lazy") return `v.lazy(() => ${target.name})`;
481
+ if (target.kind === "value") return target.name;
482
+ return target.kind === "unknown" ? "v.unknown()" : "v.any()";
483
+ };
484
+ const items = itemsSchemaOf(schema.items);
485
+ if (schema.type === "array" && items?.$ref) return `v.array(${valibotWrap$1(ref(items), items)})`;
486
+ return valibotWrap$1(ref(schema), schema);
487
+ }
488
+ const impliedType = isWireCoerced ? impliedWireType(schema) : void 0;
489
+ if (impliedType !== void 0) return node({
490
+ ...schema,
491
+ type: impliedType
492
+ }, rootName, isValibot, options);
493
+ if (schema.oneOf) {
494
+ if (schema.oneOf.length === 0) return valibotWrap$1("v.any()", schema);
495
+ const schemas = schema.oneOf.map((s) => valibot(s, rootName, isValibot, options));
496
+ const oneOfMessage = schema["x-oneOf-message"];
497
+ const errorPart = valibotErrorPart(oneOfMessage);
498
+ const discriminator = schema.discriminator?.propertyName;
499
+ const hasRefOrAllOf = schema.oneOf.some((s) => s.$ref !== void 0 || s.allOf !== void 0);
500
+ return valibotWrap$1(discriminator && !hasRefOrAllOf ? `v.variant('${discriminator}',[${schemas.join(",")}]${errorPart})` : `v.union([${schemas.join(",")}]${errorPart})`, schema);
501
+ }
502
+ if (schema.anyOf) {
503
+ if (schema.anyOf.length === 0) return valibotWrap$1("v.any()", schema);
504
+ const schemas = schema.anyOf.map((s) => valibot(s, rootName, isValibot, options));
505
+ const anyOfMessage = schema["x-implication-message"] ?? schema["x-anyOf-message"];
506
+ const errorPart = valibotErrorPart(anyOfMessage);
507
+ return valibotWrap$1(`v.union([${schemas.join(",")}]${errorPart})`, schema);
508
+ }
509
+ if (schema.allOf) {
510
+ if (schema.allOf.length === 0) return valibotWrap$1("v.any()", schema);
511
+ const nullable = isNullable(schema) || schema.allOf.some(isNullTypeMember);
512
+ const defaultValue = schema.allOf.find(isDefaultOnlyMember)?.default;
513
+ const schemas = foldAllOfMembers(schema.allOf.filter((s) => !isShapelessMember(s)), isWireCoerced).map((s) => isKeywordOnlyMember(s) ? keywordConstraint(s) : valibot(s, rootName, isValibot, options));
514
+ if (schemas.length === 0) return valibotWrap$1("v.any()", {
515
+ ...schema,
516
+ nullable
517
+ });
518
+ const intersected = schemas.length === 1 ? schemas[0] : `v.intersect([${schemas.join(",")}])`;
519
+ const allOfMessage = schema["x-allOf-message"];
520
+ const checked = unevaluatedPropertiesCheck(allOfMessage ? (() => {
521
+ const msgExpr = issueMessageExpression(allOfMessage);
522
+ return `v.pipe(v.unknown(),v.rawCheck(({dataset,addIssue})=>{if(!dataset.typed)return;const result=v.safeParse(${intersected},dataset.value);if(!result.success){for(const issue of result.issues){addIssue({message:${msgExpr},path:issue.path})}}}))`;
523
+ })() : intersected, schema, rootName, isValibot, options);
524
+ if (defaultValue !== void 0) return `v.optional(${nullable ? `v.nullable(${checked})` : checked},${jsLiteral(defaultValue)})`;
525
+ return valibotWrap$1(checked, {
526
+ ...schema,
527
+ nullable
528
+ });
529
+ }
530
+ if (schema.not) {
531
+ const { not: inner, ...withoutNot } = schema;
532
+ if (typeof inner !== "object" || inner === null) return valibotWrap$1("v.any()", schema);
533
+ const notMessage = schema["x-not-message"];
534
+ const errorPart = valibotErrorPart(notMessage);
535
+ const predicate = (() => {
536
+ const bigint = isBigintFormat(withoutNot);
537
+ const shared = notPredicate(inner, "input", "input", bigint);
538
+ if (shared !== void 0) return shared;
539
+ if (Array.isArray(inner.enum)) return `(input) => !${valueListLiteral(inner.enum, bigint)}.some((item) => item === input)`;
540
+ return `(input) => !v.safeParse(${valibot(inner, rootName, isValibot, options)},input).success`;
541
+ })();
542
+ if (withoutNot.type !== void 0) {
543
+ const base = valibot(withoutNot, rootName, isValibot, options);
544
+ return predicate ? appendPipe(base, [`v.check(${predicate}${errorPart})`]) : base;
545
+ }
546
+ if (predicate) return valibotWrap$1(`v.custom<unknown>(${predicate}${errorPart})`, schema);
547
+ return valibotWrap$1("v.any()", schema);
548
+ }
549
+ if (schema.const !== void 0) {
550
+ const value = schema.const;
551
+ const constMessage = schema["x-const-message"] ?? schema["x-error-message"];
552
+ const msgArg = constMessage ? valibotError(constMessage) : "";
553
+ const errorPart = msgArg ? `,${msgArg}` : "";
554
+ if (value === null) return valibotWrap$1(`v.null(${msgArg})`, schema);
555
+ const literal = typeof value === "number" && isInt64(schema) ? `v.literal(${value}n${errorPart})` : isPrimitive(value) ? `v.literal(${JSON.stringify(value)}${errorPart})` : `v.custom<${JSON.stringify(value)}>((input) => JSON.stringify(input) === ${JSON.stringify(JSON.stringify(value))}${errorPart})`;
556
+ const input = literalInput([value]);
557
+ return valibotWrap$1(input ? prependPipe(input, literal) : literal, schema);
558
+ }
559
+ if (schema.enum) {
560
+ const values = schema.enum.filter((value) => value !== null);
561
+ const input = values.length > 0 ? literalInput(values) : void 0;
562
+ if (input === void 0) return valibotWrap$1(_enum(schema), schema);
563
+ const hasNull = values.length < schema.enum.length;
564
+ const piped = prependPipe(input, _enum({
565
+ ...schema,
566
+ enum: values
567
+ }));
568
+ return valibotWrap$1(hasNull && !isNullable(schema) ? `v.nullable(${piped})` : piped, schema);
569
+ }
570
+ if (schema.properties) return readonly(valibotWrap$1(object(schema, rootName, isValibot, options), schema));
571
+ const types = normalizeTypes(schema.type);
572
+ const primitive = (t) => {
573
+ if (t === "string") return string(schema);
574
+ if (t === "number") return number(schema, { wire: isWireCoerced });
575
+ if (t === "integer") return integer(schema, { wire: isWireCoerced });
576
+ if (t !== "boolean") return void 0;
577
+ const errorMessage = schema["x-error-message"];
578
+ const errorArg = errorMessage ? valibotError(errorMessage) : "";
579
+ return isWireCoerced ? stringbool(errorArg) : `v.boolean(${errorArg})`;
580
+ };
581
+ if (isPrimitiveUnion(types, isWireCoerced)) return valibotWrap$1(`v.union([${unionPrimitiveTypes(types, isWireCoerced).map(primitive).filter((m) => m !== void 0).join(",")}])`, schema);
582
+ for (const t of [
583
+ "string",
584
+ "number",
585
+ "integer",
586
+ "boolean"
587
+ ]) {
588
+ if (!types.includes(t)) continue;
589
+ const expression = primitive(t);
590
+ if (expression !== void 0) return valibotWrap$1(expression, schema);
591
+ }
592
+ if (types.includes("array")) {
593
+ if (schema.prefixItems?.length) {
594
+ const items = schema.prefixItems.map((s) => valibot(s, rootName, isValibot, options));
595
+ const u = schema.unevaluatedItems;
596
+ const unevaluatedItemsMessage = schema["x-unevaluatedItems-message"];
597
+ const unevaluatedItemsArg = valibotErrorPart(unevaluatedItemsMessage);
598
+ const tupleExpr = isSchemaObject(u) ? `v.tupleWithRest([${items.join(",")}],${valibot(u, rootName, isValibot, options)})` : u === false ? `v.strictTuple([${items.join(",")}]${unevaluatedItemsArg})` : `v.tuple([${items.join(",")}])`;
599
+ const prefixItemsMessage = schema["x-prefixItems-message"];
600
+ return readonly(valibotWrap$1(wireArray(prefixItemsMessage ? elementMessageWrap(tupleExpr, prefixItemsMessage) : tupleExpr), schema));
601
+ }
602
+ const itemSchema = itemsSchemaOf(schema.items);
603
+ const items = itemSchema ? valibot(itemSchema, rootName, isValibot, options) : "v.any()";
604
+ const itemsMessage = schema["x-items-message"];
605
+ const arrayBase = `v.array(${items})`;
606
+ const base = itemsMessage ? elementMessageWrap(arrayBase, itemsMessage) : arrayBase;
607
+ const isFixedLength = hasFixedItemCount(schema);
608
+ const lengthMessage = schema["x-length-message"];
609
+ const minItemsMessage = schema["x-minItems-message"] ?? lengthMessage;
610
+ const minArg = valibotErrorPart(minItemsMessage);
611
+ const maxItemsMessage = schema["x-maxItems-message"] ?? lengthMessage;
612
+ const maxArg = valibotErrorPart(maxItemsMessage);
613
+ const sizeArg = valibotErrorPart(minItemsMessage ?? maxItemsMessage);
614
+ const uniqueItemsMessage = schema["x-uniqueItems-message"];
615
+ const uniqueArg = valibotErrorPart(uniqueItemsMessage);
616
+ const containsActions = (() => {
617
+ const c = schema.contains;
618
+ if (!c) return [];
619
+ const containsSchema = valibot(c, rootName, isValibot, options);
620
+ const minC = schema.minContains;
621
+ const maxC = schema.maxContains;
622
+ const errorMessage = schema["x-error-message"];
623
+ const fallback = schema["x-contains-message"] ?? errorMessage;
624
+ const out = [];
625
+ if (minC === void 0 && maxC === void 0) {
626
+ const containsArg = valibotErrorPart(fallback);
627
+ out.push(`v.check((input)=>input.some((item)=>v.safeParse(${containsSchema},item).success)${containsArg})`);
628
+ } else {
629
+ const effectiveMin = minC ?? 1;
630
+ if (effectiveMin > 0) {
631
+ const minContainsMessage = schema["x-minContains-message"] ?? fallback;
632
+ const minContainsArg = valibotErrorPart(minContainsMessage);
633
+ out.push(`v.check((input)=>input.filter((item)=>v.safeParse(${containsSchema},item).success).length>=${effectiveMin}${minContainsArg})`);
634
+ }
635
+ if (maxC !== void 0) {
636
+ const maxContainsMessage = schema["x-maxContains-message"] ?? fallback;
637
+ const maxContainsArg = valibotErrorPart(maxContainsMessage);
638
+ out.push(`v.check((input)=>input.filter((item)=>v.safeParse(${containsSchema},item).success).length<=${maxC}${maxContainsArg})`);
639
+ }
640
+ }
641
+ return out;
642
+ })();
643
+ const actions = [
644
+ isFixedLength ? `v.length(${schema.minItems}${sizeArg})` : void 0,
645
+ !isFixedLength && typeof schema.minItems === "number" ? `v.minLength(${schema.minItems}${minArg})` : void 0,
646
+ !isFixedLength && typeof schema.maxItems === "number" ? `v.maxLength(${schema.maxItems}${maxArg})` : void 0,
647
+ schema.uniqueItems === true ? `v.check((input) => new Set(input).size === input.length${uniqueArg})` : void 0,
648
+ ...containsActions
649
+ ].filter((v) => v !== void 0);
650
+ return readonly(valibotWrap$1(wireArray(actions.length > 0 ? `v.pipe(${base},${actions.join(",")})` : base), schema));
651
+ }
652
+ if (types.includes("object")) return readonly(valibotWrap$1(object(schema, rootName, isValibot, options), schema));
653
+ if (types.includes("date")) {
654
+ if (isWireCoerced) return valibotWrap$1(`v.pipe(v.string(),v.transform((input)=>new Date(input)),v.date())`, schema);
655
+ return valibotWrap$1("v.date()", schema);
656
+ }
657
+ if (types.length === 1 && types[0] === "null") return valibotWrap$1("v.null()", schema);
658
+ if (typeof schema.additionalProperties === "object") return readonly(valibotWrap$1(object(schema, rootName, isValibot, options), schema));
659
+ return valibotWrap$1("v.any()", schema);
660
+ }
661
+ //#endregion
662
+ //#region src/generator/valibot/index.ts
663
+ /**
664
+ * A recursive declaration needs an explicit annotation, since the schema is referenced
665
+ * inside its own initializer. `GenericSchema<TInput, TOutput>` pins the input to the
666
+ * output when given a single argument, which rejects any schema whose input differs — a
667
+ * field with a `default`, say — so only the output is constrained here. `_X` describes
668
+ * the output, which is what `v.InferOutput` reads.
669
+ */
670
+ function annotation(name) {
671
+ return `v.GenericSchema<unknown, _${name}>`;
672
+ }
673
+ /**
674
+ * A whole JSON Schema document as a Valibot module: imports, `$defs` in dependency
675
+ * order, the root export, and the inferred output type.
676
+ */
677
+ function schemaToValibot(input, options) {
678
+ const schema = withPolymorphicBases(hoistNestedRefs(input));
679
+ const exportType = options?.exportType ?? true;
680
+ const baseOptions = emitOptionsOf(options);
681
+ const codeExtensionsPresent = baseOptions.unsafeCodeExtensions === true && findCodeExtensionKeysInSchema(schema).length > 0;
682
+ const toName = schemaNamer(baseOptions.openapi);
683
+ const plan = planDocument(schema, rootNameOf(schema, toName));
684
+ const definitions = definitionsOf(baseOptions, plan.definitions);
685
+ const emitOptions = definitions === void 0 ? baseOptions : {
686
+ ...baseOptions,
687
+ definitions
688
+ };
689
+ const { rootName } = plan;
690
+ const needsTypeDef = plan.hasDefinitions || hasRootSelfReference(schema);
691
+ const typeDefsCode = needsTypeDef ? [`type _${rootName} = ${type(plan.root, rootName)}`, renderDefinitions(plan, toName, (def, name) => `type _${name} = ${type(def, name)}`)].filter(Boolean).join("\n\n") : "";
692
+ const schemaDefsCode = renderDefinitions(plan, toName, (def, name) => `const ${name}: ${annotation(name)} = ${valibot(def, name, true, emitOptions)}`);
693
+ const rootSchema = valibot(plan.root, rootName, true, emitOptions);
694
+ const rootExport = needsTypeDef ? `export const ${rootName}: ${annotation(rootName)} = ${rootSchema}` : `export const ${rootName} = ${rootSchema}`;
695
+ return [
696
+ ...codeExtensionsPresent ? [UNSAFE_GENERATED_MARKER] : [],
697
+ `import * as v from 'valibot'`,
698
+ typeDefsCode,
699
+ schemaDefsCode,
700
+ rootExport,
701
+ ...exportType ? [`export type ${rootName}Output = v.InferOutput<typeof ${rootName}>`] : []
702
+ ].filter(Boolean).join("\n\n");
703
+ }
704
+ //#endregion
705
+ export { valibot as n, schemaToValibot as t };