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,544 @@
1
+ import { $ as DEFINITION_REF_PREFIXES, D as isComposite, H as isStringWireLocation, M as isNullable, O as isDeepLocalPointer, R as isRootRef, S as hasFixedLength, V as isShapelessMember, X as DEFAULT_ROOT_NAME, c as normalizeTypes, j as isNullTypeMember, k as isDefaultOnlyMember, l as resolveOpenAPIRef, s as makeSafeKey, ut as NOT_KEYWORD_UNSUPPORTED_MARKER, y as hasCombinator } from "./utils-WNBq1HR0.js";
2
+ import { D as typeboxDefaultOpt, F as schemaNamer, I as cyclicDefinitionNames, L as hasRootSelfReference, M as planDocument, N as renderDefinitions, O as typeboxMetaOpts, P as rootNameOf, R as isOptionalByDefault, U as hasNotKeyword, j as missingDefinitionComment, k as typeboxRefOpt, r as typeboxWrap, z as itemsSchemaOf } from "./helper-Cfvb5UDq.js";
3
+ //#region src/generator/typebox/enum.ts
4
+ function lit(v) {
5
+ if (v === null) return "null";
6
+ if (typeof v === "string") return JSON.stringify(v);
7
+ if (typeof v === "number" || typeof v === "boolean") return String(v);
8
+ return JSON.stringify(v) ?? "null";
9
+ }
10
+ /**
11
+ * One enum member as a TypeBox type. TypeBox v1's `TLiteralValue` excludes `null`
12
+ * (string | number | boolean | bigint only), so a `null` member is `Type.Null()`, not
13
+ * `Type.Literal(null)`.
14
+ */
15
+ function member(v) {
16
+ return v === null ? "Type.Null()" : `Type.Literal(${lit(v)})`;
17
+ }
18
+ function _enum(schema, ref) {
19
+ const errorMessage = schema["x-enum-message"] ?? schema["x-error-message"];
20
+ const metaOpts = [
21
+ ...typeboxRefOpt(ref),
22
+ ...typeboxMetaOpts(schema),
23
+ ...typeboxDefaultOpt(schema)
24
+ ];
25
+ const optsParts = [errorMessage ? `errorMessage:${JSON.stringify(errorMessage)}` : void 0, ...metaOpts].filter((v) => v !== void 0);
26
+ const optsTrailer = optsParts.length > 0 ? `,{${optsParts.join(",")}}` : "";
27
+ if (!schema.enum || schema.enum.length === 0) return optsParts.length > 0 ? `Type.Any({${optsParts.join(",")}})` : "Type.Any()";
28
+ if (schema.enum.some(isComposite)) return optsParts.length > 0 ? `Type.Any({${optsParts.join(",")}})` : "Type.Any()";
29
+ if (schema.enum.length === 1) return schema.enum[0] === null ? `Type.Null(${optsParts.length > 0 ? `{${optsParts.join(",")}}` : ""})` : `Type.Literal(${lit(schema.enum[0])}${optsTrailer})`;
30
+ return `Type.Union([${schema.enum.map(member).join(",")}]${optsTrailer})`;
31
+ }
32
+ //#endregion
33
+ //#region src/generator/typebox/integer.ts
34
+ function integer(schema, ref) {
35
+ const errorMessage = schema["x-error-message"];
36
+ const requiredMessage = schema["x-required-message"];
37
+ const minMessage = schema["x-minimum-message"];
38
+ const maxMessage = schema["x-maximum-message"];
39
+ const exclusiveMinimumMessage = schema["x-exclusiveMinimum-message"];
40
+ const exclusiveMaximumMessage = schema["x-exclusiveMaximum-message"];
41
+ const multipleOfMessage = schema["x-multipleOf-message"];
42
+ const perKeywordEntries = [];
43
+ if (requiredMessage) perKeywordEntries.push(`required:${JSON.stringify(requiredMessage)}`);
44
+ if (minMessage) perKeywordEntries.push(`minimum:${JSON.stringify(minMessage)}`);
45
+ if (maxMessage) perKeywordEntries.push(`maximum:${JSON.stringify(maxMessage)}`);
46
+ if (exclusiveMinimumMessage) perKeywordEntries.push(`exclusiveMinimum:${JSON.stringify(exclusiveMinimumMessage)}`);
47
+ if (exclusiveMaximumMessage) perKeywordEntries.push(`exclusiveMaximum:${JSON.stringify(exclusiveMaximumMessage)}`);
48
+ if (multipleOfMessage) perKeywordEntries.push(`multipleOf:${JSON.stringify(multipleOfMessage)}`);
49
+ const errorMessageField = perKeywordEntries.length === 0 ? errorMessage ? `errorMessage:${JSON.stringify(errorMessage)}` : void 0 : `errorMessage:{${perKeywordEntries.join(",")}${errorMessage ? `,_:${JSON.stringify(errorMessage)}` : ""}}`;
50
+ const metaOpts = [...typeboxMetaOpts(schema), ...typeboxDefaultOpt(schema)];
51
+ if (schema.format === "bigint") {
52
+ const opts = [
53
+ ...typeboxRefOpt(ref),
54
+ schema.minimum !== void 0 ? `minimum:BigInt(${schema.minimum})` : void 0,
55
+ schema.maximum !== void 0 ? `maximum:BigInt(${schema.maximum})` : void 0,
56
+ errorMessageField,
57
+ ...metaOpts
58
+ ].filter((v) => v !== void 0);
59
+ if (opts.length > 0) return `Type.BigInt({${opts.join(",")}})`;
60
+ return "Type.BigInt()";
61
+ }
62
+ const opts = [
63
+ ...typeboxRefOpt(ref),
64
+ schema.minimum !== void 0 ? `minimum:${schema.minimum}` : void 0,
65
+ typeof schema.exclusiveMinimum === "number" ? `exclusiveMinimum:${schema.exclusiveMinimum}` : void 0,
66
+ schema.maximum !== void 0 ? `maximum:${schema.maximum}` : void 0,
67
+ typeof schema.exclusiveMaximum === "number" ? `exclusiveMaximum:${schema.exclusiveMaximum}` : void 0,
68
+ schema.multipleOf !== void 0 ? `multipleOf:${schema.multipleOf}` : void 0,
69
+ errorMessageField,
70
+ ...metaOpts
71
+ ].filter((v) => v !== void 0);
72
+ if (opts.length > 0) return `Type.Integer({${opts.join(",")}})`;
73
+ return "Type.Integer()";
74
+ }
75
+ //#endregion
76
+ //#region src/generator/typebox/number.ts
77
+ function number(schema, ref) {
78
+ const errorMessage = schema["x-error-message"];
79
+ const requiredMessage = schema["x-required-message"];
80
+ const minMessage = schema["x-minimum-message"];
81
+ const maxMessage = schema["x-maximum-message"];
82
+ const exclusiveMinimumMessage = schema["x-exclusiveMinimum-message"];
83
+ const exclusiveMaximumMessage = schema["x-exclusiveMaximum-message"];
84
+ const multipleOfMessage = schema["x-multipleOf-message"];
85
+ const perKeywordEntries = [];
86
+ if (requiredMessage) perKeywordEntries.push(`required:${JSON.stringify(requiredMessage)}`);
87
+ if (minMessage) perKeywordEntries.push(`minimum:${JSON.stringify(minMessage)}`);
88
+ if (maxMessage) perKeywordEntries.push(`maximum:${JSON.stringify(maxMessage)}`);
89
+ if (exclusiveMinimumMessage) perKeywordEntries.push(`exclusiveMinimum:${JSON.stringify(exclusiveMinimumMessage)}`);
90
+ if (exclusiveMaximumMessage) perKeywordEntries.push(`exclusiveMaximum:${JSON.stringify(exclusiveMaximumMessage)}`);
91
+ if (multipleOfMessage) perKeywordEntries.push(`multipleOf:${JSON.stringify(multipleOfMessage)}`);
92
+ const errorMessageField = perKeywordEntries.length === 0 ? errorMessage ? `errorMessage:${JSON.stringify(errorMessage)}` : void 0 : `errorMessage:{${perKeywordEntries.join(",")}${errorMessage ? `,_:${JSON.stringify(errorMessage)}` : ""}}`;
93
+ const opts = [
94
+ ...typeboxRefOpt(ref),
95
+ schema.minimum !== void 0 ? `minimum:${schema.minimum}` : void 0,
96
+ typeof schema.exclusiveMinimum === "number" ? `exclusiveMinimum:${schema.exclusiveMinimum}` : void 0,
97
+ schema.maximum !== void 0 ? `maximum:${schema.maximum}` : void 0,
98
+ typeof schema.exclusiveMaximum === "number" ? `exclusiveMaximum:${schema.exclusiveMaximum}` : void 0,
99
+ schema.multipleOf !== void 0 ? `multipleOf:${schema.multipleOf}` : void 0,
100
+ errorMessageField,
101
+ ...typeboxMetaOpts(schema),
102
+ ...typeboxDefaultOpt(schema)
103
+ ].filter((v) => v !== void 0);
104
+ if (opts.length > 0) return `Type.Number({${opts.join(",")}})`;
105
+ return "Type.Number()";
106
+ }
107
+ //#endregion
108
+ //#region src/generator/typebox/object.ts
109
+ /**
110
+ * Generate a TypeBox object schema for a JSON Schema object node.
111
+ *
112
+ * Combinators (oneOf/anyOf/allOf/not) delegate to the main `typebox` entry.
113
+ * JSON Schema 2020-12 keywords (`minProperties`, `maxProperties`,
114
+ * `propertyNames`, `patternProperties`, `dependentRequired`) are emitted as
115
+ * options on the `Type.Object(payload, opts)` constructor — TypeBox forwards
116
+ * these to AJV at runtime.
117
+ *
118
+ * Note: TypeBox has no native runtime refinement API, so all advanced
119
+ * keywords are passed through as JSON Schema options. Custom error messages
120
+ * (via `x-*-message` extensions) are not emitted because TypeBox / AJV require
121
+ * the optional `ajv-errors` plugin for that — we keep generation portable.
122
+ */
123
+ function object(schema, rootName, isTypebox, options) {
124
+ const childOptions = nestedTypeboxOptions(options);
125
+ if (hasCombinator(schema)) return typebox(schema, rootName, isTypebox, options);
126
+ if (typeof schema.additionalProperties === "object") {
127
+ const value = typebox(schema.additionalProperties, rootName, isTypebox, childOptions);
128
+ const recordOpts = [
129
+ ...typeboxRefOpt(options?.ref),
130
+ ...buildAdvancedOpts(schema, rootName, isTypebox, childOptions),
131
+ ...typeboxMetaOpts(schema),
132
+ ...typeboxDefaultOpt(schema)
133
+ ].filter((v) => v !== void 0);
134
+ return recordOpts.length === 0 ? `Type.Record(Type.String(),${value})` : `Type.Record(Type.String(),${value},{${recordOpts.join(",")}})`;
135
+ }
136
+ if (!schema.properties) {
137
+ if (schema.additionalProperties === true) {
138
+ const anyOpts = [
139
+ ...typeboxRefOpt(options?.ref),
140
+ ...typeboxMetaOpts(schema),
141
+ ...typeboxDefaultOpt(schema)
142
+ ];
143
+ return anyOpts.length === 0 ? "Type.Any()" : `Type.Any({${anyOpts.join(",")}})`;
144
+ }
145
+ const emptyOpts = [
146
+ ...typeboxRefOpt(options?.ref),
147
+ ...buildAdvancedOpts(schema, rootName, isTypebox, childOptions),
148
+ ...typeboxMetaOpts(schema),
149
+ ...typeboxDefaultOpt(schema)
150
+ ].filter((v) => v !== void 0);
151
+ return emptyOpts.length === 0 ? "Type.Object({})" : `Type.Object({},{${emptyOpts.join(",")}})`;
152
+ }
153
+ const required = new Set(schema.required);
154
+ const props = Object.entries(schema.properties).map(([key, propSchema]) => {
155
+ const parsed = typebox(propSchema, rootName, isTypebox, childOptions);
156
+ if (!parsed) return null;
157
+ const safeKey = makeSafeKey(key);
158
+ return required.has(key) || isOptionalByDefault(propSchema) ? `${safeKey}:${parsed}` : `${safeKey}:Type.Optional(${parsed})`;
159
+ }).filter((p) => p !== null);
160
+ const objectErrorMessageEntries = [];
161
+ const objectErrorMessage = schema["x-error-message"];
162
+ if (objectErrorMessage) objectErrorMessageEntries.push(`type:${JSON.stringify(objectErrorMessage)}`);
163
+ const objectMinPropertiesMessage = schema["x-minProperties-message"];
164
+ if (objectMinPropertiesMessage) objectErrorMessageEntries.push(`minProperties:${JSON.stringify(objectMinPropertiesMessage)}`);
165
+ const objectMaxPropertiesMessage = schema["x-maxProperties-message"];
166
+ if (objectMaxPropertiesMessage) objectErrorMessageEntries.push(`maxProperties:${JSON.stringify(objectMaxPropertiesMessage)}`);
167
+ const objectAdditionalPropertiesMessage = schema["x-additionalProperties-message"];
168
+ if (objectAdditionalPropertiesMessage) objectErrorMessageEntries.push(`additionalProperties:${JSON.stringify(objectAdditionalPropertiesMessage)}`);
169
+ const objectPropertyNamesMessage = schema["x-propertyNames-message"];
170
+ if (objectPropertyNamesMessage) objectErrorMessageEntries.push(`propertyNames:${JSON.stringify(objectPropertyNamesMessage)}`);
171
+ const objectPatternPropertiesMessage = schema["x-patternProperties-message"];
172
+ if (objectPatternPropertiesMessage) objectErrorMessageEntries.push(`patternProperties:${JSON.stringify(objectPatternPropertiesMessage)}`);
173
+ const objectDependentRequiredMessage = schema["x-dependentRequired-message"];
174
+ if (objectDependentRequiredMessage) objectErrorMessageEntries.push(`dependentRequired:${JSON.stringify(objectDependentRequiredMessage)}`);
175
+ const objectDependentSchemasMessage = schema["x-dependentSchemas-message"];
176
+ if (objectDependentSchemasMessage) objectErrorMessageEntries.push(`dependentSchemas:${JSON.stringify(objectDependentSchemasMessage)}`);
177
+ const objectRequiredMessage = schema["x-required-message"];
178
+ if (objectRequiredMessage) objectErrorMessageEntries.push(`required:${JSON.stringify(objectRequiredMessage)}`);
179
+ const objectPropertiesMessage = schema["x-properties-message"];
180
+ if (objectPropertiesMessage) objectErrorMessageEntries.push(`properties:${JSON.stringify(objectPropertiesMessage)}`);
181
+ const objectIfMessage = schema["x-if-message"];
182
+ const objectThenMessage = schema["x-then-message"] ?? objectIfMessage;
183
+ if (objectThenMessage) objectErrorMessageEntries.push(`then:${JSON.stringify(objectThenMessage)}`);
184
+ const objectElseMessage = schema["x-else-message"] ?? objectIfMessage;
185
+ if (objectElseMessage) objectErrorMessageEntries.push(`else:${JSON.stringify(objectElseMessage)}`);
186
+ const objectUnevaluatedPropertiesMessage = schema["x-unevaluatedProperties-message"];
187
+ if (objectUnevaluatedPropertiesMessage) objectErrorMessageEntries.push(`unevaluatedProperties:${JSON.stringify(objectUnevaluatedPropertiesMessage)}`);
188
+ const objectErrorMessageField = objectErrorMessageEntries.length > 0 ? `errorMessage:{${objectErrorMessageEntries.join(",")}}` : void 0;
189
+ const optParts = [
190
+ ...typeboxRefOpt(options?.ref),
191
+ schema.additionalProperties === false ? "additionalProperties:false" : void 0,
192
+ ...buildAdvancedOpts(schema, rootName, isTypebox, childOptions),
193
+ objectErrorMessageField,
194
+ ...typeboxMetaOpts(schema),
195
+ ...typeboxDefaultOpt(schema)
196
+ ].filter((v) => v !== void 0);
197
+ const opts = optParts.length > 0 ? `,{${optParts.join(",")}}` : "";
198
+ return `Type.Object({${props.join(",")}}${opts})`;
199
+ }
200
+ /**
201
+ * Build TypeBox option entries for advanced JSON Schema 2020-12 keywords.
202
+ * Returns an array of `'key:value'` strings ready to be joined into `{...}`.
203
+ */
204
+ function buildAdvancedOpts(schema, rootName, isTypebox, options) {
205
+ const propertyNamesOpt = schema.propertyNames ? `propertyNames:${typebox(schema.propertyNames, rootName, isTypebox, options)}` : void 0;
206
+ const patternPropertiesOpt = schema.patternProperties ? `patternProperties:{${Object.entries(schema.patternProperties).map(([pattern, propSchema]) => `${JSON.stringify(pattern)}:${typebox(propSchema, rootName, isTypebox, options)}`).join(",")}}` : void 0;
207
+ const dependentRequiredOpt = schema.dependentRequired ? `dependentRequired:{${Object.entries(schema.dependentRequired).map(([key, deps]) => `${JSON.stringify(key)}:${JSON.stringify(deps)}`).join(",")}}` : void 0;
208
+ const ifOpt = schema.if ? `if:${typebox(schema.if, rootName, isTypebox, options)}` : void 0;
209
+ const thenOpt = schema.then ? `then:${typebox(schema.then, rootName, isTypebox, options)}` : void 0;
210
+ const elseOpt = schema.else ? `else:${typebox(schema.else, rootName, isTypebox, options)}` : void 0;
211
+ const requiredOpt = !schema.properties && Array.isArray(schema.required) && schema.required.length > 0 ? `required:${JSON.stringify(schema.required)}` : void 0;
212
+ return [
213
+ typeof schema.minProperties === "number" ? `minProperties:${schema.minProperties}` : void 0,
214
+ typeof schema.maxProperties === "number" ? `maxProperties:${schema.maxProperties}` : void 0,
215
+ propertyNamesOpt,
216
+ patternPropertiesOpt,
217
+ dependentRequiredOpt,
218
+ ifOpt,
219
+ thenOpt,
220
+ elseOpt,
221
+ requiredOpt
222
+ ];
223
+ }
224
+ //#endregion
225
+ //#region src/generator/typebox/string.ts
226
+ const FORMAT_MAP = {
227
+ email: "email",
228
+ uuid: "uuid",
229
+ uri: "uri",
230
+ ipv4: "ipv4",
231
+ ipv6: "ipv6",
232
+ "date-time": "date-time",
233
+ date: "date",
234
+ time: "time"
235
+ };
236
+ function escapeRegex(s) {
237
+ return s.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&");
238
+ }
239
+ function string(schema, ref) {
240
+ const errorMessage = schema["x-error-message"];
241
+ const requiredMessage = schema["x-required-message"];
242
+ const patternMessage = schema["x-pattern-message"];
243
+ const minLengthMessage = schema["x-minLength-message"];
244
+ const maxLengthMessage = schema["x-maxLength-message"];
245
+ const perKeywordEntries = [];
246
+ if (requiredMessage) perKeywordEntries.push(`required:${JSON.stringify(requiredMessage)}`);
247
+ if (patternMessage) perKeywordEntries.push(`pattern:${JSON.stringify(patternMessage)}`);
248
+ if (minLengthMessage) perKeywordEntries.push(`minLength:${JSON.stringify(minLengthMessage)}`);
249
+ if (maxLengthMessage) perKeywordEntries.push(`maxLength:${JSON.stringify(maxLengthMessage)}`);
250
+ const errorMessageField = perKeywordEntries.length === 0 ? errorMessage ? `errorMessage:${JSON.stringify(errorMessage)}` : void 0 : `errorMessage:{${perKeywordEntries.join(",")}${errorMessage ? `,_:${JSON.stringify(errorMessage)}` : ""}}`;
251
+ const isFixedLength = hasFixedLength(schema);
252
+ const contentPattern = (() => {
253
+ if (schema.pattern) return void 0;
254
+ const parts = [];
255
+ if (typeof schema["x-startsWith"] === "string") parts.push(`^${escapeRegex(schema["x-startsWith"])}`);
256
+ if (typeof schema["x-endsWith"] === "string") parts.push(`${escapeRegex(schema["x-endsWith"])}$`);
257
+ if (typeof schema["x-includes"] === "string") parts.push(escapeRegex(schema["x-includes"]));
258
+ return parts.length > 0 ? parts.join("|") : void 0;
259
+ })();
260
+ const opts = [
261
+ ...typeboxRefOpt(ref),
262
+ schema.format && FORMAT_MAP[schema.format] ? `format:${JSON.stringify(FORMAT_MAP[schema.format])}` : void 0,
263
+ schema.pattern ? `pattern:${JSON.stringify(schema.pattern)}` : contentPattern ? `pattern:${JSON.stringify(contentPattern)}` : void 0,
264
+ isFixedLength ? `minLength:${schema.minLength}` : void 0,
265
+ isFixedLength ? `maxLength:${schema.maxLength}` : void 0,
266
+ !isFixedLength && schema.minLength !== void 0 ? `minLength:${schema.minLength}` : void 0,
267
+ !isFixedLength && schema.maxLength !== void 0 ? `maxLength:${schema.maxLength}` : void 0,
268
+ errorMessageField,
269
+ ...typeboxMetaOpts(schema),
270
+ ...typeboxDefaultOpt(schema)
271
+ ].filter((v) => v !== void 0);
272
+ const stringExpr = opts.length > 0 ? `Type.String({${opts.join(",")}})` : "Type.String()";
273
+ const transforms = [];
274
+ if (schema["x-trim"] === true) transforms.push(".trim()");
275
+ if (schema["x-toLowerCase"] === true) transforms.push(".toLowerCase()");
276
+ if (schema["x-toUpperCase"] === true) transforms.push(".toUpperCase()");
277
+ if (typeof schema["x-normalize"] === "string") transforms.push(`.normalize(${JSON.stringify(schema["x-normalize"])})`);
278
+ if (transforms.length > 0) return `Codec(${stringExpr}).Decode((value: string) => value${transforms.join("")}).Encode((value: string) => value)`;
279
+ return stringExpr;
280
+ }
281
+ //#endregion
282
+ //#region src/generator/typebox/typebox.ts
283
+ /**
284
+ * Options for a nested TypeBox node: the same as `options` but without a
285
+ * host `ref`, so only the outermost factory of a declaration receives it.
286
+ */
287
+ function nestedTypeboxOptions(options) {
288
+ if (options === void 0) return void 0;
289
+ return {
290
+ ...options.openapi !== void 0 && { openapi: options.openapi },
291
+ ...options.readonly !== void 0 && { readonly: options.readonly },
292
+ ...options.paramIn !== void 0 && { paramIn: options.paramIn },
293
+ ...options.cyclicRefs !== void 0 && { cyclicRefs: options.cyclicRefs }
294
+ };
295
+ }
296
+ /**
297
+ * Emits a single-argument TypeBox factory call (`Type.X({opts})`), embedding
298
+ * any meta options from the schema. Returns `Type.X()` when no options.
299
+ */
300
+ function tbPrim(name, schema, extraOpts = [], ref) {
301
+ const opts = [
302
+ ...typeboxRefOpt(ref),
303
+ ...extraOpts,
304
+ ...typeboxMetaOpts(schema),
305
+ ...typeboxDefaultOpt(schema)
306
+ ];
307
+ return opts.length === 0 ? `${name}()` : `${name}({${opts.join(",")}})`;
308
+ }
309
+ /**
310
+ * The `Type.String(...)` input of a string-wire coercion `Codec`. A query/path
311
+ * default is carried here in its string-wire form (`{default:'1'}`), since the
312
+ * Codec decodes from a string. A host `ref` lands on this inner `Type.String`,
313
+ * not on the `Codec(...)` wrapper.
314
+ */
315
+ function wireString(schema, ref) {
316
+ const opts = [...typeboxRefOpt(ref), ...typeboxDefaultOpt(schema, true)];
317
+ return opts.length > 0 ? `Type.String({${opts.join(",")}})` : "Type.String()";
318
+ }
319
+ /**
320
+ * Emits a two-argument TypeBox factory call (`Type.X(payload, {opts})`),
321
+ * embedding any meta options from the schema. Returns `Type.X(payload)` when
322
+ * no options.
323
+ */
324
+ function tbComp(name, payload, schema, extraOpts = [], ref) {
325
+ const opts = [
326
+ ...typeboxRefOpt(ref),
327
+ ...extraOpts,
328
+ ...typeboxMetaOpts(schema),
329
+ ...typeboxDefaultOpt(schema)
330
+ ];
331
+ return opts.length === 0 ? `${name}(${payload})` : `${name}(${payload},{${opts.join(",")}})`;
332
+ }
333
+ /** A reference to a peer of a `Type.Cyclic` map, reached by name. */
334
+ function byName(name, s) {
335
+ return tbComp("Type.Ref", `'${name}'`, s);
336
+ }
337
+ function messageOpt(msg) {
338
+ return typeof msg === "string" ? [`errorMessage:${JSON.stringify(msg)}`] : [];
339
+ }
340
+ function typebox(schema, rootName = DEFAULT_ROOT_NAME, isTypebox = false, options) {
341
+ const isStringWireParam = isStringWireLocation(options?.paramIn) && schema["x-coerce"] !== false;
342
+ const readonly = (v) => options?.readonly ? `Type.Readonly(${v})` : v;
343
+ const hostRef = options?.ref;
344
+ const childOptions = nestedTypeboxOptions(options);
345
+ const named = (name, s) => options?.cyclicRefs?.has(name) ? byName(name, s) : name;
346
+ if (schema.$ref) {
347
+ const ref = (s) => {
348
+ if (isRootRef(s.$ref)) return byName(rootName, s);
349
+ if (typeof s.$ref === "string" && isDeepLocalPointer(s.$ref)) return "Type.Unknown()";
350
+ if (options?.openapi && s.$ref) {
351
+ const resolved = resolveOpenAPIRef(s.$ref);
352
+ if (resolved) return resolved === rootName ? byName(resolved, s) : named(resolved, s);
353
+ }
354
+ const toName = schemaNamer(options?.openapi);
355
+ for (const prefix of DEFINITION_REF_PREFIXES) if (s.$ref?.startsWith(prefix)) return named(toName(s.$ref.slice(prefix.length)), s);
356
+ if (s.$ref?.startsWith("#")) {
357
+ const refName = s.$ref.slice(1);
358
+ return refName === "" ? named(rootName, s) : named(toName(refName), s);
359
+ }
360
+ if (s.$ref?.includes("#")) return "Type.Unknown()";
361
+ if (s.$ref?.startsWith("http")) {
362
+ const last = s.$ref.split("/").at(-1);
363
+ if (last) return last.replace(/\.json$/, "");
364
+ }
365
+ return "Type.Any()";
366
+ };
367
+ const items = itemsSchemaOf(schema.items);
368
+ if (schema.type === "array" && items?.$ref) return `Type.Array(${typeboxWrap(ref(items), items)})`;
369
+ return typeboxWrap(ref(schema), schema);
370
+ }
371
+ if (schema.oneOf) {
372
+ if (schema.oneOf.length === 0) return typeboxWrap(tbPrim("Type.Any", schema, [], hostRef), schema);
373
+ const schemas = schema.oneOf.map((s) => typebox(s, rootName, isTypebox, childOptions));
374
+ return typeboxWrap(tbComp("Type.Union", `[${schemas.join(",")}]`, schema, messageOpt(schema["x-oneOf-message"]), hostRef), schema);
375
+ }
376
+ if (schema.anyOf) {
377
+ if (schema.anyOf.length === 0) return typeboxWrap(tbPrim("Type.Any", schema, [], hostRef), schema);
378
+ const schemas = schema.anyOf.map((s) => typebox(s, rootName, isTypebox, childOptions));
379
+ const anyOfMessage = schema["x-implication-message"] ?? schema["x-anyOf-message"];
380
+ return typeboxWrap(tbComp("Type.Union", `[${schemas.join(",")}]`, schema, messageOpt(anyOfMessage), hostRef), schema);
381
+ }
382
+ if (schema.allOf) {
383
+ if (schema.allOf.length === 0) return typeboxWrap(tbPrim("Type.Any", schema, [], hostRef), schema);
384
+ const nullable = isNullable(schema) || schema.allOf.some(isNullTypeMember);
385
+ const defaultValue = schema.allOf.find(isDefaultOnlyMember)?.default;
386
+ const schemas = schema.allOf.filter((s) => !isShapelessMember(s)).map((s) => typebox(s, rootName, isTypebox, childOptions));
387
+ if (schemas.length === 0) return typeboxWrap(tbPrim("Type.Any", schema, [], hostRef), {
388
+ ...schema,
389
+ nullable
390
+ });
391
+ const baseResult = schemas.length === 1 ? schemas[0] : tbComp("Type.Intersect", `[${schemas.join(",")}]`, schema, messageOpt(schema["x-allOf-message"]), hostRef);
392
+ if (defaultValue !== void 0) {
393
+ const formatLiteral = typeof defaultValue === "boolean" || typeof defaultValue === "number" ? `${defaultValue}` : JSON.stringify(defaultValue);
394
+ const intersectOpts = [
395
+ ...typeboxRefOpt(hostRef),
396
+ ...messageOpt(schema["x-allOf-message"]),
397
+ `default:${formatLiteral}`
398
+ ];
399
+ const withDefault = `Type.Optional(${`Type.Intersect([${schemas.join(",")}],{${intersectOpts.join(",")}})`})`;
400
+ return nullable ? `Type.Union([${withDefault},Type.Null()])` : withDefault;
401
+ }
402
+ return typeboxWrap(baseResult, {
403
+ ...schema,
404
+ nullable
405
+ });
406
+ }
407
+ if (schema.not) return typeboxWrap(tbPrim("Type.Any", schema, messageOpt(schema["x-not-message"]), hostRef), schema);
408
+ if (schema.const !== void 0) {
409
+ const constMessage = schema["x-const-message"] ?? schema["x-error-message"];
410
+ if (schema.const === null) return typeboxWrap(tbPrim("Type.Null", schema, messageOpt(constMessage), hostRef), schema);
411
+ if (typeof schema.const === "object") return typeboxWrap(tbPrim("Type.Any", schema, messageOpt(constMessage), hostRef), schema);
412
+ return typeboxWrap(tbComp("Type.Literal", JSON.stringify(schema.const), schema, messageOpt(constMessage), hostRef), schema);
413
+ }
414
+ if (schema.enum) return typeboxWrap(_enum(schema, hostRef), schema);
415
+ if (schema.properties) return readonly(typeboxWrap(object(schema, rootName, isTypebox, options), schema));
416
+ const types = normalizeTypes(schema.type);
417
+ if (types.includes("string")) return typeboxWrap(string(schema, hostRef), schema);
418
+ if (types.includes("number")) {
419
+ const base = number(schema, hostRef);
420
+ if (isStringWireParam) {
421
+ const wire = wireString(schema, hostRef);
422
+ return typeboxWrap(`Codec(${wire}).Decode((value)=>Number(value)).Encode((value)=>String(value))`, schema);
423
+ }
424
+ return typeboxWrap(base, schema);
425
+ }
426
+ if (types.includes("integer")) {
427
+ const base = integer(schema, hostRef);
428
+ if (isStringWireParam) {
429
+ const wire = wireString(schema, hostRef);
430
+ return typeboxWrap(`Codec(${wire}).Decode((value)=>Number.parseInt(value,10)).Encode((value)=>String(value))`, schema);
431
+ }
432
+ return typeboxWrap(base, schema);
433
+ }
434
+ if (types.includes("boolean")) {
435
+ if (isStringWireParam) {
436
+ const unionOpts = [...typeboxRefOpt(hostRef), ...typeboxDefaultOpt(schema, true)];
437
+ const union = unionOpts.length > 0 ? `Type.Union([Type.Literal('true'),Type.Literal('false')],{${unionOpts.join(",")}})` : `Type.Union([Type.Literal('true'),Type.Literal('false')])`;
438
+ return typeboxWrap(`Codec(${union}).Decode((value)=>value==='true').Encode((value)=>value?'true':'false')`, schema);
439
+ }
440
+ return typeboxWrap(tbPrim("Type.Boolean", schema, [], hostRef), schema);
441
+ }
442
+ if (types.includes("array")) {
443
+ if (schema.prefixItems?.length) {
444
+ const items = schema.prefixItems.map((s) => typebox(s, rootName, isTypebox, childOptions));
445
+ const prefixItemsMessage = schema["x-prefixItems-message"];
446
+ const tupleOpts = prefixItemsMessage ? [`errorMessage:{prefixItems:${JSON.stringify(prefixItemsMessage)},items:${JSON.stringify(prefixItemsMessage)}}`] : [];
447
+ return readonly(typeboxWrap(tbComp("Type.Tuple", `[${items.join(",")}]`, schema, tupleOpts, hostRef), schema));
448
+ }
449
+ const itemSchema = itemsSchemaOf(schema.items);
450
+ const items = itemSchema ? typebox(itemSchema, rootName, isTypebox, childOptions) : "Type.Any()";
451
+ const arrayErrorMessageEntries = [];
452
+ const arrayErrorMessage = schema["x-error-message"];
453
+ if (arrayErrorMessage) arrayErrorMessageEntries.push(`type:${JSON.stringify(arrayErrorMessage)}`);
454
+ const arrayLengthMessage = schema["x-length-message"];
455
+ const arrayMinItemsMessage = schema["x-minItems-message"] ?? (typeof schema.minItems === "number" ? arrayLengthMessage : void 0);
456
+ if (arrayMinItemsMessage) arrayErrorMessageEntries.push(`minItems:${JSON.stringify(arrayMinItemsMessage)}`);
457
+ const arrayMaxItemsMessage = schema["x-maxItems-message"] ?? (typeof schema.maxItems === "number" ? arrayLengthMessage : void 0);
458
+ if (arrayMaxItemsMessage) arrayErrorMessageEntries.push(`maxItems:${JSON.stringify(arrayMaxItemsMessage)}`);
459
+ const arrayUniqueItemsMessage = schema["x-uniqueItems-message"];
460
+ if (arrayUniqueItemsMessage) arrayErrorMessageEntries.push(`uniqueItems:${JSON.stringify(arrayUniqueItemsMessage)}`);
461
+ const arrayContainsMessage = schema["x-contains-message"];
462
+ if (arrayContainsMessage) arrayErrorMessageEntries.push(`contains:${JSON.stringify(arrayContainsMessage)}`);
463
+ const arrayMinContainsMessage = schema["x-minContains-message"];
464
+ if (arrayMinContainsMessage) arrayErrorMessageEntries.push(`minContains:${JSON.stringify(arrayMinContainsMessage)}`);
465
+ const arrayMaxContainsMessage = schema["x-maxContains-message"];
466
+ if (arrayMaxContainsMessage) arrayErrorMessageEntries.push(`maxContains:${JSON.stringify(arrayMaxContainsMessage)}`);
467
+ const arrayItemsMessage = schema["x-items-message"];
468
+ if (arrayItemsMessage) arrayErrorMessageEntries.push(`items:${JSON.stringify(arrayItemsMessage)}`);
469
+ const arrayUnevaluatedItemsMessage = schema["x-unevaluatedItems-message"];
470
+ if (arrayUnevaluatedItemsMessage) arrayErrorMessageEntries.push(`unevaluatedItems:${JSON.stringify(arrayUnevaluatedItemsMessage)}`);
471
+ const arrayOpts = [
472
+ typeof schema.minItems === "number" ? `minItems:${schema.minItems}` : void 0,
473
+ typeof schema.maxItems === "number" ? `maxItems:${schema.maxItems}` : void 0,
474
+ schema.uniqueItems === true ? `uniqueItems:true` : void 0,
475
+ arrayErrorMessageEntries.length > 0 ? `errorMessage:{${arrayErrorMessageEntries.join(",")}}` : void 0
476
+ ].filter((v) => v !== void 0);
477
+ return readonly(typeboxWrap(tbComp("Type.Array", items, schema, arrayOpts, hostRef), schema));
478
+ }
479
+ if (types.includes("object")) return readonly(typeboxWrap(object(schema, rootName, isTypebox, options), schema));
480
+ if (types.includes("date")) {
481
+ const wire = wireString(schema, hostRef);
482
+ return typeboxWrap(`Codec(${wire}).Decode((value)=>new Date(value)).Encode((value)=>value.toISOString())`, schema);
483
+ }
484
+ if (types.length === 1 && types[0] === "null") return typeboxWrap(tbPrim("Type.Null", schema, [], hostRef), schema);
485
+ return typeboxWrap(tbPrim("Type.Any", schema, [], hostRef), schema);
486
+ }
487
+ //#endregion
488
+ //#region src/generator/typebox/index.ts
489
+ /** The import line, carrying `Codec` only when the emitted source calls it. */
490
+ function importLine(emitted) {
491
+ return `import { ${emitted.includes("Codec(") ? "Codec, " : ""}Type, type Static } from 'typebox'`;
492
+ }
493
+ /**
494
+ * A whole JSON Schema document as a TypeBox module. A `$ref` cycle cannot be expressed
495
+ * with plain `const` declarations, so a cyclic document becomes one
496
+ * `Type.Cyclic($defs, root)` map instead.
497
+ */
498
+ function schemaToTypebox(schema, options) {
499
+ const exportType = options?.exportType ?? true;
500
+ const openapi = options?.openapi ?? false;
501
+ const hostRef = options?.ref;
502
+ const genOptions = {
503
+ openapi,
504
+ readonly: options?.readonly ?? false,
505
+ ...options?.paramIn !== void 0 && { paramIn: options.paramIn }
506
+ };
507
+ const rootOptions = hostRef === void 0 ? genOptions : {
508
+ ...genOptions,
509
+ ref: hostRef
510
+ };
511
+ const notKeywordPresent = hasNotKeyword(schema);
512
+ const toName = schemaNamer(openapi);
513
+ const plan = planDocument(schema, rootNameOf(schema, toName));
514
+ const { rootName } = plan;
515
+ if (hasRootSelfReference(plan.root, (ref) => isRootRef(ref) || openapi && resolveOpenAPIRef(ref) === rootName) || cyclicDefinitionNames(schema).size > 0) {
516
+ const cyclicRefs = /* @__PURE__ */ new Set([...plan.orderedNames.map(toName), rootName]);
517
+ const cyclicOptions = {
518
+ ...genOptions,
519
+ cyclicRefs
520
+ };
521
+ const cyclicExport = `export const ${rootName} = Type.Cyclic({\n${[...plan.nonRootNames.map((name) => {
522
+ const def = plan.definitions[name];
523
+ const pc = toName(name);
524
+ return def ? `${pc}: ${typebox(def, pc, true, cyclicOptions)}` : missingDefinitionComment(name);
525
+ }), `${rootName}: ${typebox(plan.root, rootName, true, cyclicOptions)}`].join(",\n")}\n},'${rootName}'${hostRef === void 0 ? "" : `,{ref:${JSON.stringify(hostRef)}}`})`;
526
+ return [
527
+ ...notKeywordPresent ? [NOT_KEYWORD_UNSUPPORTED_MARKER] : [],
528
+ importLine(cyclicExport),
529
+ cyclicExport,
530
+ ...exportType ? [`export type ${rootName} = Static<typeof ${rootName}>`] : []
531
+ ].filter(Boolean).join("\n\n");
532
+ }
533
+ const schemaDefsCode = renderDefinitions(plan, toName, (def, name) => `const ${name} = ${typebox(def, name, true, genOptions)}`);
534
+ const rootExport = `export const ${rootName} = ${typebox(plan.root, rootName, true, rootOptions)}`;
535
+ return [
536
+ ...notKeywordPresent ? [NOT_KEYWORD_UNSUPPORTED_MARKER] : [],
537
+ importLine(`${schemaDefsCode}\n${rootExport}`),
538
+ schemaDefsCode,
539
+ rootExport,
540
+ ...exportType ? [`export type ${rootName} = Static<typeof ${rootName}>`] : []
541
+ ].filter(Boolean).join("\n\n");
542
+ }
543
+ //#endregion
544
+ export { nestedTypeboxOptions as n, typebox as r, schemaToTypebox as t };
@@ -0,0 +1,21 @@
1
+ import { r as JSONSchema } from "./index-DbV3dEmN.js";
2
+ import { n as GenerateOptions } from "./index-C2L8Ty0-.js";
3
+ //#region src/generator/typebox/index.d.ts
4
+ /** The options of `schemaToTypebox`: the common ones, plus a host `$ref` name. */
5
+ export type TypeboxGenerateOptions = Omit<GenerateOptions, 'unsafeCodeExtensions'> & {
6
+ /**
7
+ * Host `$ref` name for OpenAPI component registration. TypeBox has no
8
+ * post-construction `.meta()`, so this lands in the outermost builder's
9
+ * options (`Type.String({ref})`, `Type.Object({…},{ref})`, or the third
10
+ * argument of `Type.Cyclic`). Named `$defs` members are not given this
11
+ * value. Omit it and the emit is unchanged.
12
+ */
13
+ readonly ref?: string;
14
+ };
15
+ /**
16
+ * A whole JSON Schema document as a TypeBox module. A `$ref` cycle cannot be expressed
17
+ * with plain `const` declarations, so a cyclic document becomes one
18
+ * `Type.Cyclic($defs, root)` map instead.
19
+ */
20
+ export declare function schemaToTypebox(schema: JSONSchema, options?: TypeboxGenerateOptions): string;
21
+ //#endregion
@@ -0,0 +1 @@
1
+ export { t as schemaToTypebox } from "./typebox-BdWJv3ND.js";