UNPKG

reign

Version:

A persistent, typed-objects implementation.

116 lines (90 loc) 2.98 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TypedObject = undefined; exports.make = make; var _ = require("../"); var _symbols = require("../symbols"); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var TypedObject = exports.TypedObject = function TypedObject() { _classCallCheck(this, TypedObject); }; /** * Make the TypeClass meta-class for the given realm. */ function make(realm) { /** * TypeClass meta-class. */ function TypeClass(name, inititalizer) { function define() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var config = inititalizer.apply(undefined, args); if (config instanceof TypeClass) { // Issue 1138 Object.setPrototypeOf(config, define.prototype); return config; } var constructor = void 0; function Target() { return constructor.apply(this, arguments); } if (typeof config === 'function') { config = config(Target); } if (config[_symbols.$isType]) { if (config.name && config.id) { realm.registry.add(config); } return config; } var source = config.prototype || {}; // Issue 1138 if (!TypedObject.prototype.isPrototypeOf(source) && isSimplePrototype(Object.getPrototypeOf(source))) { // Issue 1138 Object.setPrototypeOf(source, TypedObject.prototype); } constructor = typeof config.constructor === 'function' ? config.constructor : function (input) { if (!(this instanceof Target)) { return input; } }; Target.prototype = Object.create(source); Target.prototype.constructor = Target; Object.defineProperty(Target.prototype, _symbols.$ValueType, { value: Target }); // Issue 1138 Object.setPrototypeOf(Target, define.prototype); Object.keys(config).filter(function (name) { return name !== 'prototype' && name !== 'constructor'; }).forEach(function (name) { Object.defineProperty(Target, name, { value: config[name] }); }); Object.defineProperty(Target, _symbols.$isType, { value: true }); if (Target.name && Target.id) { realm.registry.add(Target); } return Target; } // Issue 1138 Object.setPrototypeOf(define, TypeClass.prototype); // Issue 1138 Object.setPrototypeOf(define.prototype, Function.prototype); Object.defineProperties(define, { name: { value: name } }); return define; } // Issue 1138 Object.setPrototypeOf(TypeClass.prototype, Function.prototype); return TypeClass; } function isSimplePrototype(prototype) { return prototype == null || prototype === Object.prototype; }