1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-23 23:49:46 -05:00
denoland-deno/cli/js/util.ts

96 lines
2.5 KiB
TypeScript
Raw Normal View History

2020-01-02 15:13:47 -05:00
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
let logDebug = false;
let logSource = "JS";
// @internal
export function setLogDebug(debug: boolean, source?: string): void {
logDebug = debug;
if (source) {
logSource = source;
}
}
2018-10-15 07:29:50 +11:00
/** Debug logging for deno.
2018-09-14 16:48:12 +08:00
* Enable with the `--log-debug` or `-D` command line flag.
* @internal
*/
export function log(...args: unknown[]): void {
if (logDebug) {
// if we destructure `console` off `globalThis` too early, we don't bind to
// the right console, therefore we don't log anything out.
globalThis.console.log(`DEBUG ${logSource} -`, ...args);
}
}
// @internal
export function assert(cond: unknown, msg = "assert"): asserts cond {
if (!cond) {
2018-07-16 23:25:50 -04:00
throw Error(msg);
}
}
2018-10-15 07:29:50 +11:00
/** A `Resolvable` is a Promise with the `reject` and `resolve` functions
* placed as methods on the promise object itself. It allows you to do:
*
2018-10-15 07:29:50 +11:00
* const p = createResolvable<number>();
* // ...
* p.resolve(42);
*
2018-10-15 07:29:50 +11:00
* It'd be prettier to make `Resolvable` a class that inherits from `Promise`,
* rather than an interface. This is possible in ES2016, however typescript
* produces broken code when targeting ES5 code.
*
2018-10-15 07:29:50 +11:00
* At the time of writing, the GitHub issue is closed in favour of a proposed
* solution that is awaiting feedback.
*
* @see https://github.com/Microsoft/TypeScript/issues/15202
* @see https://github.com/Microsoft/TypeScript/issues/15397
* @internal
*/
export type ResolveFunction<T> = (value?: T | PromiseLike<T>) => void;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type RejectFunction = (reason?: any) => void;
2018-08-15 09:40:30 -07:00
export interface ResolvableMethods<T> {
resolve: ResolveFunction<T>;
reject: RejectFunction;
}
2018-08-15 09:40:30 -07:00
// @internal
export type Resolvable<T> = Promise<T> & ResolvableMethods<T>;
2018-08-15 09:40:30 -07:00
// @internal
export function createResolvable<T>(): Resolvable<T> {
let resolve: ResolveFunction<T>;
let reject: RejectFunction;
const promise = new Promise<T>((res, rej): void => {
resolve = res;
reject = rej;
}) as Resolvable<T>;
promise.resolve = resolve!;
promise.reject = reject!;
return promise;
}
// @internal
export function notImplemented(): never {
throw new Error("Not implemented");
}
// @internal
export function immutableDefine(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
o: any,
p: string | number | symbol,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: any
): void {
Object.defineProperty(o, p, {
value,
configurable: false,
writable: false
});
}