schema-truth 0.8.1 → 0.8.3

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 (38) hide show
  1. package/README.md +1 -1
  2. package/dist/{ajv-DS9gtNZC.js → ajv-DejgT2o1.js} +8 -14
  3. package/dist/ajv.d.ts +2 -4
  4. package/dist/ajv.js +1 -1
  5. package/dist/{arktype-CRZ8vXZ5.js → arktype-CzTltPwP.js} +94 -55
  6. package/dist/arktype.d.ts +3 -5
  7. package/dist/arktype.js +1 -1
  8. package/dist/cli/ajv.js +3 -4
  9. package/dist/cli/arktype.js +3 -4
  10. package/dist/cli/effect.js +3 -4
  11. package/dist/cli/typebox.js +3 -4
  12. package/dist/cli/valibot.js +3 -4
  13. package/dist/cli/yup.js +3 -4
  14. package/dist/cli/zod.js +3 -4
  15. package/dist/{cli-eAY8LqwP.js → cli-71Np9i5L.js} +6 -9
  16. package/dist/{effect-BkWovUi3.js → effect-Dj8qARFi.js} +70 -44
  17. package/dist/effect.d.ts +3 -5
  18. package/dist/effect.js +1 -1
  19. package/dist/{helper-CbeedY35.js → helper-WSNbEQKr.js} +1398 -52
  20. package/dist/{index-G7UqNQ4w.d.ts → index-DLVjyrKu.d.ts} +0 -14
  21. package/dist/{index-DYzAccyT.d.ts → index-DU2Nd8eI.d.ts} +2 -6
  22. package/dist/index.d.ts +11 -20
  23. package/dist/index.js +10 -10
  24. package/dist/{parser-CyJ2auea.js → parser-RBrkz7ZL.js} +2 -4
  25. package/dist/{typebox-wYeJqy7T.js → typebox-RAJnIZwI.js} +60 -47
  26. package/dist/typebox.d.ts +3 -5
  27. package/dist/typebox.js +1 -1
  28. package/dist/{valibot-DQUEDYKt.js → valibot-CLUhG6tp.js} +66 -45
  29. package/dist/valibot.d.ts +3 -5
  30. package/dist/valibot.js +1 -1
  31. package/dist/{yup-BMpa9Co1.js → yup-DfE_ofEu.js} +9 -15
  32. package/dist/yup.d.ts +3 -5
  33. package/dist/yup.js +1 -1
  34. package/dist/{zod-Dq9LtqPL.js → zod-BhYAQ3iW.js} +84 -56
  35. package/dist/zod.d.ts +3 -5
  36. package/dist/zod.js +1 -1
  37. package/package.json +5 -5
  38. package/dist/utils-Bky98UmP.js +0 -1146
package/README.md CHANGED
@@ -81,7 +81,7 @@ import { Schema } from 'effect'
81
81
  export const User = Schema.Struct({
82
82
  name: Schema.String,
83
83
  email: Schema.String.check(Schema.isPattern(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/)),
84
- age: Schema.optional(Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))),
84
+ age: Schema.optionalKey(Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))),
85
85
  })
86
86
  ```
87
87
 
@@ -1,5 +1,5 @@
1
- import { c as normalizeTypes, s as makeSafeKey } from "./utils-Bky98UmP.js";
2
- //#region src/generator/ajv/integer.ts
1
+ import { _t as makeSafeKey, s as sanitizeSchema, vt as normalizeTypes } from "./helper-WSNbEQKr.js";
2
+ // src/generator/ajv/integer.ts
3
3
  /**
4
4
  * Reconstruct a draft-07 integer schema. `minimum` is the only numeric keyword
5
5
  * in this slice; `maximum`, `exclusiveMinimum` and `multipleOf` are dropped.
@@ -9,8 +9,7 @@ function integer(schema) {
9
9
  if (typeof schema.minimum === "number") parts.push(`minimum:${schema.minimum}`);
10
10
  return `{${parts.join(",")}}`;
11
11
  }
12
- //#endregion
13
- //#region src/generator/ajv/number.ts
12
+ // src/generator/ajv/number.ts
14
13
  /**
15
14
  * Reconstruct a draft-07 number schema. `minimum` is the only numeric keyword
16
15
  * in this slice; `maximum`, `exclusiveMinimum` and `multipleOf` are dropped.
@@ -20,8 +19,7 @@ function number(schema) {
20
19
  if (typeof schema.minimum === "number") parts.push(`minimum:${schema.minimum}`);
21
20
  return `{${parts.join(",")}}`;
22
21
  }
23
- //#endregion
24
- //#region src/generator/ajv/object.ts
22
+ // src/generator/ajv/object.ts
25
23
  /**
26
24
  * Reconstruct a draft-07 object schema from `type`, `properties` and `required`.
27
25
  * Property values recurse through {@link ajv}; other object keywords are dropped.
@@ -38,8 +36,7 @@ function object(schema) {
38
36
  }
39
37
  return `{${parts.join(",")}}`;
40
38
  }
41
- //#endregion
42
- //#region src/generator/ajv/string.ts
39
+ // src/generator/ajv/string.ts
43
40
  /**
44
41
  * Reconstruct a draft-07 string schema. `format` is emitted only for `email`
45
42
  * (the first-slice format); every other string keyword is dropped.
@@ -49,8 +46,7 @@ function string(schema) {
49
46
  if (schema.format === "email") parts.push(`format:'email'`);
50
47
  return `{${parts.join(",")}}`;
51
48
  }
52
- //#endregion
53
- //#region src/generator/ajv/ajv.ts
49
+ // src/generator/ajv/ajv.ts
54
50
  /**
55
51
  * One schema node to one Ajv draft-07 schema-object expression.
56
52
  *
@@ -72,8 +68,7 @@ function ajv(schema) {
72
68
  if (types.includes("object")) return object(schema);
73
69
  return "{}";
74
70
  }
75
- //#endregion
76
- //#region src/generator/ajv/index.ts
71
+ // src/generator/ajv/index.ts
77
72
  /**
78
73
  * Convert a JSON Schema document to Ajv TypeScript: a reconstructed draft-07
79
74
  * schema object and `ajv.compile(...)`.
@@ -92,7 +87,7 @@ function ajv(schema) {
92
87
  * @returns Generated TypeScript/Ajv code string
93
88
  */
94
89
  function schemaToAjv(schema, options) {
95
- const expression = ajv(schema);
90
+ const expression = ajv(sanitizeSchema(schema));
96
91
  const withFormats = expression.includes("format:'email'");
97
92
  return [
98
93
  withFormats ? `import Ajv from 'ajv'\nimport addFormats from 'ajv-formats'` : `import Ajv from 'ajv'`,
@@ -101,5 +96,4 @@ function schemaToAjv(schema, options) {
101
96
  `export const validate = ajv.compile(schema)`
102
97
  ].join("\n\n");
103
98
  }
104
- //#endregion
105
99
  export { ajv as n, schemaToAjv as t };
package/dist/ajv.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { r as JSONSchema } from "./index-G7UqNQ4w.js";
2
- //#region src/generator/ajv/index.d.ts
1
+ import { r as JSONSchema } from "./index-DLVjyrKu.js";
3
2
  /**
4
3
  * Convert a JSON Schema document to Ajv TypeScript: a reconstructed draft-07
5
4
  * schema object and `ajv.compile(...)`.
@@ -20,5 +19,4 @@ import { r as JSONSchema } from "./index-G7UqNQ4w.js";
20
19
  export declare function schemaToAjv(schema: JSONSchema, options?: {
21
20
  exportType?: boolean;
22
21
  readonly?: boolean;
23
- }): string;
24
- //#endregion
22
+ }): string;
package/dist/ajv.js CHANGED
@@ -1 +1 @@
1
- export { t as schemaToAjv } from "./ajv-DS9gtNZC.js";
1
+ export { t as schemaToAjv } from "./ajv-DejgT2o1.js";
@@ -1,6 +1,5 @@
1
- import { $ as DEFINITION_REF_PREFIXES, At as UNSAFE_GENERATED_MARKER, B as isSchemaObject, D as isComposite, E as isArktypeDefinition, H as isStringWireLocation, I as isQuoted, M as isNullable, N as isObjectPrototypeProperty, O as isDeepLocalPointer, R as isRootRef, S as hasFixedLength, St as QUOTE_OR_BACKSLASH_PATTERN, V as isShapelessMember, X as DEFAULT_ROOT_NAME, at as INTEGER_TEXT_PATTERN, c as normalizeTypes, j as isNullTypeMember, l as resolveOpenAPIRef, o as issueMessageExpression, pt as NUMBER_RANGES, s as makeSafeKey, x as hasFixedItemCount, y as hasCombinator } from "./utils-Bky98UmP.js";
2
- import { A as wireNullText, B as emitOptionsOf, C as isPrimitiveUnion, D as stringboolTruthyPattern, E as stringboolPattern, G as schemaNamer, H as planDocument, M as formatPattern, N as regexSource, O as unionPrimitiveTypes, Q as findCodeExtensionKeysInSchema, S as isNullTextRead, T as ownProperties, V as missingDefinitionComment, W as rootNameOf, X as arktypePreprocess, Y as itemsSchemaOf, Z as arktypeWrap, at as regexLiteral, b as integerWirePattern, c as withPolymorphicBases, d as propertyEmitOptions, et as constraintMessage, f as withoutParameterSerialization, g as hoistNestedRefs, h as valueListLiteral, j as wireNumericKind, k as wireArrayOnce, l as hasParameterSerialization, m as notPredicate, nt as foldAllOfMembers, p as isBigintFormat, rt as isKeywordOnlyMember, tt as constraintPredicate, u as parameterReaders, w as numberWirePattern, x as isNullMatchedFirst, y as impliedWireType } from "./helper-CbeedY35.js";
3
- //#region src/generator/arktype/number.ts
1
+ import { $ as arktypePreprocess, A as wireArrayOnce, At as hasFixedLength, Bt as isObjectPrototypeProperty, C as isNullTextRead, D as stringboolPattern, Dt as hasCombinator, E as ownProperties, Ft as isComposite, Gt as isRootRef, H as emitOptionsOf, In as UNSAFE_GENERATED_MARKER, It as isDeepLocalPointer, J as discriminatedMembers, Jt as isStringWireLocation, K as rootNameOf, Kt as isSchemaObject, M as wireNumericKind, N as formatPattern, O as stringboolTruthyPattern, On as QUOTE_OR_BACKSLASH_PATTERN, P as regexSource, Pt as isArktypeDefinition, Q as itemsSchemaOf, Rt as isNullTypeMember, S as isNullMatchedFirst, T as numberWirePattern, U as missingDefinitionComment, Ut as isQuoted, V as definitionsOf, W as planDocument, _ as hoistNestedRefs, _t as makeSafeKey, an as DEFINITION_REF_PREFIXES, at as constraintMessage, b as impliedWireType, ct as isKeywordOnlyMember, d as parameterReaders, dn as INTEGER_TEXT_PATTERN, et as arktypeWrap, f as propertyEmitOptions, g as valueListLiteral, gt as issueMessageExpression, h as notPredicate, i as isEvaluatedKeyExpression, j as wireNullText, k as unionPrimitiveTypes, kt as hasFixedItemCount, l as withPolymorphicBases, m as isBigintFormat, nn as DEFAULT_ROOT_NAME, nt as callbackType, ot as constraintPredicate, p as withoutParameterSerialization, q as schemaNamer, qt as isShapelessMember, r as evaluatedProperties, rt as findCodeExtensionKeysInSchema, s as sanitizeSchema, st as foldAllOfMembers, tt as callbackReturn, u as hasParameterSerialization, ut as regexLiteral, vt as normalizeTypes, w as isPrimitiveUnion, x as integerWirePattern, yn as NUMBER_RANGES, yt as resolveOpenAPIRef, zt as isNullable } from "./helper-WSNbEQKr.js";
2
+ // src/generator/arktype/number.ts
4
3
  /** The comparators of a numeric node: `>= 1`, `< 5`, `% 2`. */
5
4
  function numericConstraints(schema) {
6
5
  return [
@@ -149,8 +148,7 @@ function number(schema) {
149
148
  function boundMethod(bound) {
150
149
  return `.${bound.op === ">=" ? "atLeast" : bound.op === ">" ? "moreThan" : bound.op === "<=" ? "atMost" : bound.op === "<" ? "lessThan" : "divisibleBy"}(${bound.value})`;
151
150
  }
152
- //#endregion
153
- //#region src/generator/arktype/integer.ts
151
+ // src/generator/arktype/integer.ts
154
152
  /** Whether a node is a 64-bit integer: a value beyond 2^53 that is read as a bigint. */
155
153
  function isInt64(schema) {
156
154
  return schema.format === "int64" || schema.format === "uint64";
@@ -201,8 +199,7 @@ function integer(schema, options) {
201
199
  if (errorMessage) return `type(${definition})${describe}`;
202
200
  return definition;
203
201
  }
204
- //#endregion
205
- //#region src/generator/arktype/enum.ts
202
+ // src/generator/arktype/enum.ts
206
203
  function lit(v, isBigint) {
207
204
  if (v === null) return "null";
208
205
  if (typeof v === "string") return `'${v}'`;
@@ -234,14 +231,14 @@ function _enum(schema) {
234
231
  if (errorMessage) return `type(${expr})${describe}`;
235
232
  return expr;
236
233
  }
237
- //#endregion
238
- //#region src/generator/arktype/object.ts
239
- function composeNarrows(base, narrows) {
240
- return narrows.length === 0 ? base : narrows.reduce((acc, n) => `${acc}.narrow(${n})`, base);
241
- }
242
- /** Wrap a raw arktype expression with `type(...)` if it's a bare quoted string. */
243
- function ensureRuntime(s) {
244
- return isQuoted(s) ? `type(${s})` : s;
234
+ // src/generator/arktype/object.ts
235
+ /**
236
+ * An object definition with its narrows. Inside a scope they stay in definition syntax
237
+ * (`[def, ":", fn]`), which the scope resolves; outside, they chain on `type(def)`.
238
+ */
239
+ function composeNarrows(definition, narrows, scopeMode) {
240
+ if (scopeMode) return narrows.reduce((acc, n) => `[${acc},":",${n}]`, definition);
241
+ return narrows.reduce((acc, n) => `${acc}.narrow(${n})`, `type(${definition})`);
245
242
  }
246
243
  /**
247
244
  * Compose a `.narrow(...)` argument with an optional error message.
@@ -249,7 +246,7 @@ function ensureRuntime(s) {
249
246
  * - Without message: `(data) => predicate`
250
247
  */
251
248
  function narrowPredicate(predicate, message) {
252
- return message ? `(data, ctx) => ${predicate} || ctx.mustBe(${JSON.stringify(message)})` : `(data) => ${predicate}`;
249
+ return message ? callbackReturn("(data, ctx)", `${predicate} || ctx.mustBe(${JSON.stringify(message)})`) : callbackReturn("(data)", predicate);
253
250
  }
254
251
  /**
255
252
  * Generate an Arktype object schema for a JSON Schema object node.
@@ -277,28 +274,34 @@ function object(schema, rootName, isArktype, options) {
277
274
  return "";
278
275
  };
279
276
  const patternPropertiesNarrows = () => schema.patternProperties ? Object.entries(schema.patternProperties).map(([pattern, propSchema]) => {
280
- const s = ensureRuntime(arktype(propSchema, rootName, isArktype, options));
277
+ const s = callbackType(arktype(propSchema, rootName, isArktype, options), isArktype);
281
278
  return narrowPredicate(`Object.entries(data).every(([key, value]) => !new RegExp(${JSON.stringify(pattern)}).test(key) || ${s}.allows(value))`, patternPropsMessage);
282
279
  }) : [];
283
- if (typeof schema.additionalProperties === "object") {
280
+ if (typeof schema.additionalProperties === "object" && schema.properties === void 0 && schema.patternProperties === void 0) {
284
281
  const innerLiteral = `{"[string]":${arktype(schema.additionalProperties, rootName, isArktype, options)}}`;
285
- const narrows = [propertyNamesNarrow(), ...patternPropertiesNarrows()].filter((a) => a !== "");
286
- if (narrows.length > 0) return composeNarrows(`type(${innerLiteral})`, narrows);
282
+ const narrows = [propertyNamesNarrow()].filter((a) => a !== "");
283
+ if (narrows.length > 0) return composeNarrows(innerLiteral, narrows, isArktype);
287
284
  return isArktype ? innerLiteral : `type(${innerLiteral})`;
288
285
  }
286
+ const properties = schema.properties ?? {};
287
+ const undeclaredRequired = (schema.required ?? []).filter((key) => !Object.hasOwn(properties, key));
289
288
  if (!schema.properties) {
290
289
  if (schema.additionalProperties === true) return "\"unknown\"";
291
- return isArktype ? "{}" : "type({})";
290
+ if (!(undeclaredRequired.length > 0 || schema.patternProperties !== void 0 || schema.additionalProperties === false || schema.unevaluatedProperties !== void 0)) return isArktype ? "{}" : "type({})";
292
291
  }
293
- const additionalMode = schema.additionalProperties === true ? "delete" : schema.additionalProperties === false ? "reject" : void 0;
292
+ const isEvaluated = isEvaluatedKeyExpression({
293
+ names: Object.keys(properties),
294
+ patterns: Object.keys(schema.patternProperties ?? {})
295
+ }, "key");
296
+ const additionalMode = schema.additionalProperties === true ? "delete" : schema.additionalProperties === false && schema.patternProperties === void 0 ? "reject" : void 0;
294
297
  const required = new Set(schema.required);
295
- const props = Object.entries(schema.properties).map(([key, propSchema]) => {
298
+ const props = [...Object.entries(properties).map(([key, propSchema]) => {
296
299
  const parsed = arktype(propSchema, rootName, isArktype, propertyEmitOptions(key, propSchema, options) ?? options);
297
300
  if (!parsed) return null;
298
301
  const isRequired = required.has(key);
299
302
  const baseSafeKey = makeSafeKey(key);
300
303
  return `${isRequired ? baseSafeKey : baseSafeKey.startsWith("\"") ? JSON.stringify(`${key}?`) : `"${key}?"`}:${parsed}`;
301
- }).filter((p) => p !== null);
304
+ }).filter((p) => p !== null), ...undeclaredRequired.map((key) => `${makeSafeKey(key)}:"unknown"`)];
302
305
  const additionalProp = additionalMode ? `"+":"${additionalMode}"` : void 0;
303
306
  const innerLiteral = `{${[...props, additionalProp].filter((p) => p !== void 0).join(",")}}`;
304
307
  const minPropertiesNarrow = typeof schema.minProperties === "number" ? narrowPredicate(`Object.keys(data).length >= ${schema.minProperties}`, minimumMessage) : "";
@@ -307,22 +310,25 @@ function object(schema, rootName, isArktype, options) {
307
310
  return narrowPredicate(`!('${key}' in data) || (${deps.map((d) => `'${d}' in data`).join(" && ")})`, depReqMessage);
308
311
  }) : [];
309
312
  const dependentSchemasNarrows = schema.dependentSchemas ? Object.entries(schema.dependentSchemas).map(([key, subSchema]) => {
310
- return narrowPredicate(`!('${key}' in data) || ${ensureRuntime(arktype(subSchema, rootName, isArktype, options))}.allows(data)`, depSchMessage);
313
+ return narrowPredicate(`!('${key}' in data) || ${callbackType(arktype(subSchema, rootName, isArktype, options), isArktype)}.allows(data)`, depSchMessage);
311
314
  }) : [];
312
- const additionalPropertiesNarrow = schema.additionalProperties === false && addlPropsMessage ? narrowPredicate(`Object.keys(data).every((key) => ${JSON.stringify(Object.keys(schema.properties))}.includes(key))`, addlPropsMessage) : "";
315
+ const additionalPropertiesNarrow = schema.additionalProperties === false && (addlPropsMessage !== void 0 || schema.patternProperties !== void 0) ? narrowPredicate(`Object.keys(data).every((key) => ${isEvaluated})`, addlPropsMessage) : "";
313
316
  const unevaluatedPropertiesNarrow = (() => {
314
- const u = schema.unevaluatedProperties;
317
+ const u = typeof schema.additionalProperties === "object" ? schema.additionalProperties : schema.unevaluatedProperties;
315
318
  if (u === void 0 || u === true) return "";
316
- const declaredKeys = JSON.stringify(Object.keys(schema.properties ?? {}));
317
- if (u === false) return narrowPredicate(`Object.keys(data).every((key) => ${declaredKeys}.includes(key))`, unevalPropsRawMessage);
318
- 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);
319
+ const message = typeof schema.additionalProperties === "object" ? addlPropsMessage : unevalPropsRawMessage;
320
+ if (u === false) return narrowPredicate(`Object.keys(data).every((key) => ${isEvaluated})`, message);
321
+ if (typeof u === "object") {
322
+ const s = callbackType(arktype(u, rootName, isArktype, options), isArktype);
323
+ return narrowPredicate(`Object.entries(data).every(([key, value]) => ${isEvaluated} || ${s}.allows(value))`, message);
324
+ }
319
325
  return "";
320
326
  })();
321
327
  const ifThenElseNarrows = (() => {
322
328
  if (!schema.if) return [];
323
- const ifS = ensureRuntime(arktype(schema.if, rootName, isArktype, options));
324
- const thenS = schema.then ? ensureRuntime(arktype(schema.then, rootName, isArktype, options)) : void 0;
325
- const elseS = schema.else ? ensureRuntime(arktype(schema.else, rootName, isArktype, options)) : void 0;
329
+ const ifS = callbackType(arktype(schema.if, rootName, isArktype, options), isArktype);
330
+ const thenS = schema.then ? callbackType(arktype(schema.then, rootName, isArktype, options), isArktype) : void 0;
331
+ const elseS = schema.else ? callbackType(arktype(schema.else, rootName, isArktype, options), isArktype) : void 0;
326
332
  if (!thenS && !elseS) return [];
327
333
  const ifMessage = schema["x-if-message"];
328
334
  const thenMessage = schema["x-then-message"] ?? ifMessage;
@@ -343,17 +349,17 @@ function object(schema, rootName, isArktype, options) {
343
349
  unevaluatedPropertiesNarrow,
344
350
  ...ifThenElseNarrows
345
351
  ].filter((a) => a !== "");
346
- const baseExpr = narrows.length > 0 ? composeNarrows(`type(${innerLiteral})`, narrows) : isArktype ? innerLiteral : `type(${innerLiteral})`;
352
+ const baseExpr = narrows.length > 0 ? composeNarrows(innerLiteral, narrows, isArktype) : isArktype ? innerLiteral : `type(${innerLiteral})`;
347
353
  const propsMessage = schema["x-properties-message"];
348
354
  const described = (() => {
349
355
  if (typeof propsMessage !== "string") return baseExpr;
350
- return `${baseExpr.startsWith("{") ? `type(${baseExpr})` : baseExpr}.describe(${JSON.stringify(propsMessage)})`;
356
+ if (isArktype && isArktypeDefinition(baseExpr)) return `[${baseExpr},"@",${JSON.stringify(propsMessage)}]`;
357
+ return `${isArktypeDefinition(baseExpr) ? `type(${baseExpr})` : baseExpr}.describe(${JSON.stringify(propsMessage)})`;
351
358
  })();
352
- const hasInheritedName = Object.keys(schema.properties).some(isObjectPrototypeProperty);
359
+ const hasInheritedName = Object.keys(properties).some(isObjectPrototypeProperty);
353
360
  return isStringWireLocation(options?.paramIn) && hasInheritedName ? `${arktypePreprocess([ownProperties("data")], described, "object")}.pipe((data) => ({ ...data }))` : described;
354
361
  }
355
- //#endregion
356
- //#region src/generator/arktype/string.ts
362
+ // src/generator/arktype/string.ts
357
363
  /** The formats ArkType checks with a keyword of its own, keyed by the lower-cased format. */
358
364
  const FORMAT_KEYWORD = {
359
365
  email: "string.email",
@@ -456,8 +462,7 @@ function string(schema) {
456
462
  if (narrows.length === 0 && !errorMessage) return patterned;
457
463
  return `${isQuoted(patterned) ? `type(${patterned})` : patterned}${narrows.join("")}${describe}`;
458
464
  }
459
- //#endregion
460
- //#region src/generator/arktype/arktype.ts
465
+ // src/generator/arktype/arktype.ts
461
466
  /**
462
467
  * Combine two ArkType expressions.
463
468
  *
@@ -517,6 +522,28 @@ function formatConst(value, isBigint) {
517
522
  function isNumericMember(schema) {
518
523
  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";
519
524
  }
525
+ /** An ArkType regex index-signature key for `source`, its slashes escaped. */
526
+ function indexKey(source) {
527
+ return JSON.stringify(`[/${source.replaceAll("/", "\\/")}/]`);
528
+ }
529
+ /**
530
+ * The members an `allOf` gains from `patternProperties` and `unevaluatedProperties` beside
531
+ * it: a regex index signature per pattern, holding the keys it matches to its schema, and
532
+ * one matching every key no member evaluates (no listed name, no pattern matching anywhere
533
+ * in it), holding it to `unevaluatedProperties`. An index signature can name a scope alias,
534
+ * which a `.narrow()` callback cannot.
535
+ */
536
+ function objectKeysMembers(schema, rootName, isArktype, options) {
537
+ const patternMembers = Object.entries(schema.patternProperties ?? {}).map(([pattern, propSchema]) => `{${indexKey(pattern)}:${arktype(propSchema, rootName, isArktype, options)}}`);
538
+ const unevaluated = schema.unevaluatedProperties;
539
+ if (unevaluated !== false && (typeof unevaluated !== "object" || unevaluated === null)) return patternMembers;
540
+ const evaluated = evaluatedProperties(schema, options?.definitions);
541
+ if (evaluated === void 0) return patternMembers;
542
+ const value = unevaluated === false ? "\"never\"" : arktype(unevaluated, rootName, isArktype, options);
543
+ const names = evaluated.names.map((name) => name.replaceAll(/[\\^$.*+?()[\]{}|]/gu, "\\$&"));
544
+ const exclusions = [...names.length === 0 ? [] : [`(?!(?:${names.join("|")})$)`], ...evaluated.patterns.map((pattern) => `(?![\\s\\S]*?(?:${pattern}))`)];
545
+ return [...patternMembers, `{${indexKey(`^${exclusions.join("")}`)}:${value}}`];
546
+ }
520
547
  /**
521
548
  * Generate ArkType schema code from JSON Schema.
522
549
  *
@@ -587,7 +614,14 @@ function node(schema, rootName, isArktype, options) {
587
614
  }, rootName, isArktype, options);
588
615
  if (schema.oneOf) {
589
616
  if (schema.oneOf.length === 0) return arktypeWrap$1("\"unknown\"", schema);
590
- return arktypeWrap$1(unionOf(schema.oneOf.map((s) => arktype(s, rootName, isArktype, options)), schema["x-oneOf-message"]), schema);
617
+ const discriminated = discriminatedMembers(schema, schema.oneOf);
618
+ return arktypeWrap$1(unionOf(schema.oneOf.map((s, i) => {
619
+ const member = arktype(s, rootName, isArktype, options);
620
+ const values = discriminated?.members[i]?.values;
621
+ if (discriminated === void 0 || values === void 0) return member;
622
+ const literal = values.map((value) => `'${value.replaceAll(/['\\]/gu, "\\$&")}'`).join(" | ");
623
+ return intersectionStr([member, `{${JSON.stringify(discriminated.propertyName)}:${JSON.stringify(literal)}}`], isArktype);
624
+ }), schema["x-oneOf-message"]), schema);
591
625
  }
592
626
  if (schema.anyOf) {
593
627
  if (schema.anyOf.length === 0) return arktypeWrap$1("\"unknown\"", schema);
@@ -614,7 +648,8 @@ function node(schema, rootName, isArktype, options) {
614
648
  ...schema,
615
649
  nullable
616
650
  });
617
- return arktypeWrap$1(schemas.length === 1 ? schemas[0] : intersectionStr(schemas, isArktype), {
651
+ const intersected = [...schemas, ...objectKeysMembers(schema, rootName, isArktype, options)];
652
+ return arktypeWrap$1(intersected.length === 1 ? intersected[0] : intersectionStr(intersected, isArktype), {
618
653
  ...schema,
619
654
  nullable
620
655
  });
@@ -729,13 +764,13 @@ function node(schema, rootName, isArktype, options) {
729
764
  const uniqueExpr = schema.uniqueItems === true ? narrowWith(lengthExpr, `(data: unknown[], ctx) => new Set(data).size === data.length${uniqueItemsMessage ? ` || ctx.mustBe(${JSON.stringify(uniqueItemsMessage)})` : ""}`) : lengthExpr;
730
765
  return arktypeWrap$1(wireArray(describeWithMessage((() => {
731
766
  if (!schema.contains) return [];
732
- const containsRt = asRuntime(arktype(schema.contains, rootName, isArktype, options));
767
+ const containsRt = callbackType(arktype(schema.contains, rootName, isArktype, options), isArktype);
733
768
  const minC = schema.minContains;
734
769
  const maxC = schema.maxContains;
735
- 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")}))`];
770
+ if (minC === void 0 && maxC === void 0) return [callbackReturn("(data: unknown[], ctx)", `data.some((item) => ${containsRt}.allows(item)) || ctx.mustBe(${JSON.stringify(containsMessage ?? "must contain at least one matching item")})`)];
736
771
  const effectiveMin = minC ?? 1;
737
- 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);
738
- })().reduce((acc, narrow) => `${asRuntime(acc)}${narrow}`, uniqueExpr), schema["x-items-message"])), schema);
772
+ return [effectiveMin > 0 ? callbackReturn("(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 ? callbackReturn("(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);
773
+ })().reduce((acc, narrow) => isArktype && isArktypeDefinition(acc) ? `[${acc},":",${narrow}]` : `${asRuntime(acc)}.narrow(${narrow})`, uniqueExpr), schema["x-items-message"])), schema);
739
774
  }
740
775
  if (types.includes("object")) return readonly(arktypeWrap$1(object(schema, rootName, isArktype, options), schema));
741
776
  if (types.includes("date")) {
@@ -746,20 +781,24 @@ function node(schema, rootName, isArktype, options) {
746
781
  if (typeof schema.additionalProperties === "object") return readonly(arktypeWrap$1(object(schema, rootName, isArktype, options), schema));
747
782
  return arktypeWrap$1("\"unknown\"", schema);
748
783
  }
749
- //#endregion
750
- //#region src/generator/arktype/index.ts
784
+ // src/generator/arktype/index.ts
751
785
  /**
752
786
  * A whole JSON Schema document as an ArkType module. A document with definitions becomes
753
787
  * a `scope({...}).export()` so members can name one another; one without is a bare
754
788
  * `type(...)` export.
755
789
  */
756
790
  function schemaToArktype(input, options) {
757
- const schema = withPolymorphicBases(hoistNestedRefs(input));
791
+ const schema = withPolymorphicBases(hoistNestedRefs(sanitizeSchema(input)));
758
792
  const exportType = options?.exportType ?? true;
759
- const emitOptions = emitOptionsOf(options);
760
- const prefix = emitOptions.unsafeCodeExtensions === true && findCodeExtensionKeysInSchema(schema).length > 0 ? [UNSAFE_GENERATED_MARKER] : [];
761
- const toName = schemaNamer(emitOptions.openapi);
793
+ const baseOptions = emitOptionsOf(options);
794
+ const prefix = baseOptions.unsafeCodeExtensions === true && findCodeExtensionKeysInSchema(schema).length > 0 ? [UNSAFE_GENERATED_MARKER] : [];
795
+ const toName = schemaNamer(baseOptions.openapi);
762
796
  const plan = planDocument(schema, rootNameOf(schema, toName));
797
+ const definitions = definitionsOf(baseOptions, plan.definitions);
798
+ const emitOptions = definitions === void 0 ? baseOptions : {
799
+ ...baseOptions,
800
+ definitions
801
+ };
763
802
  const { rootName } = plan;
764
803
  if (plan.hasDefinitions) {
765
804
  const defEntries = plan.orderedNames.map((name) => {
@@ -768,8 +807,9 @@ function schemaToArktype(input, options) {
768
807
  const pc = toName(name);
769
808
  return `${pc}:${arktype(def, pc, true, emitOptions)}`;
770
809
  });
771
- const scopeBody = `const types = scope({${(plan.rootDefinition === void 0 ? [...defEntries, `${rootName}:${arktype(schema, rootName, true, emitOptions)}`] : defEntries).join(",")}}).export()`;
772
- const usesType = /\btype[(.]/u.test(scopeBody);
810
+ const entries = (plan.rootDefinition === void 0 ? [...defEntries, `${rootName}:${arktype(schema, rootName, true, emitOptions)}`] : defEntries).join(",");
811
+ const scopeBody = entries.includes("$.type(") ? `const $ = scope({${entries}})\n\nconst types = $.export()` : `const types = scope({${entries}}).export()`;
812
+ const usesType = /(?<![\w$.])type[(.]/u.test(scopeBody);
773
813
  return [
774
814
  ...prefix,
775
815
  `import { scope${usesType ? ", type" : ""} } from "arktype"`,
@@ -799,5 +839,4 @@ function schemaToArktype(input, options) {
799
839
  ...exportType ? [`export type ${rootName} = typeof ${rootName}.infer`] : []
800
840
  ].filter(Boolean).join("\n\n");
801
841
  }
802
- //#endregion
803
842
  export { arktype as n, schemaToArktype as t };
package/dist/arktype.d.ts CHANGED
@@ -1,10 +1,8 @@
1
- import { r as JSONSchema } from "./index-G7UqNQ4w.js";
2
- import { n as GenerateOptions } from "./index-DYzAccyT.js";
3
- //#region src/generator/arktype/index.d.ts
1
+ import { r as JSONSchema } from "./index-DLVjyrKu.js";
2
+ import { n as GenerateOptions } from "./index-DU2Nd8eI.js";
4
3
  /**
5
4
  * A whole JSON Schema document as an ArkType module. A document with definitions becomes
6
5
  * a `scope({...}).export()` so members can name one another; one without is a bare
7
6
  * `type(...)` export.
8
7
  */
9
- export declare function schemaToArktype(input: JSONSchema, options?: GenerateOptions): string;
10
- //#endregion
8
+ export declare function schemaToArktype(input: JSONSchema, options?: GenerateOptions): string;
package/dist/arktype.js CHANGED
@@ -1 +1 @@
1
- export { t as schemaToArktype } from "./arktype-CRZ8vXZ5.js";
1
+ export { t as schemaToArktype } from "./arktype-CzTltPwP.js";
package/dist/cli/ajv.js CHANGED
@@ -1,15 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToAjv } from "../ajv-DS9gtNZC.js";
3
- import { n as version, t as cli } from "../cli-eAY8LqwP.js";
2
+ import { t as schemaToAjv } from "../ajv-DejgT2o1.js";
3
+ import { n as version, t as cli } from "../cli-71Np9i5L.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
7
- //#region src/ajv.ts
7
+ // src/ajv.ts
8
8
  NodeRuntime.runMain(cli({
9
9
  name: "schema-truth-ajv",
10
10
  generator: schemaToAjv,
11
11
  description: "Generate Ajv schemas from a JSON Schema document",
12
12
  version
13
13
  }).pipe(Effect.provide(NodeServices.layer)));
14
- //#endregion
15
14
  export {};
@@ -1,15 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToArktype } from "../arktype-CRZ8vXZ5.js";
3
- import { n as version, t as cli } from "../cli-eAY8LqwP.js";
2
+ import { t as schemaToArktype } from "../arktype-CzTltPwP.js";
3
+ import { n as version, t as cli } from "../cli-71Np9i5L.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
7
- //#region src/arktype.ts
7
+ // src/arktype.ts
8
8
  NodeRuntime.runMain(cli({
9
9
  name: "schema-truth-arktype",
10
10
  generator: schemaToArktype,
11
11
  description: "Generate ArkType schemas from a JSON Schema document",
12
12
  version
13
13
  }).pipe(Effect.provide(NodeServices.layer)));
14
- //#endregion
15
14
  export {};
@@ -1,15 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToEffect } from "../effect-BkWovUi3.js";
3
- import { n as version, t as cli } from "../cli-eAY8LqwP.js";
2
+ import { t as schemaToEffect } from "../effect-Dj8qARFi.js";
3
+ import { n as version, t as cli } from "../cli-71Np9i5L.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
7
- //#region src/effect.ts
7
+ // src/effect.ts
8
8
  NodeRuntime.runMain(cli({
9
9
  name: "schema-truth-effect",
10
10
  generator: schemaToEffect,
11
11
  description: "Generate Effect Schema code from a JSON Schema document",
12
12
  version
13
13
  }).pipe(Effect.provide(NodeServices.layer)));
14
- //#endregion
15
14
  export {};
@@ -1,15 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToTypebox } from "../typebox-wYeJqy7T.js";
3
- import { n as version, t as cli } from "../cli-eAY8LqwP.js";
2
+ import { t as schemaToTypebox } from "../typebox-RAJnIZwI.js";
3
+ import { n as version, t as cli } from "../cli-71Np9i5L.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
7
- //#region src/typebox.ts
7
+ // src/typebox.ts
8
8
  NodeRuntime.runMain(cli({
9
9
  name: "schema-truth-typebox",
10
10
  generator: schemaToTypebox,
11
11
  description: "Generate TypeBox schemas from a JSON Schema document",
12
12
  version
13
13
  }).pipe(Effect.provide(NodeServices.layer)));
14
- //#endregion
15
14
  export {};
@@ -1,15 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToValibot } from "../valibot-DQUEDYKt.js";
3
- import { n as version, t as cli } from "../cli-eAY8LqwP.js";
2
+ import { t as schemaToValibot } from "../valibot-CLUhG6tp.js";
3
+ import { n as version, t as cli } from "../cli-71Np9i5L.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
7
- //#region src/valibot.ts
7
+ // src/valibot.ts
8
8
  NodeRuntime.runMain(cli({
9
9
  name: "schema-truth-valibot",
10
10
  generator: schemaToValibot,
11
11
  description: "Generate Valibot schemas from a JSON Schema document",
12
12
  version
13
13
  }).pipe(Effect.provide(NodeServices.layer)));
14
- //#endregion
15
14
  export {};
package/dist/cli/yup.js CHANGED
@@ -1,15 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToYup } from "../yup-BMpa9Co1.js";
3
- import { n as version, t as cli } from "../cli-eAY8LqwP.js";
2
+ import { t as schemaToYup } from "../yup-DfE_ofEu.js";
3
+ import { n as version, t as cli } from "../cli-71Np9i5L.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
7
- //#region src/yup.ts
7
+ // src/yup.ts
8
8
  NodeRuntime.runMain(cli({
9
9
  name: "schema-truth-yup",
10
10
  generator: schemaToYup,
11
11
  description: "Generate Yup schemas from a JSON Schema document",
12
12
  version
13
13
  }).pipe(Effect.provide(NodeServices.layer)));
14
- //#endregion
15
14
  export {};
package/dist/cli/zod.js CHANGED
@@ -1,15 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import { t as schemaToZod } from "../zod-Dq9LtqPL.js";
3
- import { n as version, t as cli } from "../cli-eAY8LqwP.js";
2
+ import { t as schemaToZod } from "../zod-BhYAQ3iW.js";
3
+ import { n as version, t as cli } from "../cli-71Np9i5L.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6
6
  import * as NodeServices from "@effect/platform-node/NodeServices";
7
- //#region src/zod.ts
7
+ // src/zod.ts
8
8
  NodeRuntime.runMain(cli({
9
9
  name: "schema-truth-zod",
10
10
  generator: schemaToZod,
11
11
  description: "Generate Zod schemas from a JSON Schema document",
12
12
  version
13
13
  }).pipe(Effect.provide(NodeServices.layer)));
14
- //#endregion
15
14
  export {};
@@ -1,5 +1,5 @@
1
- import { L as isRecord } from "./utils-Bky98UmP.js";
2
- import { i as fmt, n as parseSchemaFile } from "./parser-CyJ2auea.js";
1
+ import { Wt as isRecord } from "./helper-WSNbEQKr.js";
2
+ import { i as fmt, n as parseSchemaFile } from "./parser-RBrkz7ZL.js";
3
3
  import * as Effect from "effect/Effect";
4
4
  import path from "node:path";
5
5
  import { Argument, CliError, Command, Flag } from "effect/cli";
@@ -8,10 +8,9 @@ import * as Schema from "effect/Schema";
8
8
  import * as Stdio from "effect/Stdio";
9
9
  import "@effect/platform-node/NodeFileSystem";
10
10
  import * as FileSystem from "effect/FileSystem";
11
- //#region package.json
12
- var version = "0.8.1";
13
- //#endregion
14
- //#region src/file/index.ts
11
+ // package.json
12
+ var version = "0.8.3";
13
+ // src/file/index.ts
15
14
  /** Creates the directory and its parents. An existing directory is not an error. */
16
15
  function mkdir(dir) {
17
16
  return Effect.gen(function* () {
@@ -31,8 +30,7 @@ function writeFile(path, data) {
31
30
  yield* fs.writeFileString(path, data);
32
31
  });
33
32
  }
34
- //#endregion
35
- //#region src/cli/index.ts
33
+ // src/cli/index.ts
36
34
  const InputPathSchema = Schema.String.pipe(Schema.refine(Schema.is(Schema.TemplateLiteral([Schema.String, Schema.Literals([".json", ".yaml"])])), { message: "a JSON Schema document ending in .json or .yaml" }));
37
35
  const OutputPathSchema = Schema.String.pipe(Schema.refine(Schema.is(Schema.TemplateLiteral([Schema.String, ".ts"])), { message: "a TypeScript file path ending in .ts" }));
38
36
  /**
@@ -120,5 +118,4 @@ function cli(options) {
120
118
  return yield* runCli(options, yield* (yield* Stdio.Stdio).args);
121
119
  });
122
120
  }
123
- //#endregion
124
121
  export { version as n, cli as t };