record.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.parseRecordDef = void 0;
  4. const zod_1 = require("zod");
  5. const parseDef_js_1 = require("../parseDef.js");
  6. const string_js_1 = require("./string.js");
  7. const branded_js_1 = require("./branded.js");
  8. function parseRecordDef(def, refs) {
  9. if (refs.target === "openAi") {
  10. console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
  11. }
  12. if (refs.target === "openApi3" &&
  13. def.keyType?._def.typeName === zod_1.ZodFirstPartyTypeKind.ZodEnum) {
  14. return {
  15. type: "object",
  16. required: def.keyType._def.values,
  17. properties: def.keyType._def.values.reduce((acc, key) => ({
  18. ...acc,
  19. [key]: (0, parseDef_js_1.parseDef)(def.valueType._def, {
  20. ...refs,
  21. currentPath: [...refs.currentPath, "properties", key],
  22. }) ?? {},
  23. }), {}),
  24. additionalProperties: refs.rejectedAdditionalProperties,
  25. };
  26. }
  27. const schema = {
  28. type: "object",
  29. additionalProperties: (0, parseDef_js_1.parseDef)(def.valueType._def, {
  30. ...refs,
  31. currentPath: [...refs.currentPath, "additionalProperties"],
  32. }) ?? refs.allowedAdditionalProperties,
  33. };
  34. if (refs.target === "openApi3") {
  35. return schema;
  36. }
  37. if (def.keyType?._def.typeName === zod_1.ZodFirstPartyTypeKind.ZodString &&
  38. def.keyType._def.checks?.length) {
  39. const { type, ...keyType } = (0, string_js_1.parseStringDef)(def.keyType._def, refs);
  40. return {
  41. ...schema,
  42. propertyNames: keyType,
  43. };
  44. }
  45. else if (def.keyType?._def.typeName === zod_1.ZodFirstPartyTypeKind.ZodEnum) {
  46. return {
  47. ...schema,
  48. propertyNames: {
  49. enum: def.keyType._def.values,
  50. },
  51. };
  52. }
  53. else if (def.keyType?._def.typeName === zod_1.ZodFirstPartyTypeKind.ZodBranded &&
  54. def.keyType._def.type._def.typeName === zod_1.ZodFirstPartyTypeKind.ZodString &&
  55. def.keyType._def.type._def.checks?.length) {
  56. const { type, ...keyType } = (0, branded_js_1.parseBrandedDef)(def.keyType._def, refs);
  57. return {
  58. ...schema,
  59. propertyNames: keyType,
  60. };
  61. }
  62. return schema;
  63. }
  64. exports.parseRecordDef = parseRecordDef;