UNPKG

alpha-dic

Version:

Asynchronous dependency injection container

56 lines (55 loc) 1.62 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TypeRef = void 0; const isPred = require("predicates"); const reservedConstructors = new Set([ 'Function', 'Object', 'Promise' ].map(x => global[x]) .filter(x => x)); class TypeRef { constructor(target) { this.target = target; if (!TypeRef.isAllowedTarget(target)) { throw new Error(`Target ${target} is not allowed`); } Object.freeze(this); } matches(type) { //tslint:disable-next-line: strict-comparisons return type.target === this.target || type.target.prototype instanceof this.target; } toString() { return `instance of class "${this.target.name}"`; } get predicate() { return x => x.type !== undefined && this.matches(x.type); } static isAllowedTarget(target) { return !reservedConstructors.has(target); } static is(value) { return value instanceof TypeRef; } static createFromType(type) { if (TypeRef.isAllowedTarget(type)) { return new TypeRef(type); } } static createFromValue(value) { if (isPred.object(value) && value !== null) { const proto = Object.getPrototypeOf(value); if (TypeRef.isAllowedTarget(proto.constructor)) { return new TypeRef(proto.constructor); } } } static predicateForType(type) { const ref = TypeRef.createFromType(type); if (ref) { return ref.predicate; } } } exports.TypeRef = TypeRef;