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,746 @@
1
+ import { $ as DEFINITION_REF_PREFIXES, B as isSchemaObject, D as isComposite, E as isArktypeDefinition, H as isStringWireLocation, I as isQuoted, M as isNullable, N as isObjectPrototypeProperty, O as isDeepLocalPointer, Ot as UNSAFE_GENERATED_MARKER, R as isRootRef, S as hasFixedLength, V as isShapelessMember, X as DEFAULT_ROOT_NAME, at as INTEGER_TEXT_PATTERN, bt as QUOTE_OR_BACKSLASH_PATTERN, c as normalizeTypes, ft as NUMBER_RANGES, j as isNullTypeMember, l as resolveOpenAPIRef, o as issueMessageExpression, s as makeSafeKey, x as hasFixedItemCount, y as hasCombinator } from "./utils-WNBq1HR0.js";
2
+ import { A as emitOptionsOf, B as arktypePreprocess, C as formatPattern, F as schemaNamer, H as findCodeExtensionKeysInSchema, M as planDocument, P as rootNameOf, S as wireNullText, V as arktypeWrap, _ as ownProperties, a as regexLiteral, b as unionPrimitiveTypes, c as parameterReaders, g as isPrimitiveUnion, h as isNullTextRead, j as missingDefinitionComment, l as withoutParameterSerialization, m as isNullMatchedFirst, p as impliedWireType, s as hasParameterSerialization, u as notPredicate, v as stringboolPattern, w as regexSource, x as wireArrayOnce, y as stringboolTruthyPattern, z as itemsSchemaOf } from "./helper-Cfvb5UDq.js";
3
+ //#region src/generator/arktype/number.ts
4
+ /** The DSL comparators of a numeric node: `>= 1`, `< 5`, `% 2`. */
5
+ function numericConstraints(schema) {
6
+ return [
7
+ (() => {
8
+ if (schema.minimum !== void 0) return schema.exclusiveMinimum === true ? `> ${schema.minimum}` : `>= ${schema.minimum}`;
9
+ if (typeof schema.exclusiveMinimum === "number") return `> ${schema.exclusiveMinimum}`;
10
+ })(),
11
+ (() => {
12
+ if (schema.maximum !== void 0) return schema.exclusiveMaximum === true ? `< ${schema.maximum}` : `<= ${schema.maximum}`;
13
+ if (typeof schema.exclusiveMaximum === "number") return `< ${schema.exclusiveMaximum}`;
14
+ })(),
15
+ schema.multipleOf !== void 0 ? `% ${schema.multipleOf}` : void 0
16
+ ].filter((v) => v !== void 0);
17
+ }
18
+ /** The range comparators of a fixed-width numeric `format`, if it has one. */
19
+ function rangeConstraints(format) {
20
+ const range = format === void 0 ? void 0 : NUMBER_RANGES[format];
21
+ if (range === void 0) return [];
22
+ return [`>= ${range.minimum}`, `<= ${range.maximum}`];
23
+ }
24
+ /**
25
+ * A numeric keyword with its comparators as one quoted definition:
26
+ * `"number.integer >= 1 & number.integer <= 5"`. One definition, not an `.and()` chain
27
+ * of them, so a morph can validate its output against it with `.to()`.
28
+ */
29
+ function constraintDefinition(base, constraints) {
30
+ if (constraints.length === 0) return `"${base}"`;
31
+ return `"${constraints.map((c) => `${base} ${c}`).join(" & ")}"`;
32
+ }
33
+ /**
34
+ * The `.narrow(...)` chain of a numeric node whose bounds carry their own messages: the
35
+ * DSL has no message slot, so each keyword becomes a predicate with `ctx.mustBe`.
36
+ */
37
+ function numericNarrows(schema, errorMessage) {
38
+ const minMessage = schema["x-minimum-message"];
39
+ const maxMessage = schema["x-maximum-message"];
40
+ const exclusiveMinimumMessage = schema["x-exclusiveMinimum-message"];
41
+ const exclusiveMaximumMessage = schema["x-exclusiveMaximum-message"];
42
+ const multipleOfMessage = schema["x-multipleOf-message"];
43
+ const narrows = [];
44
+ if (schema.minimum !== void 0 && schema.exclusiveMinimum !== true) {
45
+ const msg = minMessage ?? errorMessage ?? `must be >= ${schema.minimum}`;
46
+ narrows.push(`.narrow((data, ctx) => data >= ${schema.minimum} || ctx.mustBe(${JSON.stringify(msg)}))`);
47
+ }
48
+ if (schema.exclusiveMinimum === true && schema.minimum !== void 0) {
49
+ const msg = exclusiveMinimumMessage ?? errorMessage ?? `must be > ${schema.minimum}`;
50
+ narrows.push(`.narrow((data, ctx) => data > ${schema.minimum} || ctx.mustBe(${JSON.stringify(msg)}))`);
51
+ }
52
+ if (typeof schema.exclusiveMinimum === "number") {
53
+ const msg = exclusiveMinimumMessage ?? errorMessage ?? `must be > ${schema.exclusiveMinimum}`;
54
+ narrows.push(`.narrow((data, ctx) => data > ${schema.exclusiveMinimum} || ctx.mustBe(${JSON.stringify(msg)}))`);
55
+ }
56
+ if (schema.maximum !== void 0 && schema.exclusiveMaximum !== true) {
57
+ const msg = maxMessage ?? errorMessage ?? `must be <= ${schema.maximum}`;
58
+ narrows.push(`.narrow((data, ctx) => data <= ${schema.maximum} || ctx.mustBe(${JSON.stringify(msg)}))`);
59
+ }
60
+ if (schema.exclusiveMaximum === true && schema.maximum !== void 0) {
61
+ const msg = exclusiveMaximumMessage ?? errorMessage ?? `must be < ${schema.maximum}`;
62
+ narrows.push(`.narrow((data, ctx) => data < ${schema.maximum} || ctx.mustBe(${JSON.stringify(msg)}))`);
63
+ }
64
+ if (typeof schema.exclusiveMaximum === "number") {
65
+ const msg = exclusiveMaximumMessage ?? errorMessage ?? `must be < ${schema.exclusiveMaximum}`;
66
+ narrows.push(`.narrow((data, ctx) => data < ${schema.exclusiveMaximum} || ctx.mustBe(${JSON.stringify(msg)}))`);
67
+ }
68
+ if (schema.multipleOf !== void 0) {
69
+ const msg = multipleOfMessage ?? errorMessage ?? `must be a multiple of ${schema.multipleOf}`;
70
+ narrows.push(`.narrow((data, ctx) => data % ${schema.multipleOf} === 0 || ctx.mustBe(${JSON.stringify(msg)}))`);
71
+ }
72
+ return narrows.join("");
73
+ }
74
+ /** Whether any bound of a numeric node carries a message of its own. */
75
+ function hasPerKeywordMessage(schema) {
76
+ return [
77
+ schema["x-minimum-message"],
78
+ schema["x-maximum-message"],
79
+ schema["x-exclusiveMinimum-message"],
80
+ schema["x-exclusiveMaximum-message"],
81
+ schema["x-multipleOf-message"]
82
+ ].some(Boolean);
83
+ }
84
+ /**
85
+ * A morph reading the text of a wire parameter with `Number`, guarded by `guard`: what
86
+ * every other generator reads, where ArkType's own `string.numeric.parse` refuses `1e3`,
87
+ * `1.0`, `007` and `-0`.
88
+ */
89
+ function numberMorph(guard, expected) {
90
+ return `type("string").pipe((data, ctx) => { const value = Number(data); return Number.${guard}(value) ? value : ctx.error(${JSON.stringify(expected)}) })`;
91
+ }
92
+ /**
93
+ * The ArkType definition of a number node: the `number` keyword with its comparators,
94
+ * `float` / `float32` carrying its range. Bounds with messages of their own become a
95
+ * `.narrow()` chain instead.
96
+ */
97
+ function number(schema) {
98
+ const errorMessage = schema["x-error-message"] ?? schema["x-required-message"];
99
+ const describe = errorMessage ? `.describe(${JSON.stringify(errorMessage)})` : "";
100
+ const isFloat32 = schema.format === "float" || schema.format === "float32";
101
+ const constraints = [...rangeConstraints(isFloat32 ? "float32" : void 0), ...numericConstraints(schema)];
102
+ if (hasPerKeywordMessage(schema)) return `type(${constraintDefinition("number", rangeConstraints(isFloat32 ? "float32" : void 0))})${numericNarrows(schema, errorMessage)}${describe}`;
103
+ const definition = constraintDefinition("number", constraints);
104
+ if (errorMessage) return `type(${definition})${describe}`;
105
+ return definition;
106
+ }
107
+ //#endregion
108
+ //#region src/generator/arktype/integer.ts
109
+ /** Whether a node is a 64-bit integer: a value beyond 2^53 that is read as a bigint. */
110
+ function isInt64(schema) {
111
+ return schema.format === "int64" || schema.format === "uint64";
112
+ }
113
+ /**
114
+ * A morph reading a 64-bit integer into a bigint. On the string wire the text is a sign
115
+ * and digits; in a JSON body the value is a bigint, a safe-integer number, or the string
116
+ * of digits that is the only lossless way to carry a larger one.
117
+ */
118
+ function bigintMorph(isWire) {
119
+ const digits = regexSource(INTEGER_TEXT_PATTERN);
120
+ if (isWire) return `type("string").pipe((data, ctx) => (${digits}.test(data) ? BigInt(data) : ctx.error("an integer")))`;
121
+ return `type("bigint | number.integer").or(${digits}).pipe((data) => BigInt(data))`;
122
+ }
123
+ /**
124
+ * The `.narrow(...)` chain holding a bigint within its bounds: ArkType's DSL has no
125
+ * bigint comparators, so each is a predicate with `ctx.mustBe`.
126
+ */
127
+ function bigintNarrows(schema, lit) {
128
+ const range = schema.format === void 0 ? void 0 : NUMBER_RANGES[schema.format];
129
+ return [
130
+ range === void 0 ? void 0 : `.narrow((data, ctx) => (data >= ${range.minimum} && data <= ${range.maximum}) || ctx.mustBe(${JSON.stringify(schema.format === "uint64" ? "a uint64" : "an int64")}))`,
131
+ schema.minimum === void 0 ? void 0 : schema.exclusiveMinimum === true ? `.narrow((data, ctx) => data > ${lit(schema.minimum)} || ctx.mustBe(${JSON.stringify(`more than ${schema.minimum}`)}))` : `.narrow((data, ctx) => data >= ${lit(schema.minimum)} || ctx.mustBe(${JSON.stringify(`at least ${schema.minimum}`)}))`,
132
+ typeof schema.exclusiveMinimum === "number" ? `.narrow((data, ctx) => data > ${lit(schema.exclusiveMinimum)} || ctx.mustBe(${JSON.stringify(`more than ${schema.exclusiveMinimum}`)}))` : void 0,
133
+ schema.maximum === void 0 ? void 0 : schema.exclusiveMaximum === true ? `.narrow((data, ctx) => data < ${lit(schema.maximum)} || ctx.mustBe(${JSON.stringify(`less than ${schema.maximum}`)}))` : `.narrow((data, ctx) => data <= ${lit(schema.maximum)} || ctx.mustBe(${JSON.stringify(`at most ${schema.maximum}`)}))`,
134
+ typeof schema.exclusiveMaximum === "number" ? `.narrow((data, ctx) => data < ${lit(schema.exclusiveMaximum)} || ctx.mustBe(${JSON.stringify(`less than ${schema.exclusiveMaximum}`)}))` : void 0,
135
+ schema.multipleOf === void 0 ? void 0 : `.narrow((data, ctx) => data % ${lit(schema.multipleOf)} === 0n || ctx.mustBe(${JSON.stringify(`a multiple of ${schema.multipleOf}`)}))`
136
+ ].filter((v) => v !== void 0).join("");
137
+ }
138
+ /**
139
+ * The ArkType definition of an integer node: the `number.integer` keyword with its
140
+ * comparators, `int32` / `uint32` carrying their range. `int64` / `uint64` are bigints
141
+ * wherever they come from, and `bigint` is one too; their bounds are narrows.
142
+ */
143
+ function integer(schema, options) {
144
+ const errorMessage = schema["x-error-message"] ?? schema["x-required-message"];
145
+ const describe = errorMessage ? `.describe(${JSON.stringify(errorMessage)})` : "";
146
+ if (schema.format === "bigint") {
147
+ const narrows = bigintNarrows(schema, (n) => `BigInt(${n})`);
148
+ return `${options?.wire === true ? bigintMorph(true) : narrows || errorMessage ? "type(\"bigint\")" : "\"bigint\""}${narrows}${describe}`;
149
+ }
150
+ if (isInt64(schema)) return `${bigintMorph(options?.wire === true)}${bigintNarrows(schema, (n) => `${n}n`)}${describe}`;
151
+ const range = rangeConstraints(schema.format);
152
+ if (hasPerKeywordMessage(schema)) return `type(${constraintDefinition("number.integer", range)})${numericNarrows(schema, errorMessage)}${describe}`;
153
+ const definition = constraintDefinition("number.integer", [...range, ...numericConstraints(schema)]);
154
+ if (errorMessage) return `type(${definition})${describe}`;
155
+ return definition;
156
+ }
157
+ //#endregion
158
+ //#region src/generator/arktype/enum.ts
159
+ function lit(v, isBigint) {
160
+ if (v === null) return "null";
161
+ if (typeof v === "string") return `'${v}'`;
162
+ if (typeof v === "number" && isBigint) return `${v}n`;
163
+ if (typeof v === "number" || typeof v === "boolean") return String(v);
164
+ return JSON.stringify(v) ?? "null";
165
+ }
166
+ /**
167
+ * The ArkType definition of an enum: a `"a | b | c"` string union. The members of an
168
+ * int64 / uint64 enum are bigint literals, as the value they match is.
169
+ */
170
+ function _enum(schema) {
171
+ const errorMessage = schema["x-enum-message"] ?? schema["x-error-message"];
172
+ const describe = errorMessage ? `.describe(${JSON.stringify(errorMessage)})` : "";
173
+ if (!schema.enum || schema.enum.length === 0) return "\"unknown\"";
174
+ const isBigint = isInt64(schema);
175
+ if (schema.enum.some(isComposite)) return "\"unknown\"";
176
+ if (schema.enum.some((v) => typeof v === "string" && QUOTE_OR_BACKSLASH_PATTERN.test(v))) {
177
+ const expr = `type.enumerated(${schema.enum.map((v) => JSON.stringify(v)).join(",")})`;
178
+ if (errorMessage) return `${expr}${describe}`;
179
+ return expr;
180
+ }
181
+ if (schema.enum.length === 1) {
182
+ const expr = `"${lit(schema.enum[0], isBigint)}"`;
183
+ if (errorMessage) return `type(${expr})${describe}`;
184
+ return expr;
185
+ }
186
+ const expr = `"${schema.enum.map((v) => lit(v, isBigint)).join(" | ")}"`;
187
+ if (errorMessage) return `type(${expr})${describe}`;
188
+ return expr;
189
+ }
190
+ //#endregion
191
+ //#region src/generator/arktype/object.ts
192
+ function composeNarrows(base, narrows) {
193
+ return narrows.length === 0 ? base : narrows.reduce((acc, n) => `${acc}.narrow(${n})`, base);
194
+ }
195
+ /** Wrap a raw arktype expression with `type(...)` if it's a bare quoted string. */
196
+ function ensureRuntime(s) {
197
+ return isQuoted(s) ? `type(${s})` : s;
198
+ }
199
+ /**
200
+ * Compose a `.narrow(...)` argument with an optional error message.
201
+ * - With message: `(data, ctx) => predicate || ctx.mustBe("msg")`
202
+ * - Without message: `(data) => predicate`
203
+ */
204
+ function narrowPredicate(predicate, message) {
205
+ return message ? `(data, ctx) => ${predicate} || ctx.mustBe(${JSON.stringify(message)})` : `(data) => ${predicate}`;
206
+ }
207
+ /**
208
+ * Generate an Arktype object schema for a JSON Schema object node.
209
+ *
210
+ * Combinators (oneOf/anyOf/allOf/not) delegate to the main `arktype` entry.
211
+ * JSON Schema 2020-12 keywords (`minProperties`, `maxProperties`,
212
+ * `propertyNames`, `patternProperties`, `dependentRequired`) are emitted as
213
+ * `.narrow(...)` chains. When narrows are applied, the result is always in
214
+ * wrapped form (`type({...}).narrow(...)`) regardless of `isArktype`.
215
+ */
216
+ function object(schema, rootName, isArktype, options) {
217
+ if (hasCombinator(schema)) return arktype(schema, rootName, isArktype, options);
218
+ const errorMessage = schema["x-error-message"];
219
+ const minimumMessage = schema["x-minProperties-message"];
220
+ const maximumMessage = schema["x-maxProperties-message"];
221
+ const patternPropsMessage = schema["x-patternProperties-message"];
222
+ const propNamesMessage = schema["x-propertyNames-message"];
223
+ const depReqMessage = schema["x-dependentRequired-message"] ?? errorMessage;
224
+ const depSchMessage = schema["x-dependentSchemas-message"] ?? errorMessage;
225
+ const addlPropsMessage = schema["x-additionalProperties-message"];
226
+ const unevalPropsRawMessage = schema["x-unevaluatedProperties-message"];
227
+ const propertyNamesNarrow = () => {
228
+ if (schema.propertyNames?.pattern) return narrowPredicate(`Object.keys(data).every((key) => new RegExp(${JSON.stringify(schema.propertyNames.pattern)}).test(key))`, propNamesMessage);
229
+ if (schema.propertyNames?.enum) return narrowPredicate(`Object.keys(data).every((key) => ${JSON.stringify(schema.propertyNames.enum)}.includes(key))`, propNamesMessage);
230
+ return "";
231
+ };
232
+ const patternPropertiesNarrows = () => schema.patternProperties ? Object.entries(schema.patternProperties).map(([pattern, propSchema]) => {
233
+ const s = ensureRuntime(arktype(propSchema, rootName, isArktype, options));
234
+ return narrowPredicate(`Object.entries(data).every(([key, value]) => !new RegExp(${JSON.stringify(pattern)}).test(key) || ${s}.allows(value))`, patternPropsMessage);
235
+ }) : [];
236
+ if (typeof schema.additionalProperties === "object") {
237
+ const innerLiteral = `{"[string]":${arktype(schema.additionalProperties, rootName, isArktype, options)}}`;
238
+ const narrows = [propertyNamesNarrow(), ...patternPropertiesNarrows()].filter((a) => a !== "");
239
+ if (narrows.length > 0) return composeNarrows(`type(${innerLiteral})`, narrows);
240
+ return isArktype ? innerLiteral : `type(${innerLiteral})`;
241
+ }
242
+ if (!schema.properties) {
243
+ if (schema.additionalProperties === true) return "\"unknown\"";
244
+ return isArktype ? "{}" : "type({})";
245
+ }
246
+ const additionalMode = schema.additionalProperties === true ? "delete" : schema.additionalProperties === false ? "reject" : void 0;
247
+ const required = new Set(schema.required);
248
+ const props = Object.entries(schema.properties).map(([key, propSchema]) => {
249
+ const parsed = arktype(propSchema, rootName, isArktype, options);
250
+ if (!parsed) return null;
251
+ const isRequired = required.has(key);
252
+ const baseSafeKey = makeSafeKey(key);
253
+ return `${isRequired ? baseSafeKey : baseSafeKey.startsWith("\"") ? JSON.stringify(`${key}?`) : `"${key}?"`}:${parsed}`;
254
+ }).filter((p) => p !== null);
255
+ const additionalProp = additionalMode ? `"+":"${additionalMode}"` : void 0;
256
+ const innerLiteral = `{${[...props, additionalProp].filter((p) => p !== void 0).join(",")}}`;
257
+ const minPropertiesNarrow = typeof schema.minProperties === "number" ? narrowPredicate(`Object.keys(data).length >= ${schema.minProperties}`, minimumMessage) : "";
258
+ const maxPropertiesNarrow = typeof schema.maxProperties === "number" ? narrowPredicate(`Object.keys(data).length <= ${schema.maxProperties}`, maximumMessage) : "";
259
+ const dependentRequiredNarrows = schema.dependentRequired ? Object.entries(schema.dependentRequired).map(([key, deps]) => {
260
+ return narrowPredicate(`!('${key}' in data) || (${deps.map((d) => `'${d}' in data`).join(" && ")})`, depReqMessage);
261
+ }) : [];
262
+ const dependentSchemasNarrows = schema.dependentSchemas ? Object.entries(schema.dependentSchemas).map(([key, subSchema]) => {
263
+ return narrowPredicate(`!('${key}' in data) || ${ensureRuntime(arktype(subSchema, rootName, isArktype, options))}.allows(data)`, depSchMessage);
264
+ }) : [];
265
+ const additionalPropertiesNarrow = schema.additionalProperties === false && addlPropsMessage ? narrowPredicate(`Object.keys(data).every((key) => ${JSON.stringify(Object.keys(schema.properties))}.includes(key))`, addlPropsMessage) : "";
266
+ const unevaluatedPropertiesNarrow = (() => {
267
+ const u = schema.unevaluatedProperties;
268
+ if (u === void 0 || u === true) return "";
269
+ const declaredKeys = JSON.stringify(Object.keys(schema.properties ?? {}));
270
+ if (u === false) return narrowPredicate(`Object.keys(data).every((key) => ${declaredKeys}.includes(key))`, unevalPropsRawMessage);
271
+ if (typeof u === "object") return narrowPredicate(`Object.entries(data).filter(([key]) => !${declaredKeys}.includes(key)).every(([, value]) => ${ensureRuntime(arktype(u, rootName, isArktype, options))}.allows(value))`, unevalPropsRawMessage);
272
+ return "";
273
+ })();
274
+ const ifThenElseNarrows = (() => {
275
+ if (!schema.if) return [];
276
+ const ifS = ensureRuntime(arktype(schema.if, rootName, isArktype, options));
277
+ const thenS = schema.then ? ensureRuntime(arktype(schema.then, rootName, isArktype, options)) : void 0;
278
+ const elseS = schema.else ? ensureRuntime(arktype(schema.else, rootName, isArktype, options)) : void 0;
279
+ if (!thenS && !elseS) return [];
280
+ const ifMessage = schema["x-if-message"];
281
+ const thenMessage = schema["x-then-message"] ?? ifMessage;
282
+ const elseMessage = schema["x-else-message"] ?? ifMessage;
283
+ const parts = [];
284
+ if (thenS) parts.push(narrowPredicate(`!${ifS}.allows(data) || ${thenS}.allows(data)`, thenMessage));
285
+ if (elseS) parts.push(narrowPredicate(`${ifS}.allows(data) || ${elseS}.allows(data)`, elseMessage));
286
+ return parts;
287
+ })();
288
+ const narrows = [
289
+ minPropertiesNarrow,
290
+ maxPropertiesNarrow,
291
+ propertyNamesNarrow(),
292
+ ...patternPropertiesNarrows(),
293
+ ...dependentRequiredNarrows,
294
+ ...dependentSchemasNarrows,
295
+ additionalPropertiesNarrow,
296
+ unevaluatedPropertiesNarrow,
297
+ ...ifThenElseNarrows
298
+ ].filter((a) => a !== "");
299
+ const baseExpr = narrows.length > 0 ? composeNarrows(`type(${innerLiteral})`, narrows) : isArktype ? innerLiteral : `type(${innerLiteral})`;
300
+ const propsMessage = schema["x-properties-message"];
301
+ const described = (() => {
302
+ if (typeof propsMessage !== "string") return baseExpr;
303
+ return `${baseExpr.startsWith("{") ? `type(${baseExpr})` : baseExpr}.describe(${JSON.stringify(propsMessage)})`;
304
+ })();
305
+ const hasInheritedName = Object.keys(schema.properties).some(isObjectPrototypeProperty);
306
+ return isStringWireLocation(options?.paramIn) && hasInheritedName ? `${arktypePreprocess([ownProperties("data")], described, "object")}.pipe((data) => ({ ...data }))` : described;
307
+ }
308
+ //#endregion
309
+ //#region src/generator/arktype/string.ts
310
+ /** The formats ArkType checks with a keyword of its own, keyed by the lower-cased format. */
311
+ const FORMAT_KEYWORD = {
312
+ email: "string.email",
313
+ uuid: "string.uuid",
314
+ uuidv4: "string.uuid.v4",
315
+ uuidv6: "string.uuid.v6",
316
+ uuidv7: "string.uuid.v7",
317
+ url: "string.url",
318
+ uri: "string.url",
319
+ ipv4: "string.ip.v4",
320
+ ipv6: "string.ip.v6",
321
+ ip: "string.ip",
322
+ base64: "string.base64",
323
+ base64url: "string.base64.url",
324
+ hex: "string.hex",
325
+ creditcard: "string.creditCard"
326
+ };
327
+ /** The formats that normalise the value rather than check it: ArkType's morph keywords. */
328
+ const TRANSFORM_KEYWORD = {
329
+ trim: "string.trim",
330
+ tolowercase: "string.lower",
331
+ touppercase: "string.upper"
332
+ };
333
+ /** An `http` / `https` URL, which `string.url` alone does not require. */
334
+ const HTTP_URL_PATTERN = String.raw`/^https?:\/\//`;
335
+ /** The definition checking a string `format`: a keyword, a pattern, or `"string"` for none. */
336
+ function formatDefinition(schema, format) {
337
+ if (format === void 0) return "\"string\"";
338
+ if (format === "binary") return "\"File\"";
339
+ if (format === "httpurl") return `type("string.url").and(${HTTP_URL_PATTERN})`;
340
+ if (format === "uuid" && typeof schema["x-uuidVersion"] === "string") return `"string.uuid.${schema["x-uuidVersion"]}"`;
341
+ const keyword = FORMAT_KEYWORD[format];
342
+ if (keyword !== void 0) return `"${keyword}"`;
343
+ const pattern = formatPattern(schema, format);
344
+ return pattern === void 0 ? "\"string\"" : `type(${pattern})`;
345
+ }
346
+ /** A count of characters, as the predicate messages spell it. */
347
+ function characters(count) {
348
+ return `${count} ${count === 1 ? "character" : "characters"}`;
349
+ }
350
+ /** `expr` validated against `definition` after its morphs: `.to()` for a definition, `.pipe()` for a type. */
351
+ function validateWith(expr, definition) {
352
+ return isQuoted(definition) ? `${expr}.to(${definition})` : `${expr}.pipe(${definition})`;
353
+ }
354
+ /**
355
+ * The ArkType definition of a string node. A transform — `x-trim`, `format: trim` and
356
+ * their siblings — is a morph keyword the format and the checks follow, so the value is
357
+ * normalised before it is checked. `minLength` / `maxLength` count code points, as JSON
358
+ * Schema does, so a narrow over `[...data]` stands in for the `string >= n` DSL, which
359
+ * counts UTF-16 units.
360
+ */
361
+ function string(schema) {
362
+ const errorMessage = schema["x-error-message"] ?? schema["x-required-message"];
363
+ const describe = errorMessage ? `.describe(${JSON.stringify(errorMessage)})` : "";
364
+ const lengthMessage = schema["x-minLength-message"] ?? schema["x-maxLength-message"];
365
+ const minLengthMessage = schema["x-minLength-message"];
366
+ const maxLengthMessage = schema["x-maxLength-message"];
367
+ const patternMessage = schema["x-pattern-message"];
368
+ const formatName = schema.format?.toLowerCase();
369
+ const transformFormat = formatName === void 0 ? void 0 : TRANSFORM_KEYWORD[formatName];
370
+ const transforms = [
371
+ schema["x-trim"] === true || transformFormat === "string.trim" ? "string.trim" : void 0,
372
+ schema["x-toLowerCase"] === true || transformFormat === "string.lower" ? "string.lower" : void 0,
373
+ schema["x-toUpperCase"] === true || transformFormat === "string.upper" ? "string.upper" : void 0,
374
+ typeof schema["x-normalize"] === "string" ? `string.normalize.${schema["x-normalize"]}` : void 0
375
+ ].filter((t) => t !== void 0);
376
+ const format = formatDefinition(schema, transformFormat === void 0 ? formatName : void 0);
377
+ const hasMorph = transforms.length > 0;
378
+ const constrain = (expr, pattern) => hasMorph ? `${expr}.to(${pattern})` : `${expr}.and(${pattern})`;
379
+ const narrows = [];
380
+ if (schema.pattern && patternMessage) narrows.push(`.narrow((data, ctx) => new RegExp(${JSON.stringify(schema.pattern)}).test(data) || ctx.mustBe(${JSON.stringify(patternMessage)}))`);
381
+ if (hasFixedLength(schema)) {
382
+ const msg = lengthMessage ?? `exactly ${characters(schema.minLength)}`;
383
+ narrows.push(`.narrow((data, ctx) => [...data].length === ${schema.minLength} || ctx.mustBe(${JSON.stringify(msg)}))`);
384
+ } else {
385
+ if (schema.minLength !== void 0) {
386
+ const msg = minLengthMessage ?? errorMessage ?? `at least ${characters(schema.minLength)}`;
387
+ narrows.push(`.narrow((data, ctx) => [...data].length >= ${schema.minLength} || ctx.mustBe(${JSON.stringify(msg)}))`);
388
+ }
389
+ if (schema.maxLength !== void 0) {
390
+ const msg = maxLengthMessage ?? errorMessage ?? `at most ${characters(schema.maxLength)}`;
391
+ narrows.push(`.narrow((data, ctx) => [...data].length <= ${schema.maxLength} || ctx.mustBe(${JSON.stringify(msg)}))`);
392
+ }
393
+ }
394
+ if (typeof schema["x-startsWith"] === "string") {
395
+ const prefix = schema["x-startsWith"];
396
+ narrows.push(`.narrow((data: string, ctx) => data.startsWith(${JSON.stringify(prefix)}) || ctx.mustBe(${JSON.stringify(`must start with ${JSON.stringify(prefix)}`)}))`);
397
+ }
398
+ if (typeof schema["x-endsWith"] === "string") {
399
+ const suffix = schema["x-endsWith"];
400
+ narrows.push(`.narrow((data: string, ctx) => data.endsWith(${JSON.stringify(suffix)}) || ctx.mustBe(${JSON.stringify(`must end with ${JSON.stringify(suffix)}`)}))`);
401
+ }
402
+ if (typeof schema["x-includes"] === "string") {
403
+ const sub = schema["x-includes"];
404
+ narrows.push(`.narrow((data: string, ctx) => data.includes(${JSON.stringify(sub)}) || ctx.mustBe(${JSON.stringify(`must include ${JSON.stringify(sub)}`)}))`);
405
+ }
406
+ const morphed = transforms.reduce((acc, t) => acc === void 0 ? `type("${t}")` : `${acc}.to("${t}")`, void 0);
407
+ const based = morphed === void 0 ? format : format === "\"string\"" ? morphed : validateWith(morphed, format);
408
+ const patterned = schema.pattern && !patternMessage ? constrain(isQuoted(based) ? `type(${based})` : based, regexLiteral(schema.pattern)) : based;
409
+ if (narrows.length === 0 && !errorMessage) return patterned;
410
+ return `${isQuoted(patterned) ? `type(${patterned})` : patterned}${narrows.join("")}${describe}`;
411
+ }
412
+ //#endregion
413
+ //#region src/generator/arktype/arktype.ts
414
+ /**
415
+ * Combine two ArkType expressions.
416
+ *
417
+ * Inside `scope({...})` a definition may name a scope-local alias, which the
418
+ * global `type(...)` cannot resolve, so scope mode composes with ArkType's
419
+ * tuple expressions — which stay in definition syntax — instead of methods.
420
+ */
421
+ function combine(op, inScope) {
422
+ return (acc, s) => inScope && isArktypeDefinition(acc) ? `[${acc},"${op}",${s}]` : `type(${acc}).${op === "&" ? "and" : "or"}(${s})`;
423
+ }
424
+ function unionStr(schemas, inScope = false) {
425
+ return schemas.every(isQuoted) ? `"${schemas.map((s) => s.slice(1, -1)).join(" | ")}"` : schemas.reduce(combine("|", inScope));
426
+ }
427
+ function intersectionStr(schemas, inScope = false) {
428
+ return schemas.every(isQuoted) ? `"${schemas.map((s) => s.slice(1, -1)).join(" & ")}"` : schemas.reduce(combine("&", inScope));
429
+ }
430
+ /** An ArkType expression that carries methods: a quoted definition is wrapped in `type(...)`. */
431
+ function asRuntime(source) {
432
+ return isQuoted(source) ? `type(${source})` : source;
433
+ }
434
+ /** Whether an expression reads its input through a morph: ArkType cannot union two of them. */
435
+ function isMorph(source) {
436
+ return source.includes(".pipe(");
437
+ }
438
+ /**
439
+ * A union of wire members, each a morph over the text, tried in order: ArkType refuses
440
+ * an unordered union of morphs with overlapping inputs, so the first branch that reads
441
+ * the text wins, as `z.union()` reads it.
442
+ */
443
+ function wireUnion(schemas, message) {
444
+ return `type("unknown").pipe((data, ctx) => { for (const branch of [${schemas.map(asRuntime).join(",")}]) { const out = branch(data); if (!(out instanceof type.errors)) return out } return ctx.error(${JSON.stringify(message ?? "one of the members")}) })`;
445
+ }
446
+ /** `morph` validated against `inner` after it, unless `inner` is the bare keyword the morph already reads. */
447
+ function wireNumeric(morph, inner) {
448
+ if (inner === "\"number\"" || inner === "\"number.integer\"") return morph;
449
+ return isQuoted(inner) ? `${morph}.to(${inner})` : `${morph}.pipe(${inner})`;
450
+ }
451
+ /** The boolean spellings of the wire, read into a boolean as `z.stringbool()` reads them. */
452
+ function stringbool() {
453
+ return `type(${stringboolPattern()}).pipe((data) => ${stringboolTruthyPattern()}.test(data))`;
454
+ }
455
+ function formatConst(value, isBigint) {
456
+ if (typeof value === "string") return `"'${value}'"`;
457
+ if (typeof value === "number" && isBigint) return `"${value}n"`;
458
+ if (typeof value === "number" || typeof value === "boolean") return `"${String(value)}"`;
459
+ if (value !== null && typeof value === "object") return "\"unknown\"";
460
+ return `"${JSON.stringify(value) ?? "null"}"`;
461
+ }
462
+ /** Whether an `allOf` member is a numeric primitive whose constraints can be merged into one definition. */
463
+ function isNumericMember(schema) {
464
+ return (schema.type === "number" || schema.type === "integer") && schema.$ref === void 0 && !hasCombinator(schema) && schema.enum === void 0 && schema.const === void 0 && !isInt64(schema) && schema.format !== "bigint";
465
+ }
466
+ /**
467
+ * Generate ArkType schema code from JSON Schema.
468
+ *
469
+ * @example
470
+ * ```ts
471
+ * arktype({ type: 'string' }, 'MySchema') // '"string"'
472
+ * ```
473
+ */
474
+ function arktype(schema, rootName = DEFAULT_ROOT_NAME, isArktype = false, options) {
475
+ if (hasParameterSerialization(options)) {
476
+ const inner = arktype(schema, rootName, isArktype, withoutParameterSerialization(options));
477
+ return arktypePreprocess(parameterReaders(schema, options, "data"), inner);
478
+ }
479
+ const expression = node(schema, rootName, isArktype, options);
480
+ if (!(isStringWireLocation(options?.paramIn) && schema["x-coerce"] !== false) || !isNullTextRead(schema)) return expression;
481
+ const nullFirst = isNullMatchedFirst(schema) ? expression : arktypeWrap(expression, { nullable: true }, { ...isArktype && { scopeMode: true } });
482
+ return arktypePreprocess([wireNullText("data")], nullFirst);
483
+ }
484
+ function node(schema, rootName, isArktype, options) {
485
+ const codeExtOpts = {
486
+ ...options?.unsafeCodeExtensions === true && { unsafeCodeExtensions: true },
487
+ ...isArktype && { scopeMode: true }
488
+ };
489
+ const arktypeWrap$1 = (arktypeStr, s) => arktypeWrap(arktypeStr, s, codeExtOpts);
490
+ const readonly = (v) => options?.readonly ? `${v}.readonly()` : v;
491
+ const isStringWireParam = isStringWireLocation(options?.paramIn);
492
+ const isWireCoerced = isStringWireParam && schema["x-coerce"] !== false;
493
+ const wireArray = (v) => isStringWireParam ? arktypePreprocess([wireArrayOnce("data")], v) : v;
494
+ const literalInput = (values) => {
495
+ if (values.every((v) => typeof v === "number")) {
496
+ if (isInt64(schema)) return bigintMorph(isWireCoerced);
497
+ if (isWireCoerced) return numberMorph("isFinite", "a number");
498
+ }
499
+ if (isWireCoerced && values.every((v) => typeof v === "boolean")) return stringbool();
500
+ };
501
+ const describeWithMessage = (expr, msg) => {
502
+ if (typeof msg !== "string") return expr;
503
+ const text = JSON.stringify(msg);
504
+ if (isArktype && isArktypeDefinition(expr)) return `[${expr},"@",${text}]`;
505
+ return `${isQuoted(expr) ? `type(${expr})` : expr}.describe(${text})`;
506
+ };
507
+ const unionOf = (schemas, message) => isWireCoerced && schemas.some(isMorph) ? wireUnion(schemas, message) : describeWithMessage(unionStr(schemas, isArktype), message);
508
+ if (schema.$ref) {
509
+ const emitRef = (name) => !isArktype && name !== rootName ? name : `"${name}"`;
510
+ const ref = (s) => {
511
+ if (isRootRef(s.$ref)) return `"${rootName}"`;
512
+ if (typeof s.$ref === "string" && isDeepLocalPointer(s.$ref)) return "\"unknown\"";
513
+ if (options?.openapi && s.$ref) {
514
+ const resolved = resolveOpenAPIRef(s.$ref);
515
+ if (resolved) return emitRef(resolved);
516
+ }
517
+ const toName = schemaNamer(options?.openapi);
518
+ for (const prefix of DEFINITION_REF_PREFIXES) if (s.$ref?.startsWith(prefix)) return emitRef(toName(s.$ref.slice(prefix.length)));
519
+ if (s.$ref?.startsWith("#")) {
520
+ const refName = s.$ref.slice(1);
521
+ return refName === "" ? `"${rootName}"` : emitRef(toName(refName));
522
+ }
523
+ return "\"unknown\"";
524
+ };
525
+ const items = itemsSchemaOf(schema.items);
526
+ if (schema.type === "array" && items?.$ref) return arktypeWrap$1(`${ref(items)}.array()`, schema);
527
+ return arktypeWrap$1(ref(schema), schema);
528
+ }
529
+ const impliedType = isWireCoerced ? impliedWireType(schema) : void 0;
530
+ if (impliedType !== void 0) return node({
531
+ ...schema,
532
+ type: impliedType
533
+ }, rootName, isArktype, options);
534
+ if (schema.oneOf) {
535
+ if (schema.oneOf.length === 0) return arktypeWrap$1("\"unknown\"", schema);
536
+ return arktypeWrap$1(unionOf(schema.oneOf.map((s) => arktype(s, rootName, isArktype, options)), schema["x-oneOf-message"]), schema);
537
+ }
538
+ if (schema.anyOf) {
539
+ if (schema.anyOf.length === 0) return arktypeWrap$1("\"unknown\"", schema);
540
+ return arktypeWrap$1(unionOf(schema.anyOf.map((s) => arktype(s, rootName, isArktype, options)), schema["x-implication-message"] ?? schema["x-anyOf-message"]), schema);
541
+ }
542
+ if (schema.allOf) {
543
+ if (schema.allOf.length === 0) return arktypeWrap$1("\"unknown\"", schema);
544
+ const nullable = isNullable(schema) || schema.allOf.some(isNullTypeMember);
545
+ const members = schema.allOf.filter((s) => !isShapelessMember(s));
546
+ if (isWireCoerced && members.length > 0 && members.every(isNumericMember)) {
547
+ const definitions = members.map((s) => s.type === "integer" ? integer(s) : number(s));
548
+ if (definitions.every(isQuoted)) {
549
+ const isInteger = members.some((s) => s.type === "integer");
550
+ const parts = definitions.map((d) => d.slice(1, -1)).filter((d) => d !== "number" && d !== "number.integer");
551
+ const merged = parts.length === 0 ? isInteger ? "\"number.integer\"" : "\"number\"" : `"${parts.join(" & ")}"`;
552
+ return arktypeWrap$1(wireNumeric(isInteger ? numberMorph("isSafeInteger", "an integer") : numberMorph("isFinite", "a number"), merged), {
553
+ ...schema,
554
+ nullable
555
+ });
556
+ }
557
+ }
558
+ const schemas = members.map((s) => arktype(s, rootName, isArktype, options));
559
+ if (schemas.length === 0) return arktypeWrap$1("\"unknown\"", {
560
+ ...schema,
561
+ nullable
562
+ });
563
+ return arktypeWrap$1(schemas.length === 1 ? schemas[0] : intersectionStr(schemas, isArktype), {
564
+ ...schema,
565
+ nullable
566
+ });
567
+ }
568
+ if (schema.not) {
569
+ const { not: inner, ...withoutNot } = schema;
570
+ if (typeof inner !== "object" || inner === null) return arktypeWrap$1("\"unknown\"", schema);
571
+ const notMessage = schema["x-not-message"];
572
+ const predicate = (() => {
573
+ const shared = notPredicate(inner, "data", "data: unknown");
574
+ if (shared !== void 0) return shared;
575
+ if (Array.isArray(inner.enum)) return `(data: unknown) => !${JSON.stringify(inner.enum)}.includes(data as never)`;
576
+ })();
577
+ if (withoutNot.type !== void 0) {
578
+ const base = arktype(withoutNot, rootName, isArktype, options);
579
+ if (!predicate) return base;
580
+ const narrowed = isArktype && isArktypeDefinition(base) ? `[${base},":",${predicate}]` : `${asRuntime(base)}.narrow(${predicate})`;
581
+ return notMessage ? describeWithMessage(narrowed, notMessage) : narrowed;
582
+ }
583
+ if (!predicate) return arktypeWrap$1("\"unknown\"", schema);
584
+ const base = `type("unknown").narrow(${predicate})`;
585
+ return arktypeWrap$1(notMessage ? `${base}.describe(${JSON.stringify(notMessage)})` : base, schema);
586
+ }
587
+ if (schema.const !== void 0) {
588
+ const constMessage = schema["x-const-message"] ?? schema["x-error-message"];
589
+ if (typeof schema.const === "string" && QUOTE_OR_BACKSLASH_PATTERN.test(schema.const)) {
590
+ const unit = `type.unit(${JSON.stringify(schema.const)})`;
591
+ return arktypeWrap$1(constMessage ? `${unit}.describe(${JSON.stringify(constMessage)})` : unit, schema);
592
+ }
593
+ const constExpr = formatConst(schema.const, isInt64(schema));
594
+ const literal = constMessage ? `type(${constExpr}).describe(${JSON.stringify(constMessage)})` : constExpr;
595
+ const input = literalInput([schema.const]);
596
+ return arktypeWrap$1(input ? wireNumeric(input, literal) : literal, schema);
597
+ }
598
+ if (schema.enum) {
599
+ const values = schema.enum.filter((value) => value !== null);
600
+ const input = values.length > 0 ? literalInput(values) : void 0;
601
+ if (input === void 0) return arktypeWrap$1(_enum(schema), schema);
602
+ const hasNull = values.length < schema.enum.length;
603
+ return arktypeWrap$1(wireNumeric(input, _enum({
604
+ ...schema,
605
+ enum: values
606
+ })), {
607
+ ...schema,
608
+ nullable: hasNull || isNullable(schema)
609
+ });
610
+ }
611
+ if (schema.properties) return readonly(arktypeWrap$1(object(schema, rootName, isArktype, options), schema));
612
+ const types = normalizeTypes(schema.type);
613
+ const primitive = (t) => {
614
+ if (t === "string") return string(schema);
615
+ if (t === "number") {
616
+ const definition = number(schema);
617
+ return isWireCoerced ? wireNumeric(numberMorph("isFinite", "a number"), definition) : definition;
618
+ }
619
+ if (t === "integer") {
620
+ if (isInt64(schema) || schema.format === "bigint") return integer(schema, { wire: isWireCoerced });
621
+ const definition = integer(schema);
622
+ return isWireCoerced ? wireNumeric(numberMorph("isSafeInteger", "an integer"), definition) : definition;
623
+ }
624
+ if (t !== "boolean") return void 0;
625
+ return isWireCoerced ? stringbool() : "\"boolean\"";
626
+ };
627
+ if (isPrimitiveUnion(types, isWireCoerced)) return arktypeWrap$1(unionOf(unionPrimitiveTypes(types, isWireCoerced).map(primitive).filter((m) => m !== void 0), void 0), schema);
628
+ for (const t of [
629
+ "string",
630
+ "number",
631
+ "integer",
632
+ "boolean"
633
+ ]) {
634
+ if (!types.includes(t)) continue;
635
+ const expression = primitive(t);
636
+ if (expression !== void 0) return arktypeWrap$1(expression, schema);
637
+ }
638
+ if (types.includes("array")) {
639
+ if (schema.prefixItems?.length) {
640
+ const items = schema.prefixItems.map((s) => arktype(s, rootName, isArktype, options));
641
+ const u = schema.unevaluatedItems;
642
+ const baseTuple = arktypeWrap$1(wireArray(describeWithMessage(isSchemaObject(u) ? (() => {
643
+ const rest = arktype(u, rootName, isArktype, options);
644
+ const restInner = isQuoted(rest) ? rest.slice(1, -1) : rest;
645
+ return `type([${items.join(",")},"...","${restInner}[]"])`;
646
+ })() : `type([${items.join(",")}])`, schema["x-prefixItems-message"])), schema);
647
+ const unevalItemsMessage = schema["x-unevaluatedItems-message"];
648
+ return u === false && unevalItemsMessage ? `${baseTuple}.describe(${JSON.stringify(unevalItemsMessage)})` : baseTuple;
649
+ }
650
+ const itemSchema = itemsSchemaOf(schema.items);
651
+ const items = itemSchema ? arktype(itemSchema, rootName, isArktype, options) : "\"unknown\"";
652
+ const base = isQuoted(items) ? `"${items.slice(1, -1)}[]"` : `type(${items}).array()`;
653
+ const { minItems, maxItems } = schema;
654
+ const isFixedLength = hasFixedItemCount(schema);
655
+ const lengthMessage = schema["x-length-message"];
656
+ const minItemsMessage = schema["x-minItems-message"] ?? lengthMessage;
657
+ const maxItemsMessage = schema["x-maxItems-message"] ?? lengthMessage;
658
+ const uniqueItemsMessage = schema["x-uniqueItems-message"];
659
+ const containsMessage = schema["x-contains-message"];
660
+ const minContainsMessage = schema["x-minContains-message"];
661
+ const maxContainsMessage = schema["x-maxContains-message"];
662
+ const fixedItemsMessage = minItemsMessage ?? maxItemsMessage;
663
+ const hasArrayMessage = [
664
+ minItemsMessage,
665
+ maxItemsMessage,
666
+ uniqueItemsMessage,
667
+ containsMessage,
668
+ minContainsMessage,
669
+ maxContainsMessage
670
+ ].some(Boolean);
671
+ const andWith = (a, b) => isArktype && isArktypeDefinition(a) ? `[${a},"&",${b}]` : `type(${a}).and(type(${b}))`;
672
+ const narrowWith = (a, fn) => isArktype && isArktypeDefinition(a) ? `[${a},":",${fn}]` : `${isArktypeDefinition(a) ? `type(${a})` : a}.narrow(${fn})`;
673
+ const lengthExpr = isFixedLength ? hasArrayMessage ? narrowWith(base, `(data: unknown[], ctx) => data.length === ${minItems} || ctx.mustBe(${JSON.stringify(fixedItemsMessage ?? `must contain exactly ${minItems} items`)})`) : andWith(base, `"unknown[] == ${minItems}"`) : typeof minItems === "number" && typeof maxItems === "number" ? hasArrayMessage ? narrowWith(narrowWith(base, `(data: unknown[], ctx) => data.length >= ${minItems} || ctx.mustBe(${JSON.stringify(minItemsMessage ?? `must contain at least ${minItems} items`)})`), `(data: unknown[], ctx) => data.length <= ${maxItems} || ctx.mustBe(${JSON.stringify(maxItemsMessage ?? `must contain at most ${maxItems} items`)})`) : andWith(base, `"${minItems} <= unknown[] <= ${maxItems}"`) : typeof minItems === "number" ? hasArrayMessage ? narrowWith(base, `(data: unknown[], ctx) => data.length >= ${minItems} || ctx.mustBe(${JSON.stringify(minItemsMessage ?? `must contain at least ${minItems} items`)})`) : andWith(base, `"unknown[] >= ${minItems}"`) : typeof maxItems === "number" ? hasArrayMessage ? narrowWith(base, `(data: unknown[], ctx) => data.length <= ${maxItems} || ctx.mustBe(${JSON.stringify(maxItemsMessage ?? `must contain at most ${maxItems} items`)})`) : andWith(base, `"unknown[] <= ${maxItems}"`) : base;
674
+ const uniqueExpr = schema.uniqueItems === true ? narrowWith(lengthExpr, `(data: unknown[], ctx) => new Set(data).size === data.length${uniqueItemsMessage ? ` || ctx.mustBe(${JSON.stringify(uniqueItemsMessage)})` : ""}`) : lengthExpr;
675
+ return arktypeWrap$1(wireArray(describeWithMessage((() => {
676
+ if (!schema.contains) return [];
677
+ const containsRt = asRuntime(arktype(schema.contains, rootName, isArktype, options));
678
+ const minC = schema.minContains;
679
+ const maxC = schema.maxContains;
680
+ if (minC === void 0 && maxC === void 0) return [`.narrow((data: unknown[], ctx) => data.some((item) => ${containsRt}.allows(item)) || ctx.mustBe(${JSON.stringify(containsMessage ?? "must contain at least one matching item")}))`];
681
+ const effectiveMin = minC ?? 1;
682
+ return [effectiveMin > 0 ? `.narrow((data: unknown[], ctx) => data.filter((item) => ${containsRt}.allows(item)).length >= ${effectiveMin} || ctx.mustBe(${JSON.stringify(minContainsMessage ?? `must contain at least ${effectiveMin} matching items`)}))` : void 0, maxC !== void 0 ? `.narrow((data: unknown[], ctx) => data.filter((item) => ${containsRt}.allows(item)).length <= ${maxC} || ctx.mustBe(${JSON.stringify(maxContainsMessage ?? `must contain at most ${maxC} matching items`)}))` : void 0].filter((v) => v !== void 0);
683
+ })().reduce((acc, narrow) => `${asRuntime(acc)}${narrow}`, uniqueExpr), schema["x-items-message"])), schema);
684
+ }
685
+ if (types.includes("object")) return readonly(arktypeWrap$1(object(schema, rootName, isArktype, options), schema));
686
+ if (types.includes("date")) {
687
+ if (isWireCoerced) return arktypeWrap$1("\"string.date.parse\"", schema);
688
+ return arktypeWrap$1("\"Date\"", schema);
689
+ }
690
+ if (types.length === 1 && types[0] === "null") return arktypeWrap$1("\"null\"", schema);
691
+ return arktypeWrap$1("\"unknown\"", schema);
692
+ }
693
+ //#endregion
694
+ //#region src/generator/arktype/index.ts
695
+ /**
696
+ * A whole JSON Schema document as an ArkType module. A document with definitions becomes
697
+ * a `scope({...}).export()` so members can name one another; one without is a bare
698
+ * `type(...)` export.
699
+ */
700
+ function schemaToArktype(schema, options) {
701
+ const exportType = options?.exportType ?? true;
702
+ const emitOptions = emitOptionsOf(options);
703
+ const prefix = emitOptions.unsafeCodeExtensions === true && findCodeExtensionKeysInSchema(schema).length > 0 ? [UNSAFE_GENERATED_MARKER] : [];
704
+ const toName = schemaNamer(emitOptions.openapi);
705
+ const plan = planDocument(schema, rootNameOf(schema, toName));
706
+ const { rootName } = plan;
707
+ if (plan.hasDefinitions) {
708
+ const defEntries = plan.orderedNames.map((name) => {
709
+ const def = plan.definitions[name];
710
+ if (!def) return missingDefinitionComment(name);
711
+ const pc = toName(name);
712
+ return `${pc}:${arktype(def, pc, true, emitOptions)}`;
713
+ });
714
+ const scopeBody = `const types = scope({${(plan.rootDefinition === void 0 ? [...defEntries, `${rootName}:${arktype(schema, rootName, true, emitOptions)}`] : defEntries).join(",")}}).export()`;
715
+ const usesType = /\btype[(.]/u.test(scopeBody);
716
+ return [
717
+ ...prefix,
718
+ `import { scope${usesType ? ", type" : ""} } from "arktype"`,
719
+ scopeBody,
720
+ `export const ${rootName} = types.${rootName}`,
721
+ ...exportType ? [`export type ${rootName} = typeof ${rootName}.infer`] : []
722
+ ].filter(Boolean).join("\n\n");
723
+ }
724
+ const rootSchema = arktype(schema, rootName, false, emitOptions);
725
+ const rootExpr = rootSchema.startsWith("type(") ? rootSchema : rootSchema.startsWith("\"") ? `type(${rootSchema})` : rootSchema;
726
+ const allOfMessage = schema.allOf && schema["x-allOf-message"];
727
+ if (allOfMessage) {
728
+ const innerName = `${rootName}Inner`;
729
+ const wrapped = `type('unknown').narrow((data, ctx) => {const result = ${innerName}(data); if (result instanceof type.errors) {for (const issue of result) ctx.reject({ message: ${issueMessageExpression(allOfMessage)}, path: issue.path }); return false;} return true;})`;
730
+ return [
731
+ ...prefix,
732
+ `import { type } from "arktype"`,
733
+ `const ${innerName} = ${rootExpr}`,
734
+ `export const ${rootName} = ${wrapped}`,
735
+ ...exportType ? [`export type ${rootName} = typeof ${innerName}.infer`] : []
736
+ ].filter(Boolean).join("\n\n");
737
+ }
738
+ return [
739
+ ...prefix,
740
+ `import { type } from "arktype"`,
741
+ `export const ${rootName} = ${rootExpr}`,
742
+ ...exportType ? [`export type ${rootName} = typeof ${rootName}.infer`] : []
743
+ ].filter(Boolean).join("\n\n");
744
+ }
745
+ //#endregion
746
+ export { arktype as n, schemaToArktype as t };