UNPKG

runtime-type

Version:

Module for casting to types at runtime.

188 lines (187 loc) 10.6 kB
"use strict"; 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); } Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _smartError = _interopRequireDefault(require("smart-error")); var _nullable = _interopRequireDefault(require("./base/nullable")); var _base = _interopRequireDefault(require("./base")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } 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 _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, 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 _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var Shape = /*#__PURE__*/function (_Base) { _inherits(Shape, _Base); var _super = _createSuper(Shape); function Shape(shape) { var _this; _classCallCheck(this, Shape); _this = _super.call(this); _this._shape = null; _this._required = []; _this._dynamic = []; Object.keys(shape).forEach(function (key) { var type = shape[key]; if (!(type instanceof _base["default"])) { throw new _smartError["default"]("The type ".concat(type, " must be an instance of Type."), 'unsupported_operation'); } if (key.indexOf('?') === key.length - 1) { delete shape[key]; var k = key.substr(0, key.length - 1); shape[k] = type; if (_this._isKeyDynamic(k)) { _this._dynamic.push(k); } return; } if (_this._isKeyDynamic(key)) { _this._dynamic.push(key); } _this._required.push(key); }); _this._shape = shape; return _this; } _createClass(Shape, [{ key: "cast", value: function cast(value) { var _this2 = this; var o = {}; Object.keys(this._shape).forEach(function (key) { if (_this2._dynamic.includes(key)) { return; } var type = _this2._shape[key]; if (value[key] === undefined) { if (_this2._required.includes(key)) { throw new _smartError["default"]("Missing key '".concat(key, "' in the shape."), 'unsupported_operation'); } return; } try { o[key] = type.cast(value[key]); } catch (e) { if (e.code === 'ERR_INVALID_CAST') { throw new _smartError["default"]("The value at key '".concat(key, "' cannot be cast to ").concat(type.getName().toLowerCase(), "."), 'invalid_cast'); } throw e; } }); var usedDynamicKeys = []; Object.keys(value).forEach(function (key) { if (_this2._shape[key] === undefined) { var _iterator = _createForOfIteratorHelper(_this2._dynamic), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var dynamicKey = _step.value; var type = _this2._shape[dynamicKey]; if (type.canCast(value[key])) { o[key] = type.cast(value[key]); if (_this2._isKeyRequired(dynamicKey) && !usedDynamicKeys.includes(dynamicKey)) { usedDynamicKeys.push(dynamicKey); } } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } if (o[key] !== undefined) { return; } throw new _smartError["default"]("The key '".concat(key, "' is not defined in the shape."), 'unsupported_operation'); } }); if (usedDynamicKeys.length !== this._dynamic.length) { this._dynamic.forEach(function (key) { if (usedDynamicKeys.includes(key)) { return; } if (_this2._isKeyOptional(key)) { return; } throw new _smartError["default"]("Missing key '".concat(key, "' in the shape."), 'unsupported_operation'); }); } return o; } }, { key: "getName", value: function getName() { return 'Shape'; } }, { key: "toString", value: function toString() { var _this3 = this; var o = {}; Object.keys(this._shape).forEach(function (key) { var k = _this3._isKeyRequired(key) ? key : "".concat(key, "?"); o[k] = _this3._shape[key].toString(); }); return "shape(".concat(JSON.stringify(o), ")"); } }, { key: "getTSType", value: function getTSType() { var _this4 = this; var format = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var a = Object.keys(this._shape).map(function (key) { var k = _this4._isKeyRequired(key) ? key : "".concat(key, "?"); if (_this4._isKeyDynamic(key)) { k = "[".concat(key.replace(/^\[(\w+)\]$/, '$1'), ": string]"); } if (_this4._shape[key] instanceof Shape && format) { return "".concat(k, ": ").concat(_this4._shape[key].getTSType(format, level + 1)); } return "".concat(k, ": ").concat(_this4._shape[key].getTSType(format)); }); if (!a.length) { return '{}'; } if (!format) { return "{ ".concat(a.join(', '), " }"); } var tabs = new Array(level + 1).fill('\t').join(''); return "{\n".concat(a.map(function (v) { return "".concat(tabs).concat(v, ";"); }).join('\n'), "\n").concat(tabs.substr(1), "}"); } }, { key: "_getTypeOf", value: function _getTypeOf() { return 'object'; } }, { key: "_isKeyDynamic", value: function _isKeyDynamic(key) { return /^\[\w+\]$/.test(key); } }, { key: "_isKeyOptional", value: function _isKeyOptional(key) { return !this._isKeyRequired(key); } }, { key: "_isKeyRequired", value: function _isKeyRequired(key) { return this._required.includes(key); } }]); return Shape; }(_nullable["default"]); exports["default"] = Shape;