@naturalcycles/js-lib 14.104.1 → 14.105.1

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,7 +53,7 @@ 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, END, SKIP, _noop, _objectKeys, _passNothingPredicate, _passthroughMapper, _passthroughPredicate, _passUndefinedMapper, _stringMapEntries, _stringMapValues } from './types';
56
57
  export * from './unit/size.util';
57
58
  import { is } from './vendor/is';
58
59
  import { CommonLogLevel, CommonLogFunction, CommonLogger, commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, CommonLogWithLevelFunction, commonLoggerCreate } from './log/commonLogger';
@@ -69,5 +70,5 @@ import { LocalDateConfig, LocalDateFormatter, LocalDateUnit, LocalDateUnitStrict
69
70
  import { LocalTimeConfig, LocalTimeFormatter, LocalTimeUnit, LocalTimeComponents, ISODayOfWeek } from './datetime/localTime';
70
71
  import { DateIntervalConfig, DateIntervalString } from './datetime/dateInterval';
71
72
  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 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, };
73
74
  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, };
package/dist/index.js CHANGED
@@ -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; } });
@@ -330,6 +330,7 @@ function _set(obj, path, value) {
330
330
  a[c]
331
331
  : // No: create the key. Is the next key a potential array-index?
332
332
  (a[c] =
333
+ // @ts-ignore
333
334
  // eslint-disable-next-line
334
335
  Math.abs(path[i + 1]) >> 0 === +path[i + 1]
335
336
  ? [] // Yes: assign a new array object
@@ -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;
@@ -17,6 +17,8 @@ exports.pProps = void 0;
17
17
  */
18
18
  async function pProps(input) {
19
19
  const keys = Object.keys(input);
20
+ // `as any` here is added to make it compile when `noUncheckedIndexedAccess` is false
21
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
20
22
  return Object.fromEntries((await Promise.all(Object.values(input))).map((v, i) => [keys[i], v]));
21
23
  }
22
24
  exports.pProps = pProps;
@@ -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
  }
@@ -17,7 +17,7 @@ exports._parseQueryString = void 0;
17
17
  function _parseQueryString(search) {
18
18
  const qs = {};
19
19
  search
20
- .substr(search[0] === '?' ? 1 : 0)
20
+ .slice(search[0] === '?' ? 1 : 0)
21
21
  .split('&')
22
22
  .forEach(p => {
23
23
  const [k, v] = p.split('=');
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;
@@ -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';
@@ -306,6 +306,7 @@ export function _set(obj, path, value) {
306
306
  a[c]
307
307
  : // No: create the key. Is the next key a potential array-index?
308
308
  (a[c] =
309
+ // @ts-ignore
309
310
  // eslint-disable-next-line
310
311
  Math.abs(path[i + 1]) >> 0 === +path[i + 1]
311
312
  ? [] // Yes: assign a new array object
@@ -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;
@@ -14,5 +14,7 @@
14
14
  */
15
15
  export async function pProps(input) {
16
16
  const keys = Object.keys(input);
17
+ // `as any` here is added to make it compile when `noUncheckedIndexedAccess` is false
18
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
17
19
  return Object.fromEntries((await Promise.all(Object.values(input))).map((v, i) => [keys[i], v]));
18
20
  }
@@ -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
  }
@@ -14,7 +14,7 @@
14
14
  export function _parseQueryString(search) {
15
15
  const qs = {};
16
16
  search
17
- .substr(search[0] === '?' ? 1 : 0)
17
+ .slice(search[0] === '?' ? 1 : 0)
18
18
  .split('&')
19
19
  .forEach(p => {
20
20
  const [k, v] = p.split('=');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@naturalcycles/js-lib",
3
- "version": "14.104.1",
3
+ "version": "14.105.1",
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,
@@ -217,6 +221,9 @@ export type {
217
221
  StringMap,
218
222
  PromiseMap,
219
223
  AnyObject,
224
+ AnyEnum,
225
+ NumberEnum,
226
+ StringEnum,
220
227
  AnyFunction,
221
228
  ValuesOf,
222
229
  ValueOf,
@@ -125,7 +125,7 @@ export function _mapValues<T extends AnyObject, OUT = T>(
125
125
  mutate = false,
126
126
  ): OUT {
127
127
  return Object.entries(obj).reduce((map, [k, v]) => {
128
- map[k] = mapper(k, v, obj)
128
+ map[k as keyof OUT] = mapper(k, v, obj)
129
129
  return map
130
130
  }, (mutate ? obj : {}) as OUT)
131
131
  }
@@ -142,9 +142,9 @@ export function _mapKeys<T extends AnyObject>(
142
142
  ): StringMap<T[keyof T]> {
143
143
  // eslint-disable-next-line unicorn/prefer-object-from-entries
144
144
  return Object.entries(obj).reduce((map, [k, v]) => {
145
- map[mapper(k, v, obj)] = v
145
+ map[mapper(k, v, obj) as keyof T] = v
146
146
  return map
147
- }, {})
147
+ }, {} as T)
148
148
  }
149
149
 
150
150
  /**
@@ -299,7 +299,7 @@ export function _unset<T extends AnyObject>(obj: T, prop: string): void {
299
299
  export function _invert<T extends AnyObject>(o: T): { [k in ValueOf<T>]: keyof T | undefined } {
300
300
  const inv = {} as { [k in ValueOf<T>]: keyof T }
301
301
  Object.keys(o).forEach(k => {
302
- inv[o[k]] = k
302
+ inv[o[k] as ValueOf<T>] = k
303
303
  })
304
304
  return inv
305
305
  }
@@ -365,6 +365,7 @@ export function _set<IN extends AnyObject, OUT = IN>(
365
365
  a[c]
366
366
  : // No: create the key. Is the next key a potential array-index?
367
367
  (a[c] =
368
+ // @ts-ignore
368
369
  // eslint-disable-next-line
369
370
  Math.abs(path[i + 1]) >> 0 === +path[i + 1]
370
371
  ? [] // Yes: assign a new array object
@@ -16,7 +16,7 @@ export function _sortObjectDeep<T>(o: T): T {
16
16
  Object.keys(o)
17
17
  .sort((a, b) => a.localeCompare(b))
18
18
  .forEach(k => {
19
- out[k] = _sortObjectDeep(o[k])
19
+ out[k as keyof T] = _sortObjectDeep(o[k as keyof T])
20
20
  })
21
21
 
22
22
  return out
@@ -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
@@ -16,5 +16,9 @@ export async function pProps<T>(input: { [K in keyof T]: T[K] | Promise<T[K]> })
16
16
  [K in keyof T]: Awaited<T[K]>
17
17
  }> {
18
18
  const keys = Object.keys(input)
19
- return Object.fromEntries((await Promise.all(Object.values(input))).map((v, i) => [keys[i], v]))
19
+ // `as any` here is added to make it compile when `noUncheckedIndexedAccess` is false
20
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
21
+ return Object.fromEntries(
22
+ (await Promise.all(Object.values(input))).map((v, i) => [keys[i], v]),
23
+ ) as any
20
24
  }
@@ -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
  },
@@ -14,9 +14,9 @@ import { StringMap } from '../types'
14
14
  * Goal of this function is to produce exactly same output as URLSearchParams would.
15
15
  */
16
16
  export function _parseQueryString(search: string): StringMap {
17
- const qs = {}
17
+ const qs: StringMap = {}
18
18
  search
19
- .substr(search[0] === '?' ? 1 : 0)
19
+ .slice(search[0] === '?' ? 1 : 0)
20
20
  .split('&')
21
21
  .forEach(p => {
22
22
  const [k, v] = p.split('=')
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