github
DocsBlog
fontcolor_theme
package

API @deepkit/core

npm install @deepkit/core

Classes - Network
Functions - Decorators
Functions - Network
Functions - String
Const - Type Guards

Classes

Timer [source]
export class Timer {
    setTimeout(cb: () => void, timeout: number): any;
    /**
     * Clears all timers at once.
     */
    clear();
}
ProcessLock [source]
export class ProcessLock {
    constructor(public readonly id: string);
    async acquire(ttl: number = , timeout: number = );
    isLocked();
    tryLock(ttl: number = );
    unlock();
}

This lock mechanism works only for one process (worker).

live-mutex: has horrible API and doesn't allow to check if an key is currently locked. proper-filelock: No way to do a correct mutex locking with event-driven blocking acquire() method. redislock: Very bad performance on high-load (when multiple locks on the same key wait, since it loops) mongodb lock: even worse performance than redis. Jesus.

ProcessLocker [source]
export class ProcessLocker {
    /**
     *
     * @param id
     * @param ttl optional defines when the times automatically unlocks.
     * @param timeout if after `timeout` seconds the lock isn't acquired, it throws an error.
     */
    async acquireLock(id: string, ttl: number = , timeout: number = ): Promise<ProcessLock>;
    async tryLock(id: string, ttl: number = ): Promise<ProcessLock | undefined>;
    isLocked(id: string): boolean;
}
Mutex [source]
export class Mutex {
    unlock(): void;
    async lock(): Promise<void>;
}
ParsedHost [source]
export class ParsedHost {
    host: string;
    port: number;
    unixSocket: string;
    get isUnixSocket(): boolean;
    get isHostname(): boolean;
    get hostWithIp(): string;
    toString(): string;
    getWebSocketUrl(secure: boolean = false);
    getHttpUrl(secure: boolean = false);
}
CompilerContext [source]
export class CompilerContext {
    readonly context;
    maxReservedVariable: number;
    /**
     * Code that is executed in the context, but before the actual function is generated.
     * This helps for example to initialize dynamically some context variables.
     */
    preCode: string;
    initialiseVariables: string[];
    config: {
        indent: boolean;
    };
    constructor(config: Partial<CompilerContext[]> = {});
    reserveName(name: string): string;
    set(values: {
        [name: string]: any;
    });
    /**
     * Returns always the same variable name for the same value.
     * The variable name should not be set afterwards.
     */
    reserveConst(value: any, name: string = ): string;
    reserveVariable(name: string = , value?: any): string;
    raw(functionCode: string): Function;
    build(functionCode: string, ...args: string[]): any;
    buildAsync(functionCode: string, ...args: string[]): Function;
}
EmitterEvent [source]
export class EmitterEvent {
    readonly id;
    stopped;
    propagationStopped;
    /**
     * Stop propagating the event to subsequent event listeners.
     */
    stopPropagation();
    /**
     * Signal the emitter that you want to abort.
     * Subsequent event listeners will still be called.
     */
    stop();
}
EventEmitter [source]
export class EventEmitter<T extends EmitterEvent> {
    constructor(protected parent?: EventEmitter<any>);
    subscribe(callback: Subscriber<T>): EventSubscription;
    emit(event: T): void;
    hasSubscriptions(): boolean;
}
AsyncEventEmitter [source]
export class AsyncEventEmitter<T extends EmitterEvent> {
    constructor(protected parent?: AsyncEventEmitter<any>);
    subscribe(callback: AsyncSubscriber<T>): AsyncEventSubscription;
    async emit(event: T): Promise<void>;
    hasSubscriptions(): boolean;
}

Const

AsyncFunction [source]
new (...args: string[]) => Function

Functions

getClassName [source]
<T>(classTypeOrInstance: ClassType<T> | Object): string

Returns the class name either of the class definition or of the class of an instance.

Note when code is minimized/uglified this output will change. You should disable in your compile the className modification.

getClassPropertyName [source]
<T>(classType: ClassType<T> | Object, propertyName: string): string

Same as getClassName but appends the propertyName.

applyDefaults [source]
<T>(classType: ClassType<T>, target: { [k: string]: any; }): T
identifyType [source]
(obj: any): any

Tries to identify the object by normalised result of Object.toString(obj).

getClassTypeFromInstance [source]
<T>(target: T): ClassType<T>

Returns the ClassType for a given instance.

stringifyValueWithType [source]
(value: any, depth?: number): string

Returns a human-readable string representation from the given value.

changeClass [source]
<T>(value: object, newClass: ClassType<T>): T

Changes the class of a given instance and returns the new object.

prettyPrintObject [source]
(object: object, depth?: number): string
indexOf [source]
<T>(array: T[], item: T): number
sleep [source]
(seconds: number): Promise<void>
copy [source]
<T>(v: T[]): T[]

Creates a shallow copy of given array.

empty [source]
<T>(value?: T[] | object | {}): boolean

Checks whether given array or object is empty (no keys). If given object is falsy, returns false.

size [source]
<T>(array: T[] | { [key: string]: T; }): number

Returns the size of given array or object.

firstKey [source]
(v: { [key: string]: any; } | object): string | undefined

Returns the first key of a given object.

lastKey [source]
(v: { [key: string]: any; } | object): string | undefined

Returns the last key of a given object.

first [source]
<T>(v: { [key: string]: T; } | T[]): T | undefined

Returns the first value of given array or object.

last [source]
<T>(v: { [key: string]: T; } | T[]): T | undefined

Returns the last value of given array or object.

average [source]
(array: number[]): number

Returns the average of a number array.

prependObjectKeys [source]
(o: { [k: string]: any; }, prependText: string): { [k: string]: any; }
appendObject [source]
(origin: { [k: string]: any; }, extend: { [k: string]: any; }, prependKeyName?: string): void
asyncOperation [source]
<T>(executor: (resolve: (value: T) => void, reject: (error: any) => void) => void | Promise<void>): Promise<T>

A better alternative to "new Promise()" that supports error handling and maintains the stack trace for Error.stack.

When you use new Promise() you need to wrap your code inside a try-catch to call reject on error. asyncOperation() does this automatically.

When you use new Promise() you will lose the stack trace when reject(new Error()) is called. asyncOperation() makes sure the error stack trace is the correct one.

fixAsyncOperation [source]
<T>(promise: Promise<T>): Promise<T>

When an API is called that returns a promise that loses the stack trace on error, you can use fixAsyncOperation().

cons storage = new BrokenPromiseStorage();
const files = await fixAsyncOperation(storage.files('/'));
mergePromiseStack [source]
<T>(promise: Promise<T>, stack?: string): Promise<T>
createStack [source]
(removeCallee?: boolean): string
mergeStack [source]
(error: Error, stack: string): void
ensureError [source]
(error?: any, classType?: ClassType): Error

Makes sure the given value is an error. If it's not an error, it creates a new error with the given value as message.

collectForMicrotask [source]
<T>(callback: (args: T[]) => void): (arg: T) => void
getPathValue [source]
(bag: { [field: string]: any; }, parameterPath: string, defaultValue?: any): any
setPathValue [source]
(bag: object, parameterPath: string, value: any): void
deletePathValue [source]
(bag: object, parameterPath: string): void
humanBytes [source]
(bytes: number, si?: boolean): string

Returns the human-readable byte representation.

getObjectKeysSize [source]
(obj: object): number

Returns the number of properties on obj. This is 20x faster than Object.keys(obj).length.

getParentClass [source]
(classType: ClassType): ClassType | undefined
getInheritanceChain [source]
(classType: ClassType): ClassType[]
inDebugMode [source]
(): boolean
createDynamicClass [source]
(name: string, base?: ClassType): ClassType

Create a new class with the given name. This is currently the only know way to make it workable in browsers too.

iterableSize [source]
(value: Array<unknown> | Set<unknown> | Map<unknown, unknown>): number
getCurrentFileName [source]
(offset?: number): string

Returns __filename, works in both cjs and esm.

getCurrentDirName [source]
(): string

Returns the directory name of the current file (__dirname), works in both cjs and esm.

escapeRegExp [source]
(string: string): string

Escape special characters in a regex string, so it can be used as a literal string.

hasProperty [source]
(object: any, property: any): boolean
range [source]
(startOrLength: number, stop?: number, step?: number): IterableIterator<number>

Returns an iterator of numbers from start (inclusive) to stop (exclusive) by step.

rangeArray [source]
(startOrLength: number, stop?: number, step?: number): number[]

Returns an array of numbers from start (inclusive) to stop (exclusive) by step.

Works the same as python's range function.

zip [source]
<T extends (readonly unknown[])[]>(...args: T): { [K in keyof T]: T[K] extends (infer V)[] ? V : never; }[]

Returns a combined array of the given arrays.

Works the same as python's zip function.

forwardTypeArguments [source]
(x: any, y: any): void

Forwards the runtime type arguments from function x to function y. This is necessary when a generic function is overridden and forwarded to something else.

let generic = <T>(type?: ReceiveType<T>) => undefined;

let forwarded<T> = () => {
    forwardTypeArguments(forwarded, generic); //all type arguments are forwarded to generic()
    generic(); //call as usual
}

forwarded<any>(); //generic receives any in runtime.

Note that generic.bind(this) will not work, as bind() creates a new function and forwarded type arguments can not reach the original function anymore.

let forwarded<T> = () => {
    const bound = generic.bind(this);
    forwardTypeArguments(forwarded, bound); //can not be forwarded anymore
    bound(); //fails
}

This is a limitation of JavaScript. In this case you have to manually forward type arguments.

let forwarded<T> = (type?: ReceiveType<T>) => {
   const bound = generic.bind(this);
   bound(type);
}
formatError [source]
(error: any, withStack?: boolean): string
assertInstanceOf [source]
<T>(object: any, constructor: { new (...args: any[]): T; }): asserts object is T

Asserts that the given object is an instance of the given class.

assertDefined [source]
<T>(value: T): asserts value is NonNullable<T>

Asserts that the given value is defined (not null and not undefined).

log [source]
(): (target: object, propertyKey: string | symbol, descriptor: PropertyDescriptor) => PropertyDescriptor

Logs every call to this method on stdout.

stack [source]
(): (target: object, propertyKey: string, descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<any>>) => void

Makes sure that calls to this async method are stacked up and are called one after another and not parallel.

singleStack [source]
(): (target: object, propertyKey: string, descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<any>>) => void

Makes sure that this async method is only running once at a time. When this method is running and it is tried to call it another times, that call is "dropped" and it returns simply the result of the previous running call (waiting for it to complete first).

getEnumLabel [source]
(enumType: { [field: string]: any; }, id: any): any

Returns the enum label for a given enum value.

getEnumLabels [source]
(enumDefinition: any): string[]

Returns all possible enum labels.

getEnumValues [source]
(enumDefinition: any): any[]

Returns all possible enum keys.

getEnumKeyLabelMap [source]
(enumDefinition: any): Map<any, string>
isValidEnumValue [source]
(enumDefinition: any, value: any, allowLabelsAsValue?: boolean): boolean

Checks whether given enum value is valid.

getValidEnumValue [source]
(enumDefinition: any, value: any, allowLabelsAsValue?: boolean): any
parseHost [source]
(hostWithIpOrUnixPath: string): ParsedHost
toFastProperties [source]
(obj: any): void
indent [source]
(indentation: number, prefix?: string): (str?: string) => string
capitalize [source]
(string: string): string
throttleTime [source]
(call: Function, cps?: number): (...args: any[]) => void

Wraps a function and calls it only cps times per frame.

This is handy to throttle all kind of rapid calls, like mouse move events or other kind of events.

bufferedGate [source]
<T>(callback: (arg: T) => any): { activate: () => void; call: (i: T) => void; }

This functions returns a stack that is filled as long as the gate is not activated. Once activated all recorded calls go to given callback and subsequent calls go directly to given callback.

nextTick [source]
(cb: () => void) => any
clearTick [source]
(id: any) => any
extractParameters [source]
(fn: string | Function | ClassType): string[]
extractMethodBody [source]
(classCode: string, name: string): string
removeStrings [source]
(code: string): string
urlJoin [source]
(...path: string[]): string
arrayHasItem [source]
<T>(array: T[], item: T): boolean
arrayClear [source]
<T>(array: T[]): number

Clears the array so its empty. Returns the amount of removed items.

arrayRemoveItem [source]
<T>(array: T[], item: T): boolean

Removes on particular item by reference of an array.

arrayMoveItem [source]
<A extends T[], T>(array: A, item: T, move: number): A

Moves a particular item in an array up or down (move>0=down, move<0=up). Changes the array itself.

const array = ['a', 'b', 'c'];

arrayMoveItem(array, 'a', +1); //['b', 'a', 'c']
arrayMoveItem(array, 'a', -1); //['a', 'b', 'c']

arrayMoveItem(array, 'b', -1); //['b', 'a', 'c']
arrayMoveItem(array, 'b', +1); //['a', 'c', 'b']

arrayMoveItem(array, 'c', -1); //['b', 'c', 'b']
arrayMoveItem(array, 'c', +1); //['a', 'b', 'c']
bufferConcat [source]
(chunks: Uint8Array[], length?: number): Uint8Array

Concat multiple buffers into one.

bufferToString [source]
(buffer: string | Uint8Array): string

Convert a buffer to a string.

nativeBase64ToUint8Array [source]
(base64: string): Uint8Array
createBuffer [source]
(size: number) => Uint8Array<ArrayBufferLike>

Create a buffer of the given size (uninitialized, so it may contain random data).

Note that the result is either Uin8Array or Buffer, depending on the environment. Buffer from NodeJS works slightly different than Uint8Array.

uint8ArrayToUtf8 [source]
(buffer: Uint8Array<ArrayBufferLike>) => any
base64ToUint8Array [source]
(v: string) => Uint8Array<ArrayBufferLike>

Converts a base64 string to a Uint8Array.

isPlainObject [source]
(obj: any): obj is object

Returns true if the given obj is a plain object, and no class instance.

isPlainObject({}) === true isPlainObject(new ClassXY) === false

isClassInstance [source]
(target: any): boolean

Returns true when target is a class instance.

isFunction [source]
(obj: any): obj is Function

Returns true if given obj is a function.

isAsyncFunction [source]
(obj: any): obj is (...args: any[]) => Promise<any>

Returns true if given obj is a async function.

isPromise [source]
<T>(obj: any | Promise<T>): obj is Promise<T>

Returns true if given obj is a promise like object.

Note: There's no way to check if it's actually a Promise using instanceof since there are a lot of different implementations around.

isClass [source]
(obj: any): obj is AbstractClassType

Returns true if given obj is a ES6 class (ES5 fake classes are not supported).

isGlobalClass [source]
(obj: any): obj is AbstractClassType
isObject [source]
(obj: any): obj is { [key: string]: any; }

Returns true for real objects: object literals ({}) or class instances (new MyClass).

isObjectLiteral [source]
(obj: any): obj is { [key: string]: any; }

Returns true if given obj is a plain object, and no Date, Array, Map, Set, etc.

This is different to isObject and used in the type system to differentiate between JS objects in general and what we define as ReflectionKind.objectLiteral. Since we have Date, Set, Map, etc. in the type system, we need to differentiate between them and all other object literals.

isNull [source]
(obj: any): obj is null
isUndefined [source]
(obj: any): obj is undefined
isSet [source]
(obj: any): boolean

Checks if obj is not null and not undefined.

isNumber [source]
(obj: any): obj is number

Check if it is a real number (not NaN/Infinite).

isNumeric [source]
(s: string | number): boolean

Returns true if given value is strictly a numeric string value (or a number).

isNumeric(12); //true
isNumeric('12'); //true
isNumeric('12.3'); //true
isNumeric('12.3 '); //false
isNumeric('12px'); //false
isString [source]
(obj: any): obj is string
isConstructable [source]
(fn: any): boolean
isPrototypeOfBase [source]
(prototype: AbstractClassType | undefined, base: ClassType): boolean
isIterable [source]
(value: any): boolean
isArray [source]
(obj: any) => obj is any[]
isInteger [source]
(obj: any) => obj is number
pathNormalize [source]
(path: string): string

Normalizes the given path. Removes duplicate slashes, removes trailing slashes, adds a leading slash.

pathNormalizeDirectory [source]
(path: string): string

Same as pathNormalize, but ensures the path is a directory (always ends with a slash).

pathDirectory [source]
(path: string): string

Returns the directory (dirname) of the given path.

pathBasename [source]
(path: string): string

Returns the basename of the given path.

pathExtension [source]
(path: string): string

Returns the extension of the given path.

pathJoin [source]
(...paths: string[]): string

Types

ClassType [source]
interface ClassType<T = any> {
    new(...args: any[]): T;
}
AbstractClassType [source]
type AbstractClassType<T = any> = abstract new (...args: any[]) => T;
ExtractClassType [source]
type ExtractClassType<T> = T extends AbstractClassType<infer K> ? K : never;
AsyncEventSubscription [source]
type AsyncEventSubscription = { unsubscribe: () => void };
EventSubscription [source]
type EventSubscription = { unsubscribe: () => void };
TypeAnnotation [source]
type TypeAnnotation<T extends string, Options = never> = unknown;

Type to use for custom type annotations.

Adds runtime meta information to a type without influencing the type itself. This is like an intrinsic type, but only for runtime.

import { TypeAnnotation } from '@deepkit/core';
import { typeAnnotation } from '@deepkit/type';

type PrimaryKey = TypeAnnotation<'primaryKey'>;
type UserId = string & PrimaryKey;

const type = typeOf<UserId>();
const metaData = typeAnnotation.getType(type, 'primaryKey');

Runtime type is { __meta?: never & [T, Options] };

InjectMeta [source]
type InjectMeta<T = never> = TypeAnnotation<'inject', T>;
Inject [source]
type Inject<Type, Token = never> = Type & InjectMeta<Token>;