@naturalcycles/js-lib 14.104.2 → 14.106.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,55 @@
1
+ import { NumberEnum, StringEnum } from './types';
2
+ /**
3
+ * Returns all number keys of a number-enum.
4
+ */
5
+ export declare function _numberEnumKeys(en: NumberEnum): string[];
6
+ /**
7
+ * Returns all number values of a number-enum.
8
+ */
9
+ export declare function _numberEnumValues(en: NumberEnum): number[];
10
+ /**
11
+ * Returns all string keys of a string-enum.
12
+ */
13
+ export declare function _stringEnumKeys(en: StringEnum): string[];
14
+ /**
15
+ * Returns all string values of a string-enum.
16
+ */
17
+ export declare function _stringEnumValues(en: StringEnum): string[];
18
+ /**
19
+ * Returns all number-enum "entries", where entry is a tuple of [key, value],
20
+ * where key is a String key, value is a Number value, typed as Enum itself.
21
+ *
22
+ * Doesn't work on String-enums!
23
+ */
24
+ export declare function _numberEnumEntries<T extends NumberEnum>(en: T): [k: string, v: T[keyof T]][];
25
+ /**
26
+ * Returns all string-enum "entries", where entry is a tuple of [key, value],
27
+ * where key is a String key, value is a String value, typed as Enum itself.
28
+ *
29
+ * Doesn't work on Number-enums!
30
+ */
31
+ export declare function _stringEnumEntries<T extends StringEnum>(en: T): [k: string, v: T[keyof T]][];
32
+ /**
33
+ * Allows to return a Number enum value (typed as Enum itself) based on it's String key.
34
+ * e.g:
35
+ * const v = SomeEnum['stringValue']
36
+ * // v is of type SomeEnum, which is of type Number
37
+ *
38
+ * Throws if value is not found!
39
+ */
40
+ export declare function _numberEnumInverse<T extends NumberEnum>(en: T, v: string): T[keyof T];
41
+ /**
42
+ * _enumInverse, but allows to get/return undefined output.
43
+ */
44
+ export declare function _numberEnumInverseNullable<T extends NumberEnum>(en: T, v: string | undefined): T[keyof T] | undefined;
45
+ /**
46
+ * Takes number or string enum input, returns normalized Enum output.
47
+ * Only works for number enums.
48
+ *
49
+ * Throws if value is not found!
50
+ */
51
+ export declare function _numberEnumNormalize<T extends NumberEnum>(en: T, v: string | number): T[keyof T];
52
+ /**
53
+ * Same as _enumNormalize, but allows to return undefined values.
54
+ */
55
+ export declare function _numberEnumNormalizeNullable<T extends NumberEnum>(en: T, v: string | number | undefined): T[keyof T] | undefined;
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports._numberEnumNormalizeNullable = exports._numberEnumNormalize = exports._numberEnumInverseNullable = exports._numberEnumInverse = exports._stringEnumEntries = exports._numberEnumEntries = exports._stringEnumValues = exports._stringEnumKeys = exports._numberEnumValues = exports._numberEnumKeys = void 0;
4
+ /**
5
+ * Returns all number keys of a number-enum.
6
+ */
7
+ function _numberEnumKeys(en) {
8
+ return Object.values(en).filter(k => typeof k === 'string');
9
+ }
10
+ exports._numberEnumKeys = _numberEnumKeys;
11
+ /**
12
+ * Returns all number values of a number-enum.
13
+ */
14
+ function _numberEnumValues(en) {
15
+ return Object.values(en).filter(k => typeof k === 'number');
16
+ }
17
+ exports._numberEnumValues = _numberEnumValues;
18
+ /**
19
+ * Returns all string keys of a string-enum.
20
+ */
21
+ function _stringEnumKeys(en) {
22
+ return Object.keys(en);
23
+ }
24
+ exports._stringEnumKeys = _stringEnumKeys;
25
+ /**
26
+ * Returns all string values of a string-enum.
27
+ */
28
+ function _stringEnumValues(en) {
29
+ // filtering here is unnecessary, but works as a safety in case Number-enum is passed
30
+ return Object.values(en).filter(k => typeof k === 'string');
31
+ }
32
+ exports._stringEnumValues = _stringEnumValues;
33
+ /**
34
+ * Returns all number-enum "entries", where entry is a tuple of [key, value],
35
+ * where key is a String key, value is a Number value, typed as Enum itself.
36
+ *
37
+ * Doesn't work on String-enums!
38
+ */
39
+ function _numberEnumEntries(en) {
40
+ return Object.values(en)
41
+ .filter(k => typeof k === 'string')
42
+ .map(k => [k, en[k]]);
43
+ }
44
+ exports._numberEnumEntries = _numberEnumEntries;
45
+ /**
46
+ * Returns all string-enum "entries", where entry is a tuple of [key, value],
47
+ * where key is a String key, value is a String value, typed as Enum itself.
48
+ *
49
+ * Doesn't work on Number-enums!
50
+ */
51
+ function _stringEnumEntries(en) {
52
+ return Object.keys(en).map(k => [k, en[k]]);
53
+ }
54
+ exports._stringEnumEntries = _stringEnumEntries;
55
+ /**
56
+ * Allows to return a Number enum value (typed as Enum itself) based on it's String key.
57
+ * e.g:
58
+ * const v = SomeEnum['stringValue']
59
+ * // v is of type SomeEnum, which is of type Number
60
+ *
61
+ * Throws if value is not found!
62
+ */
63
+ function _numberEnumInverse(en, v) {
64
+ const r = en[v];
65
+ if (!r)
66
+ throw new Error(`enumInverse value not found for: ${v}`);
67
+ return r;
68
+ }
69
+ exports._numberEnumInverse = _numberEnumInverse;
70
+ /**
71
+ * _enumInverse, but allows to get/return undefined output.
72
+ */
73
+ function _numberEnumInverseNullable(en, v) {
74
+ return en[v];
75
+ }
76
+ exports._numberEnumInverseNullable = _numberEnumInverseNullable;
77
+ /**
78
+ * Takes number or string enum input, returns normalized Enum output.
79
+ * Only works for number enums.
80
+ *
81
+ * Throws if value is not found!
82
+ */
83
+ function _numberEnumNormalize(en, v) {
84
+ const r = _numberEnumNormalizeNullable(en, v);
85
+ if (!r || !en[r])
86
+ throw new Error(`enumNormalize value not found for: ${v}`);
87
+ return r;
88
+ }
89
+ exports._numberEnumNormalize = _numberEnumNormalize;
90
+ /**
91
+ * Same as _enumNormalize, but allows to return undefined values.
92
+ */
93
+ function _numberEnumNormalizeNullable(en, v) {
94
+ return typeof v === 'string' ? en[v] : v;
95
+ }
96
+ exports._numberEnumNormalizeNullable = _numberEnumNormalizeNullable;
package/dist/index.d.ts CHANGED
@@ -16,6 +16,7 @@ export * from './decorators/retry.decorator';
16
16
  export * from './decorators/timeout.decorator';
17
17
  export * from './error/app.error';
18
18
  export * from './error/assert';
19
+ export * from './enum.util';
19
20
  import { Admin401ErrorData, Admin403ErrorData, ErrorData, ErrorObject, HttpErrorData, HttpErrorResponse } from './error/error.model';
20
21
  export * from './error/error.util';
21
22
  import { ErrorMode } from './error/errorMode';
@@ -52,12 +53,15 @@ import { JsonStringifyFunction, StringifyAnyOptions, _stringifyAny } from './str
52
53
  export * from './time/time.util';
53
54
  export * from './is.util';
54
55
  import { Class, ConditionalExcept, ConditionalPick, Merge, Promisable, ReadonlyDeep, Simplify } from './typeFest';
55
- import { AsyncMapper, AsyncPredicate, BaseDBEntity, CreatedUpdated, CreatedUpdatedId, ObjectWithId, AnyObjectWithId, Saved, Unsaved, UnsavedId, BatchResult, InstanceId, IsoDate, IsoDateString, IsoDateTimeString, KeyValueTuple, Mapper, ObjectMapper, ObjectPredicate, Predicate, PromiseMap, AnyObject, AnyFunction, Reviver, SavedDBEntity, StringMap, UnixTimestampNumber, UnixTimestampMillisNumber, UnixTimestamp, Integer, ValueOf, ValuesOf, AbortableMapper, AbortableAsyncPredicate, AbortableAsyncMapper, AbortablePredicate, NullishValue, FalsyValue, END, SKIP, _noop, _objectKeys, _passNothingPredicate, _passthroughMapper, _passthroughPredicate, _passUndefinedMapper, _stringMapEntries, _stringMapValues } from './types';
56
+ import { AsyncMapper, AsyncPredicate, BaseDBEntity, CreatedUpdated, CreatedUpdatedId, ObjectWithId, AnyObjectWithId, Saved, Unsaved, UnsavedId, BatchResult, InstanceId, IsoDate, IsoDateString, IsoDateTimeString, KeyValueTuple, Mapper, ObjectMapper, ObjectPredicate, Predicate, PromiseMap, AnyObject, AnyEnum, NumberEnum, StringEnum, AnyFunction, Reviver, SavedDBEntity, StringMap, UnixTimestampNumber, UnixTimestampMillisNumber, UnixTimestamp, Integer, ValueOf, ValuesOf, AbortableMapper, AbortableAsyncPredicate, AbortableAsyncMapper, AbortablePredicate, NullishValue, FalsyValue } from './types';
57
+ export * from './types';
56
58
  export * from './unit/size.util';
57
59
  import { is } from './vendor/is';
58
- import { CommonLogLevel, CommonLogFunction, CommonLogger, commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, CommonLogWithLevelFunction, commonLoggerCreate } from './log/commonLogger';
60
+ import { CommonLogLevel, CommonLogFunction, CommonLogger, CommonLogWithLevelFunction } from './log/commonLogger';
61
+ export * from './log/commonLogger';
59
62
  export * from './string/safeJsonStringify';
60
- import { PQueue, PQueueCfg } from './promise/pQueue';
63
+ import { PQueueCfg } from './promise/pQueue';
64
+ export * from './promise/pQueue';
61
65
  export * from './seq/seq';
62
66
  export * from './math/stack.util';
63
67
  export * from './string/leven';
@@ -69,5 +73,5 @@ import { LocalDateConfig, LocalDateFormatter, LocalDateUnit, LocalDateUnitStrict
69
73
  import { LocalTimeConfig, LocalTimeFormatter, LocalTimeUnit, LocalTimeComponents, ISODayOfWeek } from './datetime/localTime';
70
74
  import { DateIntervalConfig, DateIntervalString } from './datetime/dateInterval';
71
75
  import { TimeIntervalConfig, TimeIntervalString } from './datetime/timeInterval';
72
- export type { DateIntervalConfig, DateIntervalString, TimeIntervalConfig, TimeIntervalString, LocalDateConfig, LocalDateFormatter, LocalDateUnit, LocalDateUnitStrict, Inclusiveness, LocalTimeConfig, LocalTimeFormatter, LocalTimeUnit, ISODayOfWeek, LocalTimeComponents, AbortableMapper, AbortablePredicate, AbortableAsyncPredicate, AbortableAsyncMapper, PQueueCfg, MemoCache, AsyncMemoCache, PromiseDecoratorCfg, PromiseDecoratorResp, ErrorData, ErrorObject, HttpErrorData, HttpErrorResponse, Admin401ErrorData, Admin403ErrorData, StringMap, PromiseMap, AnyObject, AnyFunction, ValuesOf, ValueOf, KeyValueTuple, ObjectMapper, ObjectPredicate, InstanceId, IsoDate, IsoDateString, IsoDateTimeString, Reviver, FalsyValue, NullishValue, PMapOptions, Mapper, AsyncMapper, Predicate, AsyncPredicate, BatchResult, DeferredPromise, PRetryOptions, PTimeoutOptions, TryCatchOptions, StringifyAnyOptions, JsonStringifyFunction, Merge, ReadonlyDeep, Promisable, Simplify, ConditionalPick, ConditionalExcept, Class, UnixTimestampNumber, UnixTimestampMillisNumber, UnixTimestamp, Integer, BaseDBEntity, SavedDBEntity, Saved, Unsaved, UnsavedId, CreatedUpdated, CreatedUpdatedId, ObjectWithId, AnyObjectWithId, JsonSchema, JsonSchemaAny, JsonSchemaOneOf, JsonSchemaAllOf, JsonSchemaAnyOf, JsonSchemaNot, JsonSchemaRef, JsonSchemaConst, JsonSchemaEnum, JsonSchemaString, JsonSchemaNumber, JsonSchemaBoolean, JsonSchemaNull, JsonSchemaRootObject, JsonSchemaObject, JsonSchemaArray, JsonSchemaTuple, JsonSchemaBuilder, CommonLogLevel, CommonLogWithLevelFunction, CommonLogFunction, CommonLogger, };
73
- export { is, _createPromiseDecorator, _stringMapValues, _stringMapEntries, _objectKeys, pMap, _passthroughMapper, _passUndefinedMapper, _passthroughPredicate, _passNothingPredicate, _noop, ErrorMode, pDefer, AggregatedError, pRetry, pRetryFn, pTimeout, pTimeoutFn, _tryCatch, _TryCatch, _stringifyAny, jsonSchema, JsonSchemaAnyBuilder, commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, commonLoggerCreate, PQueue, END, SKIP, };
76
+ export type { DateIntervalConfig, DateIntervalString, TimeIntervalConfig, TimeIntervalString, LocalDateConfig, LocalDateFormatter, LocalDateUnit, LocalDateUnitStrict, Inclusiveness, LocalTimeConfig, LocalTimeFormatter, LocalTimeUnit, ISODayOfWeek, LocalTimeComponents, AbortableMapper, AbortablePredicate, AbortableAsyncPredicate, AbortableAsyncMapper, PQueueCfg, MemoCache, AsyncMemoCache, PromiseDecoratorCfg, PromiseDecoratorResp, ErrorData, ErrorObject, HttpErrorData, HttpErrorResponse, Admin401ErrorData, Admin403ErrorData, StringMap, PromiseMap, AnyObject, AnyEnum, NumberEnum, StringEnum, AnyFunction, ValuesOf, ValueOf, KeyValueTuple, ObjectMapper, ObjectPredicate, InstanceId, IsoDate, IsoDateString, IsoDateTimeString, Reviver, FalsyValue, NullishValue, PMapOptions, Mapper, AsyncMapper, Predicate, AsyncPredicate, BatchResult, DeferredPromise, PRetryOptions, PTimeoutOptions, TryCatchOptions, StringifyAnyOptions, JsonStringifyFunction, Merge, ReadonlyDeep, Promisable, Simplify, ConditionalPick, ConditionalExcept, Class, UnixTimestampNumber, UnixTimestampMillisNumber, UnixTimestamp, Integer, BaseDBEntity, SavedDBEntity, Saved, Unsaved, UnsavedId, CreatedUpdated, CreatedUpdatedId, ObjectWithId, AnyObjectWithId, JsonSchema, JsonSchemaAny, JsonSchemaOneOf, JsonSchemaAllOf, JsonSchemaAnyOf, JsonSchemaNot, JsonSchemaRef, JsonSchemaConst, JsonSchemaEnum, JsonSchemaString, JsonSchemaNumber, JsonSchemaBoolean, JsonSchemaNull, JsonSchemaRootObject, JsonSchemaObject, JsonSchemaArray, JsonSchemaTuple, JsonSchemaBuilder, CommonLogLevel, CommonLogWithLevelFunction, CommonLogFunction, CommonLogger, };
77
+ export { is, _createPromiseDecorator, pMap, ErrorMode, pDefer, AggregatedError, pRetry, pRetryFn, pTimeout, pTimeoutFn, _tryCatch, _TryCatch, _stringifyAny, jsonSchema, JsonSchemaAnyBuilder, };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SKIP = exports.END = exports.PQueue = exports.commonLoggerCreate = exports.commonLoggerPrefix = exports.commonLoggerPipe = exports.commonLogLevelNumber = exports.commonLoggerNoop = exports.commonLoggerMinLevel = exports.JsonSchemaAnyBuilder = exports.jsonSchema = exports._stringifyAny = exports._TryCatch = exports._tryCatch = exports.pTimeoutFn = exports.pTimeout = exports.pRetryFn = exports.pRetry = exports.AggregatedError = exports.pDefer = exports.ErrorMode = exports._noop = exports._passNothingPredicate = exports._passthroughPredicate = exports._passUndefinedMapper = exports._passthroughMapper = exports.pMap = exports._objectKeys = exports._stringMapEntries = exports._stringMapValues = exports._createPromiseDecorator = exports.is = void 0;
3
+ exports.JsonSchemaAnyBuilder = exports.jsonSchema = exports._stringifyAny = exports._TryCatch = exports._tryCatch = exports.pTimeoutFn = exports.pTimeout = exports.pRetryFn = exports.pRetry = exports.AggregatedError = exports.pDefer = exports.ErrorMode = exports.pMap = exports._createPromiseDecorator = exports.is = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  tslib_1.__exportStar(require("./array/array.util"), exports);
6
6
  tslib_1.__exportStar(require("./lazy"), exports);
@@ -20,6 +20,7 @@ tslib_1.__exportStar(require("./decorators/retry.decorator"), exports);
20
20
  tslib_1.__exportStar(require("./decorators/timeout.decorator"), exports);
21
21
  tslib_1.__exportStar(require("./error/app.error"), exports);
22
22
  tslib_1.__exportStar(require("./error/assert"), exports);
23
+ tslib_1.__exportStar(require("./enum.util"), exports);
23
24
  tslib_1.__exportStar(require("./error/error.util"), exports);
24
25
  const errorMode_1 = require("./error/errorMode");
25
26
  Object.defineProperty(exports, "ErrorMode", { enumerable: true, get: function () { return errorMode_1.ErrorMode; } });
@@ -66,30 +67,13 @@ const stringifyAny_1 = require("./string/stringifyAny");
66
67
  Object.defineProperty(exports, "_stringifyAny", { enumerable: true, get: function () { return stringifyAny_1._stringifyAny; } });
67
68
  tslib_1.__exportStar(require("./time/time.util"), exports);
68
69
  tslib_1.__exportStar(require("./is.util"), exports);
69
- const types_1 = require("./types");
70
- Object.defineProperty(exports, "END", { enumerable: true, get: function () { return types_1.END; } });
71
- Object.defineProperty(exports, "SKIP", { enumerable: true, get: function () { return types_1.SKIP; } });
72
- Object.defineProperty(exports, "_noop", { enumerable: true, get: function () { return types_1._noop; } });
73
- Object.defineProperty(exports, "_objectKeys", { enumerable: true, get: function () { return types_1._objectKeys; } });
74
- Object.defineProperty(exports, "_passNothingPredicate", { enumerable: true, get: function () { return types_1._passNothingPredicate; } });
75
- Object.defineProperty(exports, "_passthroughMapper", { enumerable: true, get: function () { return types_1._passthroughMapper; } });
76
- Object.defineProperty(exports, "_passthroughPredicate", { enumerable: true, get: function () { return types_1._passthroughPredicate; } });
77
- Object.defineProperty(exports, "_passUndefinedMapper", { enumerable: true, get: function () { return types_1._passUndefinedMapper; } });
78
- Object.defineProperty(exports, "_stringMapEntries", { enumerable: true, get: function () { return types_1._stringMapEntries; } });
79
- Object.defineProperty(exports, "_stringMapValues", { enumerable: true, get: function () { return types_1._stringMapValues; } });
70
+ tslib_1.__exportStar(require("./types"), exports);
80
71
  tslib_1.__exportStar(require("./unit/size.util"), exports);
81
72
  const is_1 = require("./vendor/is");
82
73
  Object.defineProperty(exports, "is", { enumerable: true, get: function () { return is_1.is; } });
83
- const commonLogger_1 = require("./log/commonLogger");
84
- Object.defineProperty(exports, "commonLoggerMinLevel", { enumerable: true, get: function () { return commonLogger_1.commonLoggerMinLevel; } });
85
- Object.defineProperty(exports, "commonLoggerNoop", { enumerable: true, get: function () { return commonLogger_1.commonLoggerNoop; } });
86
- Object.defineProperty(exports, "commonLogLevelNumber", { enumerable: true, get: function () { return commonLogger_1.commonLogLevelNumber; } });
87
- Object.defineProperty(exports, "commonLoggerPipe", { enumerable: true, get: function () { return commonLogger_1.commonLoggerPipe; } });
88
- Object.defineProperty(exports, "commonLoggerPrefix", { enumerable: true, get: function () { return commonLogger_1.commonLoggerPrefix; } });
89
- Object.defineProperty(exports, "commonLoggerCreate", { enumerable: true, get: function () { return commonLogger_1.commonLoggerCreate; } });
74
+ tslib_1.__exportStar(require("./log/commonLogger"), exports);
90
75
  tslib_1.__exportStar(require("./string/safeJsonStringify"), exports);
91
- const pQueue_1 = require("./promise/pQueue");
92
- Object.defineProperty(exports, "PQueue", { enumerable: true, get: function () { return pQueue_1.PQueue; } });
76
+ tslib_1.__exportStar(require("./promise/pQueue"), exports);
93
77
  tslib_1.__exportStar(require("./seq/seq"), exports);
94
78
  tslib_1.__exportStar(require("./math/stack.util"), exports);
95
79
  tslib_1.__exportStar(require("./string/leven"), exports);
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.pDefer = void 0;
4
+ /* eslint-disable @typescript-eslint/promise-function-async */
4
5
  /**
5
6
  * Returns DeferredPromise - a Promise that has .resolve() and .reject() methods.
6
7
  */
@@ -2,6 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.pDelay = void 0;
4
4
  async function pDelay(ms = 0, value) {
5
- return new Promise(resolve => setTimeout(() => resolve(value), ms));
5
+ return await new Promise(resolve => setTimeout(() => resolve(value), ms));
6
6
  }
7
7
  exports.pDelay = pDelay;
@@ -5,6 +5,6 @@ exports.pHang = void 0;
5
5
  * Returns Promise that never resolves ("hanging").
6
6
  */
7
7
  async function pHang() {
8
- return new Promise(() => void 0);
8
+ return await new Promise(() => void 0);
9
9
  }
10
10
  exports.pHang = pHang;
@@ -94,7 +94,7 @@ async function pMap(iterable, mapper, opt = {}) {
94
94
  }
95
95
  return ret;
96
96
  }
97
- return new Promise((resolve, reject) => {
97
+ return await new Promise((resolve, reject) => {
98
98
  const next = () => {
99
99
  if (isSettled) {
100
100
  return;
@@ -39,18 +39,18 @@ class PQueue {
39
39
  * Resolves immediately in case the queue is Idle.
40
40
  * Idle means 0 queue and 0 inFlight.
41
41
  */
42
- onIdle() {
42
+ async onIdle() {
43
43
  if (this.queue.length === 0 && this.inFlight === 0)
44
- return Promise.resolve();
44
+ return;
45
45
  const listener = (0, pDefer_1.pDefer)();
46
46
  this.onIdleListeners.push(listener);
47
- return listener;
47
+ return await listener;
48
48
  }
49
49
  /**
50
50
  * Push PromiseReturningFunction to the Queue.
51
51
  * Returns a Promise that resolves (or rejects) with the return value from the Promise.
52
52
  */
53
- push(fn_) {
53
+ async push(fn_) {
54
54
  const { concurrency } = this.cfg;
55
55
  const resolveOnStart = this.cfg.resolveOn === 'start';
56
56
  const fn = fn_;
@@ -99,7 +99,7 @@ class PQueue {
99
99
  this.queue.push(fn);
100
100
  this.debug(`inFlight ${this.inFlight}/${concurrency}, queue++ ${this.queue.length}`);
101
101
  }
102
- return fn.defer;
102
+ return await fn.defer;
103
103
  }
104
104
  }
105
105
  exports.PQueue = PQueue;
@@ -11,7 +11,7 @@ const UNIQUE_VALUE = Symbol('unique');
11
11
  * Based on: https://makandracards.com/makandra/46681-javascript-how-to-query-the-state-of-a-native-promise
12
12
  */
13
13
  async function pState(p) {
14
- return Promise.race([p, Promise.resolve(UNIQUE_VALUE)]).then(v => {
14
+ return await Promise.race([p, Promise.resolve(UNIQUE_VALUE)]).then(v => {
15
15
  return v === UNIQUE_VALUE ? 'pending' : 'resolved';
16
16
  }, () => 'rejected');
17
17
  }
package/dist/types.d.ts CHANGED
@@ -20,6 +20,9 @@ export interface PromiseMap {
20
20
  * Because `object` type is not safe/recommended to be used (e.g discouraged by eslint-typescript due to: https://github.com/microsoft/TypeScript/issues/21732)
21
21
  */
22
22
  export declare type AnyObject = Record<string, any>;
23
+ export declare type AnyEnum = NumberEnum;
24
+ export declare type NumberEnum = Record<string, number | string>;
25
+ export declare type StringEnum = Record<string, string>;
23
26
  export interface CreatedUpdated {
24
27
  created: number;
25
28
  updated: number;
@@ -191,3 +194,15 @@ export declare function _stringMapEntries<T>(m: StringMap<T>): [k: string, v: T]
191
194
  export declare function _objectKeys<T extends AnyObject>(obj: T): (keyof T)[];
192
195
  export declare type NullishValue = null | undefined;
193
196
  export declare type FalsyValue = false | '' | 0 | null | undefined;
197
+ /**
198
+ * Utility function that helps to cast *existing variable* to needed type T.
199
+ *
200
+ * @example
201
+ * try {} catch (err) {
202
+ * // err is unknown here
203
+ * _typeCast<AppError>(err)
204
+ * // now err is of type AppError
205
+ * err.data = {} // can be done, because it was casted
206
+ * }
207
+ */
208
+ export declare function _typeCast<T>(v: any): asserts v is T;
package/dist/types.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports._objectKeys = exports._stringMapEntries = exports._stringMapValues = exports._passNothingPredicate = exports._passthroughPredicate = exports._noop = exports._passUndefinedMapper = exports._passthroughMapper = exports.SKIP = exports.END = void 0;
3
+ exports._typeCast = exports._objectKeys = exports._stringMapEntries = exports._stringMapValues = exports._passNothingPredicate = exports._passthroughPredicate = exports._noop = exports._passUndefinedMapper = exports._passthroughMapper = exports.SKIP = exports.END = void 0;
4
4
  /**
5
5
  * Symbol to indicate END of Sequence.
6
6
  */
@@ -48,3 +48,16 @@ function _objectKeys(obj) {
48
48
  return Object.keys(obj);
49
49
  }
50
50
  exports._objectKeys = _objectKeys;
51
+ /**
52
+ * Utility function that helps to cast *existing variable* to needed type T.
53
+ *
54
+ * @example
55
+ * try {} catch (err) {
56
+ * // err is unknown here
57
+ * _typeCast<AppError>(err)
58
+ * // now err is of type AppError
59
+ * err.data = {} // can be done, because it was casted
60
+ * }
61
+ */
62
+ function _typeCast(v) { }
63
+ exports._typeCast = _typeCast;
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Returns all number keys of a number-enum.
3
+ */
4
+ export function _numberEnumKeys(en) {
5
+ return Object.values(en).filter(k => typeof k === 'string');
6
+ }
7
+ /**
8
+ * Returns all number values of a number-enum.
9
+ */
10
+ export function _numberEnumValues(en) {
11
+ return Object.values(en).filter(k => typeof k === 'number');
12
+ }
13
+ /**
14
+ * Returns all string keys of a string-enum.
15
+ */
16
+ export function _stringEnumKeys(en) {
17
+ return Object.keys(en);
18
+ }
19
+ /**
20
+ * Returns all string values of a string-enum.
21
+ */
22
+ export function _stringEnumValues(en) {
23
+ // filtering here is unnecessary, but works as a safety in case Number-enum is passed
24
+ return Object.values(en).filter(k => typeof k === 'string');
25
+ }
26
+ /**
27
+ * Returns all number-enum "entries", where entry is a tuple of [key, value],
28
+ * where key is a String key, value is a Number value, typed as Enum itself.
29
+ *
30
+ * Doesn't work on String-enums!
31
+ */
32
+ export function _numberEnumEntries(en) {
33
+ return Object.values(en)
34
+ .filter(k => typeof k === 'string')
35
+ .map(k => [k, en[k]]);
36
+ }
37
+ /**
38
+ * Returns all string-enum "entries", where entry is a tuple of [key, value],
39
+ * where key is a String key, value is a String value, typed as Enum itself.
40
+ *
41
+ * Doesn't work on Number-enums!
42
+ */
43
+ export function _stringEnumEntries(en) {
44
+ return Object.keys(en).map(k => [k, en[k]]);
45
+ }
46
+ /**
47
+ * Allows to return a Number enum value (typed as Enum itself) based on it's String key.
48
+ * e.g:
49
+ * const v = SomeEnum['stringValue']
50
+ * // v is of type SomeEnum, which is of type Number
51
+ *
52
+ * Throws if value is not found!
53
+ */
54
+ export function _numberEnumInverse(en, v) {
55
+ const r = en[v];
56
+ if (!r)
57
+ throw new Error(`enumInverse value not found for: ${v}`);
58
+ return r;
59
+ }
60
+ /**
61
+ * _enumInverse, but allows to get/return undefined output.
62
+ */
63
+ export function _numberEnumInverseNullable(en, v) {
64
+ return en[v];
65
+ }
66
+ /**
67
+ * Takes number or string enum input, returns normalized Enum output.
68
+ * Only works for number enums.
69
+ *
70
+ * Throws if value is not found!
71
+ */
72
+ export function _numberEnumNormalize(en, v) {
73
+ const r = _numberEnumNormalizeNullable(en, v);
74
+ if (!r || !en[r])
75
+ throw new Error(`enumNormalize value not found for: ${v}`);
76
+ return r;
77
+ }
78
+ /**
79
+ * Same as _enumNormalize, but allows to return undefined values.
80
+ */
81
+ export function _numberEnumNormalizeNullable(en, v) {
82
+ return typeof v === 'string' ? en[v] : v;
83
+ }
package/dist-esm/index.js CHANGED
@@ -15,6 +15,7 @@ export * from './decorators/retry.decorator';
15
15
  export * from './decorators/timeout.decorator';
16
16
  export * from './error/app.error';
17
17
  export * from './error/assert';
18
+ export * from './enum.util';
18
19
  export * from './error/error.util';
19
20
  import { ErrorMode } from './error/errorMode';
20
21
  export * from './error/http.error';
@@ -48,12 +49,12 @@ export * from './string/string.util';
48
49
  import { _stringifyAny } from './string/stringifyAny';
49
50
  export * from './time/time.util';
50
51
  export * from './is.util';
51
- import { END, SKIP, _noop, _objectKeys, _passNothingPredicate, _passthroughMapper, _passthroughPredicate, _passUndefinedMapper, _stringMapEntries, _stringMapValues, } from './types';
52
+ export * from './types';
52
53
  export * from './unit/size.util';
53
54
  import { is } from './vendor/is';
54
- import { commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, commonLoggerCreate, } from './log/commonLogger';
55
+ export * from './log/commonLogger';
55
56
  export * from './string/safeJsonStringify';
56
- import { PQueue } from './promise/pQueue';
57
+ export * from './promise/pQueue';
57
58
  export * from './seq/seq';
58
59
  export * from './math/stack.util';
59
60
  export * from './string/leven';
@@ -62,4 +63,4 @@ export * from './datetime/localTime';
62
63
  export * from './datetime/dateInterval';
63
64
  export * from './datetime/timeInterval';
64
65
  import { ISODayOfWeek, } from './datetime/localTime';
65
- export { is, _createPromiseDecorator, _stringMapValues, _stringMapEntries, _objectKeys, pMap, _passthroughMapper, _passUndefinedMapper, _passthroughPredicate, _passNothingPredicate, _noop, ErrorMode, pDefer, AggregatedError, pRetry, pRetryFn, pTimeout, pTimeoutFn, _tryCatch, _TryCatch, _stringifyAny, jsonSchema, JsonSchemaAnyBuilder, commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, commonLoggerCreate, PQueue, END, SKIP, };
66
+ export { is, _createPromiseDecorator, pMap, ErrorMode, pDefer, AggregatedError, pRetry, pRetryFn, pTimeout, pTimeoutFn, _tryCatch, _TryCatch, _stringifyAny, jsonSchema, JsonSchemaAnyBuilder, };
@@ -1,3 +1,4 @@
1
+ /* eslint-disable @typescript-eslint/promise-function-async */
1
2
  /**
2
3
  * Returns DeferredPromise - a Promise that has .resolve() and .reject() methods.
3
4
  */
@@ -1,3 +1,3 @@
1
1
  export async function pDelay(ms = 0, value) {
2
- return new Promise(resolve => setTimeout(() => resolve(value), ms));
2
+ return await new Promise(resolve => setTimeout(() => resolve(value), ms));
3
3
  }
@@ -2,5 +2,5 @@
2
2
  * Returns Promise that never resolves ("hanging").
3
3
  */
4
4
  export async function pHang() {
5
- return new Promise(() => void 0);
5
+ return await new Promise(() => void 0);
6
6
  }
@@ -103,7 +103,7 @@ export async function pMap(iterable, mapper, opt = {}) {
103
103
  }
104
104
  return ret;
105
105
  }
106
- return new Promise((resolve, reject) => {
106
+ return await new Promise((resolve, reject) => {
107
107
  const next = () => {
108
108
  if (isSettled) {
109
109
  return;
@@ -31,18 +31,18 @@ export class PQueue {
31
31
  * Resolves immediately in case the queue is Idle.
32
32
  * Idle means 0 queue and 0 inFlight.
33
33
  */
34
- onIdle() {
34
+ async onIdle() {
35
35
  if (this.queue.length === 0 && this.inFlight === 0)
36
- return Promise.resolve();
36
+ return;
37
37
  const listener = pDefer();
38
38
  this.onIdleListeners.push(listener);
39
- return listener;
39
+ return await listener;
40
40
  }
41
41
  /**
42
42
  * Push PromiseReturningFunction to the Queue.
43
43
  * Returns a Promise that resolves (or rejects) with the return value from the Promise.
44
44
  */
45
- push(fn_) {
45
+ async push(fn_) {
46
46
  const { concurrency } = this.cfg;
47
47
  const resolveOnStart = this.cfg.resolveOn === 'start';
48
48
  const fn = fn_;
@@ -91,6 +91,6 @@ export class PQueue {
91
91
  this.queue.push(fn);
92
92
  this.debug(`inFlight ${this.inFlight}/${concurrency}, queue++ ${this.queue.length}`);
93
93
  }
94
- return fn.defer;
94
+ return await fn.defer;
95
95
  }
96
96
  }
@@ -8,7 +8,7 @@ const UNIQUE_VALUE = Symbol('unique');
8
8
  * Based on: https://makandracards.com/makandra/46681-javascript-how-to-query-the-state-of-a-native-promise
9
9
  */
10
10
  export async function pState(p) {
11
- return Promise.race([p, Promise.resolve(UNIQUE_VALUE)]).then(v => {
11
+ return await Promise.race([p, Promise.resolve(UNIQUE_VALUE)]).then(v => {
12
12
  return v === UNIQUE_VALUE ? 'pending' : 'resolved';
13
13
  }, () => 'rejected');
14
14
  }
package/dist-esm/types.js CHANGED
@@ -37,3 +37,15 @@ export function _stringMapEntries(m) {
37
37
  export function _objectKeys(obj) {
38
38
  return Object.keys(obj);
39
39
  }
40
+ /**
41
+ * Utility function that helps to cast *existing variable* to needed type T.
42
+ *
43
+ * @example
44
+ * try {} catch (err) {
45
+ * // err is unknown here
46
+ * _typeCast<AppError>(err)
47
+ * // now err is of type AppError
48
+ * err.data = {} // can be done, because it was casted
49
+ * }
50
+ */
51
+ export function _typeCast(v) { }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@naturalcycles/js-lib",
3
- "version": "14.104.2",
3
+ "version": "14.106.0",
4
4
  "scripts": {
5
5
  "prepare": "husky install",
6
6
  "build-prod": "build-prod-esm-cjs",
@@ -12,10 +12,11 @@
12
12
  },
13
13
  "devDependencies": {
14
14
  "@naturalcycles/bench-lib": "^1.5.0",
15
- "@naturalcycles/dev-lib": "^12.0.0",
15
+ "@naturalcycles/dev-lib": "^13.0.1",
16
16
  "@naturalcycles/nodejs-lib": "^12.33.4",
17
17
  "@naturalcycles/time-lib": "^3.5.1",
18
- "@types/node": "^17.0.4",
18
+ "@types/node": "^18.0.0",
19
+ "expect-type": "^0.13.0",
19
20
  "jest": "^28.0.3",
20
21
  "patch-package": "^6.2.1",
21
22
  "prettier": "^2.1.2",
@@ -0,0 +1,98 @@
1
+ import { NumberEnum, StringEnum } from './types'
2
+
3
+ /**
4
+ * Returns all number keys of a number-enum.
5
+ */
6
+ export function _numberEnumKeys(en: NumberEnum): string[] {
7
+ return Object.values(en).filter(k => typeof k === 'string') as string[]
8
+ }
9
+
10
+ /**
11
+ * Returns all number values of a number-enum.
12
+ */
13
+ export function _numberEnumValues(en: NumberEnum): number[] {
14
+ return Object.values(en).filter(k => typeof k === 'number') as number[]
15
+ }
16
+
17
+ /**
18
+ * Returns all string keys of a string-enum.
19
+ */
20
+ export function _stringEnumKeys(en: StringEnum): string[] {
21
+ return Object.keys(en)
22
+ }
23
+
24
+ /**
25
+ * Returns all string values of a string-enum.
26
+ */
27
+ export function _stringEnumValues(en: StringEnum): string[] {
28
+ // filtering here is unnecessary, but works as a safety in case Number-enum is passed
29
+ return Object.values(en).filter(k => typeof k === 'string')
30
+ }
31
+
32
+ /**
33
+ * Returns all number-enum "entries", where entry is a tuple of [key, value],
34
+ * where key is a String key, value is a Number value, typed as Enum itself.
35
+ *
36
+ * Doesn't work on String-enums!
37
+ */
38
+ export function _numberEnumEntries<T extends NumberEnum>(en: T): [k: string, v: T[keyof T]][] {
39
+ return Object.values(en)
40
+ .filter(k => typeof k === 'string')
41
+ .map(k => [k, en[k]]) as any
42
+ }
43
+
44
+ /**
45
+ * Returns all string-enum "entries", where entry is a tuple of [key, value],
46
+ * where key is a String key, value is a String value, typed as Enum itself.
47
+ *
48
+ * Doesn't work on Number-enums!
49
+ */
50
+ export function _stringEnumEntries<T extends StringEnum>(en: T): [k: string, v: T[keyof T]][] {
51
+ return Object.keys(en).map(k => [k, en[k]]) as any
52
+ }
53
+
54
+ /**
55
+ * Allows to return a Number enum value (typed as Enum itself) based on it's String key.
56
+ * e.g:
57
+ * const v = SomeEnum['stringValue']
58
+ * // v is of type SomeEnum, which is of type Number
59
+ *
60
+ * Throws if value is not found!
61
+ */
62
+ export function _numberEnumInverse<T extends NumberEnum>(en: T, v: string): T[keyof T] {
63
+ const r = en[v as keyof T] as any
64
+ if (!r) throw new Error(`enumInverse value not found for: ${v}`)
65
+ return r
66
+ }
67
+
68
+ /**
69
+ * _enumInverse, but allows to get/return undefined output.
70
+ */
71
+ export function _numberEnumInverseNullable<T extends NumberEnum>(
72
+ en: T,
73
+ v: string | undefined,
74
+ ): T[keyof T] | undefined {
75
+ return en[v as keyof T]
76
+ }
77
+
78
+ /**
79
+ * Takes number or string enum input, returns normalized Enum output.
80
+ * Only works for number enums.
81
+ *
82
+ * Throws if value is not found!
83
+ */
84
+ export function _numberEnumNormalize<T extends NumberEnum>(en: T, v: string | number): T[keyof T] {
85
+ const r = _numberEnumNormalizeNullable(en, v)
86
+ if (!r || !en[r as keyof T]) throw new Error(`enumNormalize value not found for: ${v}`)
87
+ return r
88
+ }
89
+
90
+ /**
91
+ * Same as _enumNormalize, but allows to return undefined values.
92
+ */
93
+ export function _numberEnumNormalizeNullable<T extends NumberEnum>(
94
+ en: T,
95
+ v: string | number | undefined,
96
+ ): T[keyof T] | undefined {
97
+ return typeof v === 'string' ? en[v as keyof T] : (v as any)
98
+ }
package/src/index.ts CHANGED
@@ -20,6 +20,7 @@ export * from './decorators/retry.decorator'
20
20
  export * from './decorators/timeout.decorator'
21
21
  export * from './error/app.error'
22
22
  export * from './error/assert'
23
+ export * from './enum.util'
23
24
  import {
24
25
  Admin401ErrorData,
25
26
  Admin403ErrorData,
@@ -117,6 +118,9 @@ import {
117
118
  Predicate,
118
119
  PromiseMap,
119
120
  AnyObject,
121
+ AnyEnum,
122
+ NumberEnum,
123
+ StringEnum,
120
124
  AnyFunction,
121
125
  Reviver,
122
126
  SavedDBEntity,
@@ -133,33 +137,20 @@ import {
133
137
  AbortablePredicate,
134
138
  NullishValue,
135
139
  FalsyValue,
136
- END,
137
- SKIP,
138
- _noop,
139
- _objectKeys,
140
- _passNothingPredicate,
141
- _passthroughMapper,
142
- _passthroughPredicate,
143
- _passUndefinedMapper,
144
- _stringMapEntries,
145
- _stringMapValues,
146
140
  } from './types'
141
+ export * from './types'
147
142
  export * from './unit/size.util'
148
143
  import { is } from './vendor/is'
149
144
  import {
150
145
  CommonLogLevel,
151
146
  CommonLogFunction,
152
147
  CommonLogger,
153
- commonLoggerMinLevel,
154
- commonLoggerNoop,
155
- commonLogLevelNumber,
156
- commonLoggerPipe,
157
- commonLoggerPrefix,
158
148
  CommonLogWithLevelFunction,
159
- commonLoggerCreate,
160
149
  } from './log/commonLogger'
150
+ export * from './log/commonLogger'
161
151
  export * from './string/safeJsonStringify'
162
- import { PQueue, PQueueCfg } from './promise/pQueue'
152
+ import { PQueueCfg } from './promise/pQueue'
153
+ export * from './promise/pQueue'
163
154
  export * from './seq/seq'
164
155
  export * from './math/stack.util'
165
156
  export * from './string/leven'
@@ -217,6 +208,9 @@ export type {
217
208
  StringMap,
218
209
  PromiseMap,
219
210
  AnyObject,
211
+ AnyEnum,
212
+ NumberEnum,
213
+ StringEnum,
220
214
  AnyFunction,
221
215
  ValuesOf,
222
216
  ValueOf,
@@ -289,15 +283,7 @@ export type {
289
283
  export {
290
284
  is,
291
285
  _createPromiseDecorator,
292
- _stringMapValues,
293
- _stringMapEntries,
294
- _objectKeys,
295
286
  pMap,
296
- _passthroughMapper,
297
- _passUndefinedMapper,
298
- _passthroughPredicate,
299
- _passNothingPredicate,
300
- _noop,
301
287
  ErrorMode,
302
288
  pDefer,
303
289
  AggregatedError,
@@ -310,13 +296,4 @@ export {
310
296
  _stringifyAny,
311
297
  jsonSchema,
312
298
  JsonSchemaAnyBuilder,
313
- commonLoggerMinLevel,
314
- commonLoggerNoop,
315
- commonLogLevelNumber,
316
- commonLoggerPipe,
317
- commonLoggerPrefix,
318
- commonLoggerCreate,
319
- PQueue,
320
- END,
321
- SKIP,
322
299
  }
@@ -6,6 +6,8 @@ export interface DeferredPromise<T = void> extends Promise<T> {
6
6
  reject(e?: Error): void
7
7
  }
8
8
 
9
+ /* eslint-disable @typescript-eslint/promise-function-async */
10
+
9
11
  /**
10
12
  * Returns DeferredPromise - a Promise that has .resolve() and .reject() methods.
11
13
  */
@@ -1,3 +1,3 @@
1
1
  export async function pDelay<T>(ms: number = 0, value?: T): Promise<T> {
2
- return new Promise<T>(resolve => setTimeout(() => resolve(value as T), ms))
2
+ return await new Promise<T>(resolve => setTimeout(() => resolve(value as T), ms))
3
3
  }
@@ -2,5 +2,5 @@
2
2
  * Returns Promise that never resolves ("hanging").
3
3
  */
4
4
  export async function pHang(): Promise<never> {
5
- return new Promise<never>(() => void 0)
5
+ return await new Promise<never>(() => void 0)
6
6
  }
@@ -120,7 +120,7 @@ export async function pMap<IN, OUT>(
120
120
  return ret as OUT[]
121
121
  }
122
122
 
123
- return new Promise<OUT[]>((resolve, reject) => {
123
+ return await new Promise<OUT[]>((resolve, reject) => {
124
124
  const next = () => {
125
125
  if (isSettled) {
126
126
  return
@@ -94,19 +94,19 @@ export class PQueue {
94
94
  * Resolves immediately in case the queue is Idle.
95
95
  * Idle means 0 queue and 0 inFlight.
96
96
  */
97
- onIdle(): Promise<void> {
98
- if (this.queue.length === 0 && this.inFlight === 0) return Promise.resolve()
97
+ async onIdle(): Promise<void> {
98
+ if (this.queue.length === 0 && this.inFlight === 0) return
99
99
 
100
100
  const listener = pDefer()
101
101
  this.onIdleListeners.push(listener)
102
- return listener
102
+ return await listener
103
103
  }
104
104
 
105
105
  /**
106
106
  * Push PromiseReturningFunction to the Queue.
107
107
  * Returns a Promise that resolves (or rejects) with the return value from the Promise.
108
108
  */
109
- push<R>(fn_: PromiseReturningFunction<R>): Promise<R> {
109
+ async push<R>(fn_: PromiseReturningFunction<R>): Promise<R> {
110
110
  const { concurrency } = this.cfg
111
111
  const resolveOnStart = this.cfg.resolveOn === 'start'
112
112
 
@@ -155,6 +155,6 @@ export class PQueue {
155
155
  this.debug(`inFlight ${this.inFlight}/${concurrency}, queue++ ${this.queue.length}`)
156
156
  }
157
157
 
158
- return fn.defer
158
+ return await fn.defer
159
159
  }
160
160
  }
@@ -9,7 +9,7 @@ const UNIQUE_VALUE = Symbol('unique')
9
9
  * Based on: https://makandracards.com/makandra/46681-javascript-how-to-query-the-state-of-a-native-promise
10
10
  */
11
11
  export async function pState(p: Promise<any>): Promise<'resolved' | 'rejected' | 'pending'> {
12
- return Promise.race([p, Promise.resolve(UNIQUE_VALUE)]).then(
12
+ return await Promise.race([p, Promise.resolve(UNIQUE_VALUE)]).then(
13
13
  v => {
14
14
  return v === UNIQUE_VALUE ? 'pending' : 'resolved'
15
15
  },
package/src/types.ts CHANGED
@@ -24,6 +24,10 @@ export interface PromiseMap {
24
24
  */
25
25
  export type AnyObject = Record<string, any>
26
26
 
27
+ export type AnyEnum = NumberEnum
28
+ export type NumberEnum = Record<string, number | string>
29
+ export type StringEnum = Record<string, string>
30
+
27
31
  export interface CreatedUpdated {
28
32
  created: number
29
33
  updated: number
@@ -263,3 +267,16 @@ export function _objectKeys<T extends AnyObject>(obj: T): (keyof T)[] {
263
267
 
264
268
  export type NullishValue = null | undefined
265
269
  export type FalsyValue = false | '' | 0 | null | undefined
270
+
271
+ /**
272
+ * Utility function that helps to cast *existing variable* to needed type T.
273
+ *
274
+ * @example
275
+ * try {} catch (err) {
276
+ * // err is unknown here
277
+ * _typeCast<AppError>(err)
278
+ * // now err is of type AppError
279
+ * err.data = {} // can be done, because it was casted
280
+ * }
281
+ */
282
+ export function _typeCast<T>(v: any): asserts v is T {}