undefinedAsNull.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. /** @typedef {import("ajv").Ajv} Ajv */
  7. /**
  8. *
  9. * @param {Ajv} ajv
  10. * @param {string} keyword
  11. * @param {any} definition
  12. */
  13. function addKeyword(ajv, keyword, definition) {
  14. let customRuleCode;
  15. try {
  16. // @ts-ignore
  17. // eslint-disable-next-line global-require
  18. customRuleCode = require("ajv/lib/dotjs/custom"); // @ts-ignore
  19. const {
  20. RULES
  21. } = ajv;
  22. let ruleGroup;
  23. for (let i = 0; i < RULES.length; i++) {
  24. const rg = RULES[i];
  25. if (typeof rg.type === "undefined") {
  26. ruleGroup = rg;
  27. break;
  28. }
  29. }
  30. const rule = {
  31. keyword,
  32. definition,
  33. custom: true,
  34. code: customRuleCode,
  35. implements: definition.implements
  36. };
  37. ruleGroup.rules.unshift(rule);
  38. RULES.custom[keyword] = rule;
  39. RULES.keywords[keyword] = true;
  40. RULES.all[keyword] = true;
  41. } catch (e) {// Nothing, fallback
  42. }
  43. }
  44. /**
  45. *
  46. * @param {Ajv} ajv
  47. * @returns {Ajv}
  48. */
  49. function addUndefinedAsNullKeyword(ajv) {
  50. // There is workaround for old versions of ajv, where `before` is not implemented
  51. addKeyword(ajv, "undefinedAsNull", {
  52. modifying: true,
  53. /**
  54. * @param {boolean} kwVal
  55. * @param {unknown} data
  56. * @param {any} parentSchema
  57. * @param {string} dataPath
  58. * @param {unknown} parentData
  59. * @param {number | string} parentDataProperty
  60. * @return {boolean}
  61. */
  62. validate(kwVal, data, parentSchema, dataPath, parentData, parentDataProperty) {
  63. if (kwVal && parentSchema && typeof parentSchema.enum !== "undefined" && parentData && typeof parentDataProperty === "number") {
  64. const idx =
  65. /** @type {number} */
  66. parentDataProperty;
  67. const parentDataRef =
  68. /** @type {any[]} */
  69. parentData;
  70. if (typeof parentDataRef[idx] === "undefined") {
  71. parentDataRef[idx] = null;
  72. }
  73. }
  74. return true;
  75. }
  76. });
  77. return ajv;
  78. }
  79. var _default = addUndefinedAsNullKeyword;
  80. exports.default = _default;