UNPKG

@backland/schema

Version:

TypeScript schema declaration and validation library with static type inference

257 lines (256 loc) 13 kB
var _excluded = ["def", "defaultValue"]; function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } import { inspectObject, simpleObjectClone } from '@backland/utils'; import { CircularDeps } from '../CircularDeps'; import { parseValidationError } from '../applyValidator'; import { arrayFieldParse } from './ArrayFieldParse'; import { createFieldTypeError, isFieldError } from './FieldTypeErrors'; import { $inferableKey } from './Infer'; export * from '../applyValidator'; export var FieldsTypeCache = new Map(); export var FieldType = /*#__PURE__*/function () { function FieldType(config) { var _this = this; _classCallCheck(this, FieldType); _defineProperty(this, "typeName", void 0); _defineProperty(this, "type", void 0); _defineProperty(this, "def", void 0); _defineProperty(this, $inferableKey, void 0); _defineProperty(this, "composer", void 0); _defineProperty(this, "id", void 0); _defineProperty(this, "name", void 0); _defineProperty(this, "options", void 0); _defineProperty(this, "optional", void 0); _defineProperty(this, "list", void 0); _defineProperty(this, "defaultValue", void 0); _defineProperty(this, "description", void 0); _defineProperty(this, "hidden", void 0); _defineProperty(this, "describe", function (description) { _this.description = description; return _this; }); _defineProperty(this, "describeField", function () { return _this.asFinalFieldDef; }); _defineProperty(this, "applyParser", function (_parser) { return function (input, _options) { var options = {}; if (typeof _options === 'function') { options = { customErrorMessage: _options }; } if (typeof _options === 'string') { options = { customErrorMessage: _options }; } if (_typeof(_options) === 'object') { options = _options; } var _options3 = options, customMessage = _options3.customErrorMessage, _options3$includeHidd = _options3.includeHidden, includeHidden = _options3$includeHidd === void 0 ? true : _options3$includeHidd; // keep it secret if (_this.hidden && !includeHidden) return undefined; if (_parser.preParse) { input = _parser.preParse(input); } if ((input === undefined || input === null) && _this.defaultValue !== undefined) { input = _this.defaultValue; } if (_this.type === 'null' && input === undefined) { return null; } if (_this.type !== 'null' && input === null && _this.optional) { return undefined; } if (input === undefined && _this.optional) { return undefined; } if (input === undefined && !_this.optional) { throw createFieldTypeError('requiredField'); } if (_this.asFinalFieldDef.list) { return arrayFieldParse({ arrayOptions: {}, // since is the shot definition (list:true) there is no options input: input, parser: function parser(input) { return _parser.parse(input, options); }, parserOptions: options }); } try { return _parser.parse(input, options); } catch (originalError) { if (!customMessage && isFieldError(originalError)) { throw originalError; } throw parseValidationError(input, customMessage, originalError); } }; }); _defineProperty(this, "parse", void 0); _defineProperty(this, "__isFieldType", true); _defineProperty(this, "clone", function () { var _this$asFinalFieldDef = _this.asFinalFieldDef, def = _this$asFinalFieldDef.def, defaultValue = _this$asFinalFieldDef.defaultValue, rest = _objectWithoutProperties(_this$asFinalFieldDef, _excluded); var field; if (rest.type === 'literal') { field = _objectSpread(_objectSpread({}, simpleObjectClone(rest)), {}, { def: def, defaultValue: defaultValue }); } else { field = simpleObjectClone(rest); if (def !== undefined) { field.def = simpleObjectClone(def); } if (defaultValue !== undefined) { field.defaultValue = simpleObjectClone(def); } } return CircularDeps.fieldInstanceFromDef(field); }); var name = config.name, id = config.id, _def = config.def, _config$options = config.options, _options2 = _config$options === void 0 ? {} : _config$options; this.id = id; this.typeName = name; this.type = name; this.options = _options2; var defKeys = _def ? Object.keys(_def).sort() : undefined; if (defKeys !== null && defKeys !== void 0 && defKeys.length) { this.def = _def; } if (id) { var existing = FieldsTypeCache.get(id); if (existing) { var _existing$defKeys; var existingKeys = (_existing$defKeys = existing.defKeys) === null || _existing$defKeys === void 0 ? void 0 : _existing$defKeys.join(', '); if (existing.fieldType.typeName !== this.typeName) { throw new Error("Field with id \"".concat(id, "\" already registered with different type:\n \"").concat(inspectObject({ old: existing.fieldType.asFinalFieldDef, current: this.asFinalFieldDef }, { depth: 2 }), "\"")); } if ((defKeys === null || defKeys === void 0 ? void 0 : defKeys.join(', ')) !== existingKeys) { throw new Error("Field with id \"".concat(id, "\" already registered with different fields:\n \"").concat(existingKeys, "\"")); } } FieldsTypeCache.set(id, { fieldType: this, defKeys: defKeys }); } } _createClass(FieldType, [{ key: "definition", get: function get() { return this.asFinalFieldDef; } }, { key: "validate", value: function validate(input) { try { this.parse(input); return true; } catch (e) { return false; } } }, { key: "is", value: function is(input) { return this.validate(input); } }, { key: "toOptional", value: function toOptional() { // @ts-ignore this.optional = true; return this; } }, { key: "toRequired", value: function toRequired() { // @ts-ignore this.optional = false; return this; } }, { key: "toList", value: function toList(options) { // @ts-ignore this.list = true; if (options && _typeof(options) === 'object') { this.options = _objectSpread(_objectSpread({}, this.options), options); } return this; } }, { key: "setDefaultValue", value: function setDefaultValue(value) { // @ts-ignore this.defaultValue = value; return this; } }, { key: "asFinalFieldDef", get: function get() { var res = { def: this.def, defaultValue: this.defaultValue, description: this.description, hidden: this.hidden, list: this.list, optional: this.optional, type: this.type }; Object.entries(res).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), k = _ref2[0], v = _ref2[1]; if (v === undefined || v === false) { delete res[k]; } }); return res; } }], [{ key: "create", value: function create() { throw new Error('not implemented in abstract class.'); } }]); return FieldType; }(); export function isFieldInstance(t) { return (t === null || t === void 0 ? void 0 : t.__isFieldType) === true; } //# sourceMappingURL=FieldType.js.map