schema-truth 0.8.1 → 0.8.2

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.
@@ -1,5 +1,5 @@
1
1
  import { At as UNSAFE_GENERATED_MARKER, B as isSchemaObject, D as isComposite, F as isPrimitive, H as isStringWireLocation, M as isNullable, N as isObjectPrototypeProperty, P as isPlainObject, S as hasFixedLength, T as hasType, V as isShapelessMember, X as DEFAULT_ROOT_NAME, b as hasConditional, c as normalizeTypes, g as zodErrorPart, h as zodError, j as isNullTypeMember, k as isDefaultOnlyMember, m as zodBaseError, o as issueMessageExpression, s as makeSafeKey, st as ISO_4217_CURRENCY_CODES, y as hasCombinator } from "./utils-Bky98UmP.js";
2
- import { A as wireNullText, B as emitOptionsOf, C as isPrimitiveUnion, G as schemaNamer, H as planDocument, O as unionPrimitiveTypes, P as timePattern, Q as findCodeExtensionKeysInSchema, S as isNullTextRead, U as renderDefinitions, W as rootNameOf, Y as itemsSchemaOf, at as regexLiteral, b as integerWirePattern, c as withPolymorphicBases, d as propertyEmitOptions, et as constraintMessage, f as withoutParameterSerialization, g as hoistNestedRefs, h as valueListLiteral, i as isEvaluatedKeyExpression, j as wireNumericKind, k as wireArrayOnce, l as hasParameterSerialization, m as notPredicate, nt as foldAllOfMembers, o as typeDeclaration, p as isBigintFormat, q as hasRootSelfReference, r as evaluatedProperties, rt as isKeywordOnlyMember, s as refTarget, t as zodWrap, tt as constraintPredicate, u as parameterReaders, w as numberWirePattern, x as isNullMatchedFirst, y as impliedWireType, z as definitionsOf } from "./helper-CbeedY35.js";
2
+ import { A as wireNullText, B as emitOptionsOf, C as isPrimitiveUnion, G as schemaNamer, H as planDocument, J as hasRootSelfReference, K as discriminatedMembers, O as unionPrimitiveTypes, P as timePattern, S as isNullTextRead, U as renderDefinitions, W as rootNameOf, X as itemsSchemaOf, at as foldAllOfMembers, b as integerWirePattern, c as withPolymorphicBases, ct as regexLiteral, d as propertyEmitOptions, f as withoutParameterSerialization, g as hoistNestedRefs, h as valueListLiteral, i as isEvaluatedKeyExpression, it as constraintPredicate, j as wireNumericKind, k as wireArrayOnce, l as hasParameterSerialization, m as notPredicate, o as typeDeclaration, ot as isKeywordOnlyMember, p as isBigintFormat, r as evaluatedProperties, rt as constraintMessage, s as refTarget, t as zodWrap, tt as findCodeExtensionKeysInSchema, u as parameterReaders, w as numberWirePattern, x as isNullMatchedFirst, y as impliedWireType, z as definitionsOf } from "./helper-S7SSsYwh.js";
3
3
  //#region src/generator/zod/type.ts
4
4
  /** The TypeScript type declared beside a recursive Zod schema. */
5
5
  function type(schema, rootName = DEFAULT_ROOT_NAME) {
@@ -250,18 +250,22 @@ function object(schema, rootName, isZod, options) {
250
250
  const depReqErrorArg = depReqMessage ? `,${zodError(depReqMessage)}` : errorArg;
251
251
  const depSchMessage = schema["x-dependentSchemas-message"];
252
252
  const depSchErrorArg = depSchMessage ? `,${zodError(depSchMessage)}` : errorArg;
253
- if (typeof schema.additionalProperties === "object") return `${`z.record(z.string(),${zod(schema.additionalProperties, rootName, isZod, options)})`}${schema.propertyNames?.pattern ? `.refine((val)=>Object.keys(val).every((key)=>new RegExp(${JSON.stringify(schema.propertyNames.pattern)}).test(key))${propNamesErrorArg})` : schema.propertyNames?.enum ? `.refine((val)=>Object.keys(val).every((key)=>${JSON.stringify(schema.propertyNames.enum)}.includes(key))${propNamesErrorArg})` : ""}${schema.patternProperties ? Object.entries(schema.patternProperties).map(([pattern, propSchema]) => {
254
- const z = zod(propSchema, rootName, isZod, options);
255
- return `.refine((val)=>Object.entries(val).every(([key,value])=>!new RegExp(${JSON.stringify(pattern)}).test(key)||${z}.safeParse(value).success)${patternErrorArg})`;
256
- }).join("") : ""}`;
253
+ if (typeof schema.additionalProperties === "object" && schema.properties === void 0 && schema.patternProperties === void 0) return `${`z.record(z.string(),${zod(schema.additionalProperties, rootName, isZod, options)})`}${schema.propertyNames?.pattern ? `.refine((val)=>Object.keys(val).every((key)=>new RegExp(${JSON.stringify(schema.propertyNames.pattern)}).test(key))${propNamesErrorArg})` : schema.propertyNames?.enum ? `.refine((val)=>Object.keys(val).every((key)=>${JSON.stringify(schema.propertyNames.enum)}.includes(key))${propNamesErrorArg})` : ""}`;
254
+ const properties = schema.properties ?? {};
255
+ const undeclaredRequired = (schema.required ?? []).filter((key) => !Object.hasOwn(properties, key));
256
+ const unevaluated = schema.unevaluatedProperties;
257
+ const closed = schema.additionalProperties === false || unevaluated === false;
258
+ const closedByCheck = closed && schema.patternProperties !== void 0;
259
+ const extraSchema = typeof schema.additionalProperties === "object" ? schema.additionalProperties : typeof unevaluated === "object" ? unevaluated : void 0;
260
+ const extraMessage = typeof schema.additionalProperties === "object" ? schema["x-additionalProperties-message"] : schema["x-unevaluatedProperties-message"];
257
261
  if (!schema.properties) {
258
262
  if (schema.additionalProperties === true) return "z.any()";
259
- return "z.object({})";
263
+ if (!(undeclaredRequired.length > 0 || schema.patternProperties !== void 0 || extraSchema !== void 0 || closed)) return "z.object({})";
260
264
  }
261
- const conditionalKeysReferenced = hasConditional(schema);
262
- const objectType = schema.additionalProperties === true ? "looseObject" : schema.additionalProperties === false || schema.unevaluatedProperties === false ? "strictObject" : conditionalKeysReferenced ? "looseObject" : "object";
265
+ const readsUndeclaredKeys = hasConditional(schema) || schema.patternProperties !== void 0 || schema.propertyNames !== void 0 || schema.minProperties !== void 0 || schema.maxProperties !== void 0 || schema.dependentRequired !== void 0 || schema.dependentSchemas !== void 0 || undeclaredRequired.length > 0 || extraSchema !== void 0 || closedByCheck;
266
+ const objectType = schema.additionalProperties === true ? "looseObject" : closed && !closedByCheck ? "strictObject" : readsUndeclaredKeys ? "looseObject" : "object";
263
267
  const required = new Set(schema.required);
264
- const props = Object.entries(schema.properties).map(([key, propSchema]) => {
268
+ const props = Object.entries(properties).map(([key, propSchema]) => {
265
269
  const parsed = zod(propSchema, rootName, isZod, propertyEmitOptions(key, propSchema, options) ?? options);
266
270
  if (!parsed) return null;
267
271
  return `${makeSafeKey(key)}:${parsed}${required.has(key) ? "" : ".exactOptional()"}`;
@@ -270,17 +274,21 @@ function object(schema, rootName, isZod, options) {
270
274
  const objectParams = objectType === "strictObject" && strictMessage ? `,{error:(issue)=>issue.code==='unrecognized_keys'?${JSON.stringify(strictMessage)}:${errorMessage ? JSON.stringify(errorMessage) : "undefined"}}` : "";
271
275
  const rawBase = `z.${objectType}({${props.join(",")}}${objectParams})`;
272
276
  const propsMessage = schema["x-properties-message"];
273
- const objectExpr = `${propsMessage ? (() => {
274
- const msgExpr = issueMessageExpression(propsMessage);
275
- return `(()=>{const Schema=${rawBase};return z.unknown().check((ctx)=>{const result=Schema.safeParse(ctx.value);if(!result.success){for(const issue of result.error.issues){if(issue.path.length>0){ctx.issues.push({...issue,message:${msgExpr}})}else{ctx.issues.push(issue)}}}}).pipe(Schema)})()`;
276
- })() : rawBase}${typeof schema.minProperties === "number" ? `.refine((val)=>Object.keys(val).length>=${schema.minProperties}${minErrorArg})` : ""}${typeof schema.maxProperties === "number" ? `.refine((val)=>Object.keys(val).length<=${schema.maxProperties}${maxErrorArg})` : ""}${schema.propertyNames?.pattern ? `.refine((val)=>Object.keys(val).every((key)=>new RegExp(${JSON.stringify(schema.propertyNames.pattern)}).test(key))${propNamesErrorArg})` : schema.propertyNames?.enum ? `.refine((val)=>Object.keys(val).every((key)=>${JSON.stringify(schema.propertyNames.enum)}.includes(key))${propNamesErrorArg})` : ""}${schema.patternProperties ? Object.entries(schema.patternProperties).map(([pattern, propSchema]) => {
277
+ const partialBase = propsMessage ? nestedIssueMessageWrap(rawBase, propsMessage) : rawBase;
278
+ const minProperties = typeof schema.minProperties === "number" ? `.refine((val)=>Object.keys(val).length>=${schema.minProperties}${minErrorArg})` : "";
279
+ const maxProperties = typeof schema.maxProperties === "number" ? `.refine((val)=>Object.keys(val).length<=${schema.maxProperties}${maxErrorArg})` : "";
280
+ const propertyNames = schema.propertyNames?.pattern ? `.refine((val)=>Object.keys(val).every((key)=>new RegExp(${JSON.stringify(schema.propertyNames.pattern)}).test(key))${propNamesErrorArg})` : schema.propertyNames?.enum ? `.refine((val)=>Object.keys(val).every((key)=>${JSON.stringify(schema.propertyNames.enum)}.includes(key))${propNamesErrorArg})` : "";
281
+ const patternProperties = schema.patternProperties ? Object.entries(schema.patternProperties).map(([pattern, propSchema]) => {
277
282
  const z = zod(propSchema, rootName, isZod, options);
278
283
  return `.refine((val)=>Object.entries(val).every(([key,value])=>!new RegExp(${JSON.stringify(pattern)}).test(key)||${z}.safeParse(value).success)${patternErrorArg})`;
279
- }).join("") : ""}${schema.dependentRequired ? Object.entries(schema.dependentRequired).map(([key, deps]) => {
284
+ }).join("") : "";
285
+ const dependentRequired = schema.dependentRequired ? Object.entries(schema.dependentRequired).map(([key, deps]) => {
280
286
  return `.refine((val)=>!('${key}' in val)||(${deps.map((d) => `'${d}' in val`).join("&&")})${depReqErrorArg})`;
281
- }).join("") : ""}${schema.dependentSchemas ? Object.entries(schema.dependentSchemas).map(([key, subSchema]) => {
287
+ }).join("") : "";
288
+ const dependentSchemas = schema.dependentSchemas ? Object.entries(schema.dependentSchemas).map(([key, subSchema]) => {
282
289
  return `.refine((val)=>!('${key}' in val)||${zod(subSchema, rootName, isZod, options)}.safeParse(val).success${depSchErrorArg})`;
283
- }).join("") : ""}${(() => {
290
+ }).join("") : "";
291
+ const ifThenElse = (() => {
284
292
  if (!schema.if) return "";
285
293
  const ifS = zod(schema.if, rootName, isZod, options);
286
294
  const thenS = schema.then ? zod(schema.then, rootName, isZod, options) : void 0;
@@ -299,8 +307,14 @@ function object(schema, rootName, isZod, options) {
299
307
  parts.push(`.refine((val)=>${ifS}.safeParse(val).success||${elseS}.safeParse(val).success${arg})`);
300
308
  }
301
309
  return parts.join("");
302
- })()}`;
303
- const hasInheritedName = Object.keys(schema.properties).some(isObjectPrototypeProperty);
310
+ })();
311
+ const requiredPresent = undeclaredRequired.length > 0 ? `.refine((val)=>${JSON.stringify(undeclaredRequired)}.every((key)=>key in val)${errorArg})` : "";
312
+ const isEvaluated = isEvaluatedKeyExpression({
313
+ names: Object.keys(properties),
314
+ patterns: Object.keys(schema.patternProperties ?? {})
315
+ }, "key");
316
+ const objectExpr = `${partialBase}${minProperties}${maxProperties}${propertyNames}${patternProperties}${requiredPresent}${closedByCheck ? `.refine((val)=>Object.keys(val).every((key)=>${isEvaluated})${zodErrorPart(strictMessage ?? errorMessage)})` : extraSchema !== void 0 ? `.refine((val)=>Object.entries(val).every(([key,value])=>${isEvaluated}||${zod(extraSchema, rootName, isZod, options)}.safeParse(value).success)${zodErrorPart(extraMessage ?? errorMessage)})` : ""}${dependentRequired}${dependentSchemas}${ifThenElse}`;
317
+ const hasInheritedName = Object.keys(properties).some(isObjectPrototypeProperty);
304
318
  return isStringWireLocation(options?.paramIn) && hasInheritedName ? `z.preprocess(${OWN_PROPERTIES_PREPROCESS},${objectExpr})` : objectExpr;
305
319
  }
306
320
  //#endregion
@@ -546,8 +560,19 @@ function zodNotPredicate(inner, parent) {
546
560
  if (Array.isArray(inner.enum)) return `(val) => !${valueListLiteral(inner.enum, bigint)}.includes(val)`;
547
561
  if (inner.oneOf || inner.anyOf || inner.allOf) return `(val) => !${zod(inner)}.safeParse(val).success`;
548
562
  }
563
+ /**
564
+ * Re-push `issue` into `ctx` with `message`. Each issue code is narrowed first: the union of
565
+ * parsed issues does not type-check as a raw issue, while each member does.
566
+ */
567
+ function forwardIssue(message) {
568
+ return ZOD_ISSUE_CODES.map((c, i) => `${i === 0 ? "" : "else "}if(issue.code==='${c}'){ctx.issues.push({...issue,input:issue.input,message:${message}})}`).join("");
569
+ }
570
+ /** A message for the issues under the value (with a path); the root's own issues keep theirs. */
571
+ function nestedIssueMessageWrap(inner, msg) {
572
+ return `(()=>{const Schema=${inner};return z.unknown().check((ctx)=>{const result=Schema.safeParse(ctx.value);if(!result.success){for(const issue of result.error.issues){${forwardIssue(`issue.path.length>0?${issueMessageExpression(msg)}:issue.message`)}}}}).pipe(Schema)})()`;
573
+ }
549
574
  function elementMessageWrap(inner, msg) {
550
- return `(()=>{const Schema=${inner};return z.unknown().check((ctx)=>{const result=Schema.safeParse(ctx.value);if(!result.success){for(const issue of result.error.issues){if(issue.path.length>0){ctx.issues.push({...issue,message:${issueMessageExpression(msg)}})}else{ctx.issues.push(issue)}}}}).pipe(Schema)})()`;
575
+ return nestedIssueMessageWrap(inner, msg);
551
576
  }
552
577
  /**
553
578
  * Generate Zod schema code from JSON Schema.
@@ -568,19 +593,26 @@ function zod(schema, rootName = DEFAULT_ROOT_NAME, isZod = false, options) {
568
593
  function keywordConstraint(schema) {
569
594
  return `z.any().refine((val) => ${constraintPredicate(schema, "val")}${zodErrorPart(constraintMessage(schema))})`;
570
595
  }
596
+ /** Push a key's issues (`result`, for the value `v` under key `k`) under that key. */
597
+ function forwardKeyIssues(message) {
598
+ return `for(const issue of result.error.issues){ctx.issues.push({code:'custom',input:v,path:[k,...issue.path],message:${message === void 0 ? "issue.message" : JSON.stringify(message)}})}`;
599
+ }
571
600
  /**
572
- * An `allOf` with `unevaluatedProperties` beside it: the members' objects strip what they
573
- * do not declare, so the keys no member evaluates are checked on the input before it is
574
- * parsed. `inner` as given when the keyword is absent or every key is evaluated.
601
+ * An `allOf` with `patternProperties` or `unevaluatedProperties` beside it: the members'
602
+ * objects strip what they do not declare, so the keys are checked on the input before it
603
+ * is parsed — a key a pattern matches against that pattern's schema, a key no member
604
+ * evaluates against `unevaluatedProperties`. `inner` as given when there is nothing to check.
575
605
  */
576
- function unevaluatedPropertiesCheck(inner, schema, rootName, isZod, options) {
606
+ function objectKeysCheck(inner, schema, rootName, isZod, options) {
607
+ const patterns = Object.entries(schema.patternProperties ?? {});
577
608
  const unevaluated = schema.unevaluatedProperties;
578
- if (unevaluated !== false && (typeof unevaluated !== "object" || unevaluated === null)) return inner;
579
- const evaluated = evaluatedProperties(schema, options?.definitions);
580
- if (evaluated === void 0) return inner;
581
- const isEvaluated = isEvaluatedKeyExpression(evaluated, "k");
609
+ const unevaluatedSchema = typeof unevaluated === "object" ? unevaluated : void 0;
610
+ const evaluated = unevaluated === false || unevaluatedSchema !== void 0 ? evaluatedProperties(schema, options?.definitions) : void 0;
611
+ if (patterns.length === 0 && evaluated === void 0) return inner;
612
+ const patternMessage = schema["x-patternProperties-message"];
613
+ const patternChecks = patterns.map(([pattern, propSchema]) => `if(new RegExp(${JSON.stringify(pattern)}).test(k)){const result=${zod(propSchema, rootName, isZod, options)}.safeParse(v);if(!result.success){${forwardKeyIssues(patternMessage)}}}`).join("");
582
614
  const message = schema["x-unevaluatedProperties-message"];
583
- return `(()=>{const Schema=${inner};return z.unknown().check((ctx)=>{const o=ctx.value;if(typeof o!=='object'||o===null||Array.isArray(o))return;${unevaluated === false ? `for(const k of Object.keys(o)){if(${isEvaluated})continue;ctx.issues.push({code:'custom',input:o,path:[k],message:${message === void 0 ? "`Unrecognized key: \"${k}\"`" : JSON.stringify(message)}})}` : `const Unevaluated=${zod(unevaluated, rootName, isZod, options)};for(const [k,v] of Object.entries(o)){if(${isEvaluated})continue;const result=Unevaluated.safeParse(v);if(!result.success){for(const issue of result.error.issues){ctx.issues.push({code:'custom',input:v,path:[k,...issue.path],message:${message === void 0 ? "issue.message" : JSON.stringify(message)}})}}}`}}).pipe(Schema)})()`;
615
+ return `(()=>{const Schema=${inner};return z.unknown().check((ctx)=>{const o=ctx.value;if(typeof o!=='object'||o===null||Array.isArray(o))return;for(const [k,v] of Object.entries(o)){${patternChecks}${evaluated === void 0 ? "" : `if(!(${isEvaluatedKeyExpression(evaluated, "k")})){${unevaluatedSchema === void 0 ? `ctx.issues.push({code:'custom',input:o,path:[k],message:${message === void 0 ? "`Unrecognized key: \"${k}\"`" : JSON.stringify(message)}})` : `const result=${zod(unevaluatedSchema, rootName, isZod, options)}.safeParse(v);if(!result.success){${forwardKeyIssues(message)}}`}}`}}}).pipe(Schema)})()`;
584
616
  }
585
617
  function node(schema, rootName, isZod, options) {
586
618
  const isStringWireParam = isStringWireLocation(options?.paramIn);
@@ -618,11 +650,18 @@ function node(schema, rootName, isZod, options) {
618
650
  }, rootName, isZod, options);
619
651
  if (schema.oneOf) {
620
652
  if (schema.oneOf.length === 0) return zodWrap$1("z.any()", schema);
621
- const schemas = schema.oneOf.map((s) => zod(s, rootName, isZod, options));
622
- const oneOfMessage = schema["x-oneOf-message"];
623
- const errorPart = zodErrorPart(oneOfMessage);
624
653
  const discriminator = schema.discriminator?.propertyName;
625
654
  const hasRefOrAllOf = schema.oneOf.some((s) => s.$ref !== void 0 || s.allOf !== void 0);
655
+ const discriminated = hasRefOrAllOf ? discriminatedMembers(schema, schema.oneOf) : void 0;
656
+ const schemas = schema.oneOf.map((s, i) => {
657
+ const member = zod(s, rootName, isZod, options);
658
+ const values = discriminated?.members[i]?.values;
659
+ if (discriminated === void 0 || values === void 0) return member;
660
+ const literal = values.length === 1 ? `z.literal(${JSON.stringify(values[0])})` : `z.enum(${JSON.stringify(values)})`;
661
+ return `z.intersection(${member},z.object({${makeSafeKey(discriminated.propertyName)}:${literal}}))`;
662
+ });
663
+ const oneOfMessage = schema["x-oneOf-message"];
664
+ const errorPart = zodErrorPart(oneOfMessage);
626
665
  return zodWrap$1(discriminator && !hasRefOrAllOf ? `z.discriminatedUnion('${discriminator}',[${schemas.join(",")}]${errorPart})` : isWireCoerced ? `z.union([${schemas.join(",")}]${errorPart})` : `z.xor([${schemas.join(",")}]${errorPart})`, schema);
627
666
  }
628
667
  if (schema.anyOf) {
@@ -643,9 +682,8 @@ function node(schema, rootName, isZod, options) {
643
682
  });
644
683
  const intersected = schemas.length === 1 ? schemas[0] : schemas.reduce((acc, s) => `z.intersection(${acc},${s})`);
645
684
  const allOfMessage = schema["x-allOf-message"];
646
- const checked = unevaluatedPropertiesCheck(allOfMessage ? (() => {
647
- const msgExpr = issueMessageExpression(allOfMessage);
648
- const branches = ZOD_ISSUE_CODES.map((c, i) => `${i === 0 ? "" : "else "}if(issue.code==='${c}'){ctx.issues.push({...issue,input:issue.input,message:${msgExpr}})}`).join("");
685
+ const checked = objectKeysCheck(allOfMessage ? (() => {
686
+ const branches = forwardIssue(issueMessageExpression(allOfMessage));
649
687
  return `(()=>{const Schema=${intersected};return z.unknown().check((ctx)=>{const result=Schema.safeParse(ctx.value);if(!result.success){for(const issue of result.error.issues){${branches}}}}).pipe(Schema)})()`;
650
688
  })() : intersected, schema, rootName, isZod, options);
651
689
  const mergedDefault = defaultValue !== void 0 ? defaultValue : schema.default;
@@ -813,4 +851,4 @@ function schemaToZod(input, options) {
813
851
  ].filter(Boolean).join("\n\n");
814
852
  }
815
853
  //#endregion
816
- export { zod as n, schemaToZod as t };
854
+ export { zod as i, forwardIssue as n, nestedIssueMessageWrap as r, schemaToZod as t };
package/dist/zod.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { r as JSONSchema } from "./index-G7UqNQ4w.js";
2
- import { n as GenerateOptions } from "./index-DYzAccyT.js";
2
+ import { n as GenerateOptions } from "./index-EK43HM_z.js";
3
3
  //#region src/generator/zod/index.d.ts
4
4
  /**
5
5
  * A whole JSON Schema document as a Zod module: imports, `$defs` in dependency order,
package/dist/zod.js CHANGED
@@ -1 +1 @@
1
- export { t as schemaToZod } from "./zod-Dq9LtqPL.js";
1
+ export { t as schemaToZod } from "./zod-CXo9NFuF.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "schema-truth",
3
- "version": "0.8.1",
3
+ "version": "0.8.2",
4
4
  "description": "Generate Zod/Valibot/Effect/TypeBox/ArkType/Ajv/Yup schemas from JSON or YAML files",
5
5
  "keywords": [
6
6
  "ajv",