object.mjs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { parseDef } from "../parseDef.mjs";
  2. function decideAdditionalProperties(def, refs) {
  3. if (refs.removeAdditionalStrategy === 'strict') {
  4. return def.catchall._def.typeName === 'ZodNever' ?
  5. def.unknownKeys !== 'strict'
  6. : parseDef(def.catchall._def, {
  7. ...refs,
  8. currentPath: [...refs.currentPath, 'additionalProperties'],
  9. }) ?? true;
  10. }
  11. else {
  12. return def.catchall._def.typeName === 'ZodNever' ?
  13. def.unknownKeys === 'passthrough'
  14. : parseDef(def.catchall._def, {
  15. ...refs,
  16. currentPath: [...refs.currentPath, 'additionalProperties'],
  17. }) ?? true;
  18. }
  19. }
  20. export function parseObjectDef(def, refs) {
  21. const result = {
  22. type: 'object',
  23. ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => {
  24. if (propDef === undefined || propDef._def === undefined)
  25. return acc;
  26. const propertyPath = [...refs.currentPath, 'properties', propName];
  27. const parsedDef = parseDef(propDef._def, {
  28. ...refs,
  29. currentPath: propertyPath,
  30. propertyPath,
  31. });
  32. if (parsedDef === undefined)
  33. return acc;
  34. if (refs.openaiStrictMode && propDef.isOptional() && !propDef.isNullable()) {
  35. console.warn(`Zod field at \`${propertyPath.join('/')}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required\nThis will become an error in a future version of the SDK.`);
  36. }
  37. return {
  38. properties: {
  39. ...acc.properties,
  40. [propName]: parsedDef,
  41. },
  42. required: propDef.isOptional() && !refs.openaiStrictMode ? acc.required : [...acc.required, propName],
  43. };
  44. }, { properties: {}, required: [] }),
  45. additionalProperties: decideAdditionalProperties(def, refs),
  46. };
  47. if (!result.required.length)
  48. delete result.required;
  49. return result;
  50. }
  51. //# sourceMappingURL=object.mjs.map