parseDef.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.parseDef = void 0;
  4. const Options_js_1 = require("./Options.js");
  5. const selectParser_js_1 = require("./selectParser.js");
  6. function parseDef(def, refs, forceResolution = false) {
  7. const seenItem = refs.seen.get(def);
  8. if (refs.override) {
  9. const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
  10. if (overrideResult !== Options_js_1.ignoreOverride) {
  11. return overrideResult;
  12. }
  13. }
  14. if (seenItem && !forceResolution) {
  15. const seenSchema = get$ref(seenItem, refs);
  16. if (seenSchema !== undefined) {
  17. return seenSchema;
  18. }
  19. }
  20. const newItem = { def, path: refs.currentPath, jsonSchema: undefined };
  21. refs.seen.set(def, newItem);
  22. const jsonSchemaOrGetter = (0, selectParser_js_1.selectParser)(def, def.typeName, refs);
  23. // If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive)
  24. const jsonSchema = typeof jsonSchemaOrGetter === "function"
  25. ? parseDef(jsonSchemaOrGetter(), refs)
  26. : jsonSchemaOrGetter;
  27. if (jsonSchema) {
  28. addMeta(def, refs, jsonSchema);
  29. }
  30. if (refs.postProcess) {
  31. const postProcessResult = refs.postProcess(jsonSchema, def, refs);
  32. newItem.jsonSchema = jsonSchema;
  33. return postProcessResult;
  34. }
  35. newItem.jsonSchema = jsonSchema;
  36. return jsonSchema;
  37. }
  38. exports.parseDef = parseDef;
  39. const get$ref = (item, refs) => {
  40. switch (refs.$refStrategy) {
  41. case "root":
  42. return { $ref: item.path.join("/") };
  43. case "relative":
  44. return { $ref: getRelativePath(refs.currentPath, item.path) };
  45. case "none":
  46. case "seen": {
  47. if (item.path.length < refs.currentPath.length &&
  48. item.path.every((value, index) => refs.currentPath[index] === value)) {
  49. console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
  50. return {};
  51. }
  52. return refs.$refStrategy === "seen" ? {} : undefined;
  53. }
  54. }
  55. };
  56. const getRelativePath = (pathA, pathB) => {
  57. let i = 0;
  58. for (; i < pathA.length && i < pathB.length; i++) {
  59. if (pathA[i] !== pathB[i])
  60. break;
  61. }
  62. return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
  63. };
  64. const addMeta = (def, refs, jsonSchema) => {
  65. if (def.description) {
  66. jsonSchema.description = def.description;
  67. if (refs.markdownDescription) {
  68. jsonSchema.markdownDescription = def.description;
  69. }
  70. }
  71. return jsonSchema;
  72. };