@naturalcycles/js-lib 14.75.1 → 14.78.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.
@@ -1,9 +1,17 @@
1
+ import { _assert } from '../error/assert';
1
2
  import { pTimeout } from '../promise/pTimeout';
3
+ import { _getMethodSignature } from './decorator.util';
2
4
  // eslint-disable-next-line @typescript-eslint/naming-convention
3
5
  export function _Timeout(opt) {
4
6
  return (target, key, descriptor) => {
7
+ _assert(typeof descriptor.value === 'function', '@_Timeout can be applied only to methods');
5
8
  const originalFn = descriptor.value;
6
- descriptor.value = pTimeout(originalFn, opt);
9
+ const keyStr = String(key);
10
+ descriptor.value = async function (...args) {
11
+ const ctx = this;
12
+ opt.name || (opt.name = _getMethodSignature(ctx, keyStr));
13
+ return await pTimeout(originalFn.apply(this, args), opt);
14
+ };
7
15
  return descriptor;
8
16
  };
9
17
  }
@@ -1,3 +1,4 @@
1
+ import { AppError } from './app.error';
1
2
  /**
2
3
  * Calls a function, returns a Tuple of [error, value].
3
4
  * Allows to write shorter code that avoids `try/catch`.
@@ -38,3 +39,45 @@ export async function pTry(promise) {
38
39
  return [err, undefined];
39
40
  }
40
41
  }
42
+ /**
43
+ * It is thrown when Error was expected, but didn't happen
44
+ * ("pass" happened instead).
45
+ * "Pass" means "no error".
46
+ */
47
+ export class UnexpectedPassError extends AppError {
48
+ constructor() {
49
+ super('_expectedError passed unexpectedly');
50
+ }
51
+ }
52
+ /**
53
+ * Calls `fn`, expects is to throw, catches the expected error and returns.
54
+ * If error was NOT thrown - throws UnexpectedPassError instead.
55
+ */
56
+ export function _expectedError(fn) {
57
+ try {
58
+ fn();
59
+ // Unexpected!
60
+ throw new UnexpectedPassError();
61
+ }
62
+ catch (err) {
63
+ if (err instanceof UnexpectedPassError)
64
+ throw err; // re-throw
65
+ return err; // this is expected!
66
+ }
67
+ }
68
+ /**
69
+ * Awaits passed `promise`, expects is to throw (reject), catches the expected error and returns.
70
+ * If error was NOT thrown - throws UnexpectedPassError instead.
71
+ */
72
+ export async function pExpectedError(promise) {
73
+ try {
74
+ await promise;
75
+ // Unexpected!
76
+ throw new UnexpectedPassError();
77
+ }
78
+ catch (err) {
79
+ if (err instanceof UnexpectedPassError)
80
+ throw err; // re-throw
81
+ return err; // this is expected!
82
+ }
83
+ }
package/dist-esm/index.js CHANGED
@@ -3,24 +3,24 @@ export * from './lazy';
3
3
  export * from './string/url.util';
4
4
  export * from './array/range';
5
5
  import { _createPromiseDecorator, } from './decorators/createPromiseDecorator';
6
- import { _debounce, _throttle } from './decorators/debounce';
7
- import { _Debounce, _Throttle } from './decorators/debounce.decorator';
8
- import { _getArgsSignature } from './decorators/decorator.util';
9
- import { _LogMethod } from './decorators/logMethod.decorator';
10
- import { _Memo } from './decorators/memo.decorator';
11
- import { _memoFn } from './decorators/memoFn';
12
- import { _Retry } from './decorators/retry.decorator';
13
- import { _Timeout } from './decorators/timeout.decorator';
14
- import { AppError } from './error/app.error';
15
- import { AssertionError, _assert, _assertDeepEquals, _assertEquals, _assertIsError, _assertIsNumber, _assertIsString, _assertTypeOf, } from './error/assert';
6
+ export * from './decorators/debounce';
7
+ export * from './decorators/debounce.decorator';
8
+ export * from './decorators/decorator.util';
9
+ export * from './decorators/logMethod.decorator';
10
+ export * from './decorators/memo.decorator';
11
+ export * from './decorators/memoFn';
12
+ export * from './decorators/retry.decorator';
13
+ export * from './decorators/timeout.decorator';
14
+ export * from './error/app.error';
15
+ export * from './error/assert';
16
16
  export * from './error/error.util';
17
17
  import { ErrorMode } from './error/errorMode';
18
- import { HttpError } from './error/http.error';
19
- import { _try, pTry } from './error/try';
18
+ export * from './error/http.error';
19
+ export * from './error/try';
20
20
  import { _TryCatch, _tryCatch } from './error/tryCatch';
21
- import { generateJsonSchemaFromData } from './json-schema/from-data/generateJsonSchemaFromData';
22
- import { JSON_SCHEMA_ORDER } from './json-schema/jsonSchema.cnst';
23
- import { mergeJsonSchemaObjects } from './json-schema/jsonSchema.util';
21
+ export * from './json-schema/from-data/generateJsonSchemaFromData';
22
+ export * from './json-schema/jsonSchema.cnst';
23
+ export * from './json-schema/jsonSchema.util';
24
24
  import { jsonSchema, JsonSchemaAnyBuilder, } from './json-schema/jsonSchemaBuilder';
25
25
  export * from './math/math.util';
26
26
  export * from './math/sma';
@@ -40,19 +40,19 @@ import { pMap } from './promise/pMap';
40
40
  export * from './promise/pProps';
41
41
  import { pRetry } from './promise/pRetry';
42
42
  export * from './promise/pState';
43
- import { pTimeout } from './promise/pTimeout';
43
+ import { pTimeout, pTimeoutFn } from './promise/pTimeout';
44
44
  export * from './promise/pTuple';
45
45
  export * from './string/case';
46
46
  export * from './string/json.util';
47
47
  export * from './string/string.util';
48
48
  import { _stringifyAny } from './string/stringifyAny';
49
- import { _ms, _since } from './time/time.util';
49
+ export * from './time/time.util';
50
50
  import { END, SKIP, _noop, _objectKeys, _passNothingPredicate, _passthroughMapper, _passthroughPredicate, _passUndefinedMapper, _stringMapEntries, _stringMapValues, } from './types';
51
- import { _gb, _hb, _kb, _mb } from './unit/size.util';
51
+ export * from './unit/size.util';
52
52
  import { is } from './vendor/is';
53
53
  import { commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, commonLoggerCreate, } from './log/commonLogger';
54
- import { _safeJsonStringify } from './string/safeJsonStringify';
54
+ export * from './string/safeJsonStringify';
55
55
  import { PQueue } from './promise/pQueue';
56
56
  export * from './seq/seq';
57
57
  export * from './math/stack.util';
58
- export { is, _Memo, _memoFn, _LogMethod, _getArgsSignature, _createPromiseDecorator, AppError, HttpError, AssertionError, _assert, _assertEquals, _assertDeepEquals, _assertIsError, _assertIsString, _assertIsNumber, _assertTypeOf, _stringMapValues, _stringMapEntries, _objectKeys, _debounce, _throttle, _Debounce, _Throttle, pMap, _passthroughMapper, _passUndefinedMapper, _passthroughPredicate, _passNothingPredicate, _noop, ErrorMode, pDefer, AggregatedError, pRetry, pTimeout, _Retry, _Timeout, _tryCatch, _TryCatch, _try, pTry, _stringifyAny, _ms, _since, _hb, _gb, _mb, _kb, mergeJsonSchemaObjects, jsonSchema, JsonSchemaAnyBuilder, JSON_SCHEMA_ORDER, generateJsonSchemaFromData, commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, commonLoggerCreate, _safeJsonStringify, PQueue, END, SKIP, };
58
+ export { is, _createPromiseDecorator, _stringMapValues, _stringMapEntries, _objectKeys, pMap, _passthroughMapper, _passUndefinedMapper, _passthroughPredicate, _passNothingPredicate, _noop, ErrorMode, pDefer, AggregatedError, pRetry, pTimeout, pTimeoutFn, _tryCatch, _TryCatch, _stringifyAny, jsonSchema, JsonSchemaAnyBuilder, commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, commonLoggerCreate, PQueue, END, SKIP, };
@@ -5,7 +5,7 @@ import { _since, _stringifyAny } from '..';
5
5
  */
6
6
  // eslint-disable-next-line @typescript-eslint/ban-types
7
7
  export function pRetry(fn, opt = {}) {
8
- const { maxAttempts = 4, delay: initialDelay = 1000, delayMultiplier = 2, predicate, logger = console, } = opt;
8
+ const { maxAttempts = 4, delay: initialDelay = 1000, delayMultiplier = 2, predicate, logger = console, name = fn.name, } = opt;
9
9
  let { logFirstAttempt = false, logRetries = true, logFailures = false, logSuccess = false } = opt;
10
10
  if (opt.logAll) {
11
11
  logFirstAttempt = logRetries = logFailures = true;
@@ -13,7 +13,7 @@ export function pRetry(fn, opt = {}) {
13
13
  if (opt.logNone) {
14
14
  logSuccess = logFirstAttempt = logRetries = logFailures = false;
15
15
  }
16
- const fname = ['pRetry', fn.name].filter(Boolean).join('.');
16
+ const fname = ['pRetry', name].filter(Boolean).join('.');
17
17
  return async function (...args) {
18
18
  let delay = initialDelay;
19
19
  let attempt = 0;
@@ -33,9 +33,9 @@ export function pRetry(fn, opt = {}) {
33
33
  }
34
34
  catch (err) {
35
35
  if (logFailures) {
36
- logger.warn(`${fname} attempt #${attempt} error in ${_since(started)}:\n${_stringifyAny(err, {
36
+ logger.warn(`${fname} attempt #${attempt} error in ${_since(started)}:`, _stringifyAny(err, {
37
37
  includeErrorData: true,
38
- })}`);
38
+ }));
39
39
  }
40
40
  if (attempt >= maxAttempts || (predicate && !predicate(err, attempt, maxAttempts))) {
41
41
  // Give up
@@ -1,37 +1,55 @@
1
+ import { AppError } from '../error/app.error';
2
+ export class TimeoutError extends AppError {
3
+ }
1
4
  /**
2
5
  * Decorates a Function with a timeout.
3
6
  * Throws an Error if the Function is not resolved in a certain time.
4
7
  * If the Function rejects - passes this rejection further.
5
8
  */
6
- export function pTimeout(fn, opt) {
7
- // const fname = fn.name || 'function'
8
- const { timeout, name, onTimeout } = opt;
9
- return async function (...args) {
10
- // eslint-disable-next-line no-async-promise-executor
11
- return await new Promise(async (resolve, reject) => {
12
- // Prepare the timeout timer
13
- const timer = setTimeout(() => {
14
- if (onTimeout) {
15
- try {
16
- resolve(onTimeout());
17
- }
18
- catch (err) {
19
- reject(err);
20
- }
21
- return;
9
+ export function pTimeoutFn(fn, opt) {
10
+ opt.name || (opt.name = fn.name);
11
+ return async function pTimeoutInternalFn(...args) {
12
+ return await pTimeout(fn.apply(this, args), opt);
13
+ };
14
+ }
15
+ /**
16
+ * Decorates a Function with a timeout and immediately calls it.
17
+ * Throws an Error if the Function is not resolved in a certain time.
18
+ * If the Function rejects - passes this rejection further.
19
+ */
20
+ export async function pTimeout(promise, opt) {
21
+ // todo: check how we can automatically infer function name (only applicable to named functions)
22
+ const { timeout, name, onTimeout, keepStackTrace = true } = opt;
23
+ const fakeError = keepStackTrace ? new Error('TimeoutError') : undefined;
24
+ // eslint-disable-next-line no-async-promise-executor
25
+ return await new Promise(async (resolve, reject) => {
26
+ // Prepare the timeout timer
27
+ const timer = setTimeout(() => {
28
+ if (onTimeout) {
29
+ try {
30
+ resolve(onTimeout());
22
31
  }
23
- reject(new Error(`"${name || fn.name || 'pTimeout function'}" timed out after ${timeout} ms`));
24
- }, timeout);
25
- // Execute the Function
26
- try {
27
- resolve(await fn.apply(this, args));
28
- }
29
- catch (err) {
30
- reject(err);
31
- }
32
- finally {
33
- clearTimeout(timer);
32
+ catch (err) {
33
+ if (fakeError)
34
+ err.stack = fakeError.stack; // keep original stack
35
+ reject(err);
36
+ }
37
+ return;
34
38
  }
35
- });
36
- };
39
+ const err = new TimeoutError(`"${name || 'pTimeout function'}" timed out after ${timeout} ms`);
40
+ if (fakeError)
41
+ err.stack = fakeError.stack; // keep original stack
42
+ reject(err);
43
+ }, timeout);
44
+ // Execute the Function
45
+ try {
46
+ resolve(await promise);
47
+ }
48
+ catch (err) {
49
+ reject(err);
50
+ }
51
+ finally {
52
+ clearTimeout(timer);
53
+ }
54
+ });
37
55
  }
@@ -127,6 +127,16 @@ export class Sequence {
127
127
  a.push(v);
128
128
  }
129
129
  }
130
+ forEach(fn) {
131
+ let i = -1;
132
+ // eslint-disable-next-line no-constant-condition
133
+ while (true) {
134
+ const v = this.next();
135
+ if (v === END)
136
+ return;
137
+ fn(v, ++i);
138
+ }
139
+ }
130
140
  }
131
141
  /**
132
142
  * Convenience function to create a Sequence.
@@ -1,8 +1,8 @@
1
1
  export function _gb(b) {
2
- return Math.round(b / (1024 * 1024 * 1024));
2
+ return Math.round(b / 1024 ** 3);
3
3
  }
4
4
  export function _mb(b) {
5
- return Math.round(b / (1024 * 1024));
5
+ return Math.round(b / 1024 ** 2);
6
6
  }
7
7
  export function _kb(b) {
8
8
  return Math.round(b / 1024);
@@ -11,11 +11,33 @@ export function _kb(b) {
11
11
  * Byte size to Human byte size string
12
12
  */
13
13
  export function _hb(b = 0) {
14
- if (b < 800)
15
- return `${Math.round(b)} byte(s)`;
16
- if (b < 800 * 1024)
17
- return `${Math.round(b / 1024)} Kb`;
18
- if (b < 800 * 1024 * 1024)
19
- return `${Math.round(b / 1024 / 1024)} Mb`;
20
- return `${Math.round(b / 1024 / 1024 / 1024)} Gb`;
14
+ if (b < 1024)
15
+ return `${Math.round(b)} byte`;
16
+ if (b < 1024 ** 2)
17
+ return `${(b / 1024).toPrecision(3)} Kb`;
18
+ if (b < 1024 ** 3)
19
+ return `${(b / 1024 ** 2).toPrecision(3)} Mb`;
20
+ if (b < 1024 ** 4)
21
+ return `${(b / 1024 ** 3).toPrecision(3)} Gb`;
22
+ if (b < 1024 ** 5)
23
+ return `${(b / 1024 ** 4).toPrecision(3)} Tb`;
24
+ return `${Math.round(b / 1024 ** 4)} Tb`;
25
+ }
26
+ /**
27
+ * hc stands for "human count", similar to "human bytes" `_hb` function.
28
+ * Helpful to print big numbers, as it adds `K` (kilo), `M` (mega), etc to make
29
+ * them more readable.
30
+ */
31
+ export function _hc(c = 0) {
32
+ if (c < 10 ** 4)
33
+ return String(c);
34
+ if (c < 10 ** 6)
35
+ return (c / 10 ** 3).toPrecision(3) + ' K';
36
+ if (c < 10 ** 9)
37
+ return (c / 10 ** 6).toPrecision(3) + ' M'; // million
38
+ if (c < 10 ** 12)
39
+ return (c / 10 ** 9).toPrecision(3) + ' B'; // billion
40
+ if (c < 10 ** 15)
41
+ return (c / 10 ** 12).toPrecision(3) + ' T'; // trillion
42
+ return Math.round(c / 10 ** 12) + ' T';
21
43
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@naturalcycles/js-lib",
3
- "version": "14.75.1",
3
+ "version": "14.78.1",
4
4
  "scripts": {
5
5
  "prepare": "husky install",
6
6
  "build-prod": "build-prod-esm-cjs",
@@ -14,13 +14,14 @@
14
14
  "@naturalcycles/bench-lib": "^1.5.0",
15
15
  "@naturalcycles/dev-lib": "^12.0.0",
16
16
  "@naturalcycles/nodejs-lib": "^12.33.4",
17
- "@types/node": "^16.0.0",
17
+ "@types/node": "^17.0.4",
18
18
  "jest": "^27.0.1",
19
19
  "patch-package": "^6.2.1",
20
20
  "prettier": "^2.1.2",
21
21
  "rxjs": "^7.0.1",
22
22
  "vuepress": "^1.7.1",
23
- "vuepress-plugin-typescript": "^0.3.1"
23
+ "vuepress-plugin-typescript": "^0.3.1",
24
+ "weak-napi": "^2.0.2"
24
25
  },
25
26
  "files": [
26
27
  "dist",
@@ -1,4 +1,4 @@
1
- import { SimpleMovingAverage, _stringifyAny, CommonLogger } from '..'
1
+ import { SimpleMovingAverage, _stringifyAny, CommonLogger, _assert } from '..'
2
2
  import { _ms } from '../time/time.util'
3
3
  import { _getArgsSignature, _getMethodSignature } from './decorator.util'
4
4
 
@@ -69,9 +69,7 @@ export interface LogMethodOptions {
69
69
  // eslint-disable-next-line @typescript-eslint/naming-convention
70
70
  export function _LogMethod(opt: LogMethodOptions = {}): MethodDecorator {
71
71
  return (target, key, descriptor) => {
72
- if (typeof descriptor.value !== 'function') {
73
- throw new TypeError('@_LogMethod can be applied only to methods')
74
- }
72
+ _assert(typeof descriptor.value === 'function', '@_LogMethod can be applied only to methods')
75
73
 
76
74
  const originalFn = descriptor.value
77
75
  const keyStr = String(key)
@@ -1,10 +1,21 @@
1
+ import { _assert } from '../error/assert'
1
2
  import { pTimeout, PTimeoutOptions } from '../promise/pTimeout'
3
+ import { _getMethodSignature } from './decorator.util'
2
4
 
3
5
  // eslint-disable-next-line @typescript-eslint/naming-convention
4
6
  export function _Timeout(opt: PTimeoutOptions): MethodDecorator {
5
7
  return (target, key, descriptor) => {
8
+ _assert(typeof descriptor.value === 'function', '@_Timeout can be applied only to methods')
9
+
6
10
  const originalFn = descriptor.value
7
- descriptor.value = pTimeout(originalFn as any, opt)
11
+ const keyStr = String(key)
12
+
13
+ descriptor.value = async function (this: typeof target, ...args: any[]) {
14
+ const ctx = this
15
+ opt.name ||= _getMethodSignature(ctx, keyStr)
16
+ return await pTimeout(originalFn.apply(this, args), opt)
17
+ } as any
18
+
8
19
  return descriptor
9
20
  }
10
21
  }
package/src/error/try.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import { AnyFunction } from '../types'
2
+ import { AppError } from './app.error'
3
+
1
4
  /**
2
5
  * Calls a function, returns a Tuple of [error, value].
3
6
  * Allows to write shorter code that avoids `try/catch`.
@@ -42,3 +45,44 @@ export async function pTry<ERR = unknown, RETURN = void>(
42
45
  return [err as ERR, undefined as any]
43
46
  }
44
47
  }
48
+
49
+ /**
50
+ * It is thrown when Error was expected, but didn't happen
51
+ * ("pass" happened instead).
52
+ * "Pass" means "no error".
53
+ */
54
+ export class UnexpectedPassError extends AppError {
55
+ constructor() {
56
+ super('_expectedError passed unexpectedly')
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Calls `fn`, expects is to throw, catches the expected error and returns.
62
+ * If error was NOT thrown - throws UnexpectedPassError instead.
63
+ */
64
+ export function _expectedError<ERR = Error>(fn: AnyFunction): ERR {
65
+ try {
66
+ fn()
67
+ // Unexpected!
68
+ throw new UnexpectedPassError()
69
+ } catch (err) {
70
+ if (err instanceof UnexpectedPassError) throw err // re-throw
71
+ return err as ERR // this is expected!
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Awaits passed `promise`, expects is to throw (reject), catches the expected error and returns.
77
+ * If error was NOT thrown - throws UnexpectedPassError instead.
78
+ */
79
+ export async function pExpectedError<ERR = Error>(promise: Promise<any>): Promise<ERR> {
80
+ try {
81
+ await promise
82
+ // Unexpected!
83
+ throw new UnexpectedPassError()
84
+ } catch (err) {
85
+ if (err instanceof UnexpectedPassError) throw err // re-throw
86
+ return err as ERR // this is expected!
87
+ }
88
+ }
package/src/index.ts CHANGED
@@ -7,26 +7,17 @@ import {
7
7
  PromiseDecoratorResp,
8
8
  _createPromiseDecorator,
9
9
  } from './decorators/createPromiseDecorator'
10
- import { _debounce, _throttle } from './decorators/debounce'
11
- import { _Debounce, _Throttle } from './decorators/debounce.decorator'
12
- import { _getArgsSignature } from './decorators/decorator.util'
13
- import { _LogMethod } from './decorators/logMethod.decorator'
14
- import { _Memo } from './decorators/memo.decorator'
10
+ export * from './decorators/debounce'
11
+ export * from './decorators/debounce.decorator'
12
+ export * from './decorators/decorator.util'
13
+ export * from './decorators/logMethod.decorator'
14
+ export * from './decorators/memo.decorator'
15
15
  import { MemoCache } from './decorators/memo.util'
16
- import { _memoFn } from './decorators/memoFn'
17
- import { _Retry } from './decorators/retry.decorator'
18
- import { _Timeout } from './decorators/timeout.decorator'
19
- import { AppError } from './error/app.error'
20
- import {
21
- AssertionError,
22
- _assert,
23
- _assertDeepEquals,
24
- _assertEquals,
25
- _assertIsError,
26
- _assertIsNumber,
27
- _assertIsString,
28
- _assertTypeOf,
29
- } from './error/assert'
16
+ export * from './decorators/memoFn'
17
+ export * from './decorators/retry.decorator'
18
+ export * from './decorators/timeout.decorator'
19
+ export * from './error/app.error'
20
+ export * from './error/assert'
30
21
  import {
31
22
  Admin401ErrorData,
32
23
  Admin403ErrorData,
@@ -37,11 +28,11 @@ import {
37
28
  } from './error/error.model'
38
29
  export * from './error/error.util'
39
30
  import { ErrorMode } from './error/errorMode'
40
- import { HttpError } from './error/http.error'
41
- import { _try, pTry } from './error/try'
31
+ export * from './error/http.error'
32
+ export * from './error/try'
42
33
  import { TryCatchOptions, _TryCatch, _tryCatch } from './error/tryCatch'
43
- import { generateJsonSchemaFromData } from './json-schema/from-data/generateJsonSchemaFromData'
44
- import { JSON_SCHEMA_ORDER } from './json-schema/jsonSchema.cnst'
34
+ export * from './json-schema/from-data/generateJsonSchemaFromData'
35
+ export * from './json-schema/jsonSchema.cnst'
45
36
  import {
46
37
  JsonSchema,
47
38
  JsonSchemaAllOf,
@@ -61,7 +52,7 @@ import {
61
52
  JsonSchemaString,
62
53
  JsonSchemaTuple,
63
54
  } from './json-schema/jsonSchema.model'
64
- import { mergeJsonSchemaObjects } from './json-schema/jsonSchema.util'
55
+ export * from './json-schema/jsonSchema.util'
65
56
  import {
66
57
  jsonSchema,
67
58
  JsonSchemaAnyBuilder,
@@ -85,13 +76,13 @@ import { pMap, PMapOptions } from './promise/pMap'
85
76
  export * from './promise/pProps'
86
77
  import { pRetry, PRetryOptions } from './promise/pRetry'
87
78
  export * from './promise/pState'
88
- import { pTimeout, PTimeoutOptions } from './promise/pTimeout'
79
+ import { pTimeout, pTimeoutFn, PTimeoutOptions } from './promise/pTimeout'
89
80
  export * from './promise/pTuple'
90
81
  export * from './string/case'
91
82
  export * from './string/json.util'
92
83
  export * from './string/string.util'
93
84
  import { JsonStringifyFunction, StringifyAnyOptions, _stringifyAny } from './string/stringifyAny'
94
- import { _ms, _since } from './time/time.util'
85
+ export * from './time/time.util'
95
86
  import {
96
87
  Class,
97
88
  ConditionalExcept,
@@ -144,7 +135,7 @@ import {
144
135
  _stringMapEntries,
145
136
  _stringMapValues,
146
137
  } from './types'
147
- import { _gb, _hb, _kb, _mb } from './unit/size.util'
138
+ export * from './unit/size.util'
148
139
  import { is } from './vendor/is'
149
140
  import {
150
141
  CommonLogLevel,
@@ -158,7 +149,7 @@ import {
158
149
  CommonLogWithLevelFunction,
159
150
  commonLoggerCreate,
160
151
  } from './log/commonLogger'
161
- import { _safeJsonStringify } from './string/safeJsonStringify'
152
+ export * from './string/safeJsonStringify'
162
153
  import { PQueue, PQueueCfg } from './promise/pQueue'
163
154
  export * from './seq/seq'
164
155
  export * from './math/stack.util'
@@ -245,28 +236,10 @@ export type {
245
236
 
246
237
  export {
247
238
  is,
248
- _Memo,
249
- _memoFn,
250
- _LogMethod,
251
- _getArgsSignature,
252
239
  _createPromiseDecorator,
253
- AppError,
254
- HttpError,
255
- AssertionError,
256
- _assert,
257
- _assertEquals,
258
- _assertDeepEquals,
259
- _assertIsError,
260
- _assertIsString,
261
- _assertIsNumber,
262
- _assertTypeOf,
263
240
  _stringMapValues,
264
241
  _stringMapEntries,
265
242
  _objectKeys,
266
- _debounce,
267
- _throttle,
268
- _Debounce,
269
- _Throttle,
270
243
  pMap,
271
244
  _passthroughMapper,
272
245
  _passUndefinedMapper,
@@ -278,31 +251,18 @@ export {
278
251
  AggregatedError,
279
252
  pRetry,
280
253
  pTimeout,
281
- _Retry,
282
- _Timeout,
254
+ pTimeoutFn,
283
255
  _tryCatch,
284
256
  _TryCatch,
285
- _try,
286
- pTry,
287
257
  _stringifyAny,
288
- _ms,
289
- _since,
290
- _hb,
291
- _gb,
292
- _mb,
293
- _kb,
294
- mergeJsonSchemaObjects,
295
258
  jsonSchema,
296
259
  JsonSchemaAnyBuilder,
297
- JSON_SCHEMA_ORDER,
298
- generateJsonSchemaFromData,
299
260
  commonLoggerMinLevel,
300
261
  commonLoggerNoop,
301
262
  commonLogLevelNumber,
302
263
  commonLoggerPipe,
303
264
  commonLoggerPrefix,
304
265
  commonLoggerCreate,
305
- _safeJsonStringify,
306
266
  PQueue,
307
267
  END,
308
268
  SKIP,
@@ -1,6 +1,12 @@
1
- import { _since, _stringifyAny, CommonLogger } from '..'
1
+ import { _since, _stringifyAny, AnyFunction, CommonLogger } from '..'
2
2
 
3
3
  export interface PRetryOptions {
4
+ /**
5
+ * If set - will be included in the error message.
6
+ * Can be used to identify the place in the code that failed.
7
+ */
8
+ name?: string
9
+
4
10
  /**
5
11
  * How many attempts to try.
6
12
  * First attempt is not a retry, but "initial try". It still counts.
@@ -75,13 +81,14 @@ export interface PRetryOptions {
75
81
  * Implements "Exponential back-off strategy" by multiplying the delay by `delayMultiplier` with each try.
76
82
  */
77
83
  // eslint-disable-next-line @typescript-eslint/ban-types
78
- export function pRetry<T extends Function>(fn: T, opt: PRetryOptions = {}): T {
84
+ export function pRetry<T extends AnyFunction>(fn: T, opt: PRetryOptions = {}): T {
79
85
  const {
80
86
  maxAttempts = 4,
81
87
  delay: initialDelay = 1000,
82
88
  delayMultiplier = 2,
83
89
  predicate,
84
90
  logger = console,
91
+ name = fn.name,
85
92
  } = opt
86
93
 
87
94
  let { logFirstAttempt = false, logRetries = true, logFailures = false, logSuccess = false } = opt
@@ -93,7 +100,7 @@ export function pRetry<T extends Function>(fn: T, opt: PRetryOptions = {}): T {
93
100
  logSuccess = logFirstAttempt = logRetries = logFailures = false
94
101
  }
95
102
 
96
- const fname = ['pRetry', fn.name].filter(Boolean).join('.')
103
+ const fname = ['pRetry', name].filter(Boolean).join('.')
97
104
 
98
105
  return async function (this: any, ...args: any[]) {
99
106
  let delay = initialDelay
@@ -118,9 +125,10 @@ export function pRetry<T extends Function>(fn: T, opt: PRetryOptions = {}): T {
118
125
  } catch (err) {
119
126
  if (logFailures) {
120
127
  logger.warn(
121
- `${fname} attempt #${attempt} error in ${_since(started)}:\n${_stringifyAny(err, {
128
+ `${fname} attempt #${attempt} error in ${_since(started)}:`,
129
+ _stringifyAny(err, {
122
130
  includeErrorData: true,
123
- })}`,
131
+ }),
124
132
  )
125
133
  }
126
134