zod-json-schema-compat.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // zod-json-schema-compat.ts
  2. // ----------------------------------------------------
  3. // JSON Schema conversion for both Zod v3 and Zod v4 (Mini)
  4. // v3 uses your vendored converter; v4 uses Mini's toJSONSchema
  5. // ----------------------------------------------------
  6. import * as z4mini from 'zod/v4-mini';
  7. import { getObjectShape, safeParse, isZ4Schema, getLiteralValue } from './zod-compat.js';
  8. import { zodToJsonSchema } from 'zod-to-json-schema';
  9. function mapMiniTarget(t) {
  10. if (!t)
  11. return 'draft-7';
  12. if (t === 'jsonSchema7' || t === 'draft-7')
  13. return 'draft-7';
  14. if (t === 'jsonSchema2019-09' || t === 'draft-2020-12')
  15. return 'draft-2020-12';
  16. return 'draft-7'; // fallback
  17. }
  18. export function toJsonSchemaCompat(schema, opts) {
  19. if (isZ4Schema(schema)) {
  20. // v4 branch — use Mini's built-in toJSONSchema
  21. return z4mini.toJSONSchema(schema, {
  22. target: mapMiniTarget(opts?.target),
  23. io: opts?.pipeStrategy ?? 'input'
  24. });
  25. }
  26. // v3 branch — use vendored converter
  27. return zodToJsonSchema(schema, {
  28. strictUnions: opts?.strictUnions ?? true,
  29. pipeStrategy: opts?.pipeStrategy ?? 'input'
  30. });
  31. }
  32. export function getMethodLiteral(schema) {
  33. const shape = getObjectShape(schema);
  34. const methodSchema = shape?.method;
  35. if (!methodSchema) {
  36. throw new Error('Schema is missing a method literal');
  37. }
  38. const value = getLiteralValue(methodSchema);
  39. if (typeof value !== 'string') {
  40. throw new Error('Schema method literal must be a string');
  41. }
  42. return value;
  43. }
  44. export function parseWithCompat(schema, data) {
  45. const result = safeParse(schema, data);
  46. if (!result.success) {
  47. throw result.error;
  48. }
  49. return result.data;
  50. }
  51. //# sourceMappingURL=zod-json-schema-compat.js.map