zodToJsonSchema.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.zodToJsonSchema = void 0;
  4. const parseDef_js_1 = require("./parseDef.js");
  5. const Refs_js_1 = require("./Refs.js");
  6. const zodToJsonSchema = (schema, options) => {
  7. const refs = (0, Refs_js_1.getRefs)(options);
  8. const definitions = typeof options === "object" && options.definitions
  9. ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({
  10. ...acc,
  11. [name]: (0, parseDef_js_1.parseDef)(schema._def, {
  12. ...refs,
  13. currentPath: [...refs.basePath, refs.definitionPath, name],
  14. }, true) ?? {},
  15. }), {})
  16. : undefined;
  17. const name = typeof options === "string"
  18. ? options
  19. : options?.nameStrategy === "title"
  20. ? undefined
  21. : options?.name;
  22. const main = (0, parseDef_js_1.parseDef)(schema._def, name === undefined
  23. ? refs
  24. : {
  25. ...refs,
  26. currentPath: [...refs.basePath, refs.definitionPath, name],
  27. }, false) ?? {};
  28. const title = typeof options === "object" &&
  29. options.name !== undefined &&
  30. options.nameStrategy === "title"
  31. ? options.name
  32. : undefined;
  33. if (title !== undefined) {
  34. main.title = title;
  35. }
  36. const combined = name === undefined
  37. ? definitions
  38. ? {
  39. ...main,
  40. [refs.definitionPath]: definitions,
  41. }
  42. : main
  43. : {
  44. $ref: [
  45. ...(refs.$refStrategy === "relative" ? [] : refs.basePath),
  46. refs.definitionPath,
  47. name,
  48. ].join("/"),
  49. [refs.definitionPath]: {
  50. ...definitions,
  51. [name]: main,
  52. },
  53. };
  54. if (refs.target === "jsonSchema7") {
  55. combined.$schema = "http://json-schema.org/draft-07/schema#";
  56. }
  57. else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
  58. combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
  59. }
  60. if (refs.target === "openAi" &&
  61. ("anyOf" in combined ||
  62. "oneOf" in combined ||
  63. "allOf" in combined ||
  64. ("type" in combined && Array.isArray(combined.type)))) {
  65. console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
  66. }
  67. return combined;
  68. };
  69. exports.zodToJsonSchema = zodToJsonSchema;