@naturalcycles/js-lib 14.74.0 → 14.77.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.
@@ -20,9 +20,7 @@ const decorator_util_1 = require("./decorator.util");
20
20
  // eslint-disable-next-line @typescript-eslint/naming-convention
21
21
  function _LogMethod(opt = {}) {
22
22
  return (target, key, descriptor) => {
23
- if (typeof descriptor.value !== 'function') {
24
- throw new TypeError('@_LogMethod can be applied only to methods');
25
- }
23
+ (0, __1._assert)(typeof descriptor.value === 'function', '@_LogMethod can be applied only to methods');
26
24
  const originalFn = descriptor.value;
27
25
  const keyStr = String(key);
28
26
  const { avg, noLogArgs, logStart, logResult, noLogResultLength, logger = console } = opt;
@@ -1,12 +1,20 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports._Timeout = void 0;
4
+ const assert_1 = require("../error/assert");
4
5
  const pTimeout_1 = require("../promise/pTimeout");
6
+ const decorator_util_1 = require("./decorator.util");
5
7
  // eslint-disable-next-line @typescript-eslint/naming-convention
6
8
  function _Timeout(opt) {
7
9
  return (target, key, descriptor) => {
10
+ (0, assert_1._assert)(typeof descriptor.value === 'function', '@_Timeout can be applied only to methods');
8
11
  const originalFn = descriptor.value;
9
- descriptor.value = (0, pTimeout_1.pTimeout)(originalFn, opt);
12
+ const keyStr = String(key);
13
+ descriptor.value = async function (...args) {
14
+ const ctx = this;
15
+ opt.name || (opt.name = (0, decorator_util_1._getMethodSignature)(ctx, keyStr));
16
+ return await (0, pTimeout_1.pTimeout)(originalFn.apply(this, args), opt);
17
+ };
10
18
  return descriptor;
11
19
  };
12
20
  }
@@ -1,3 +1,5 @@
1
+ import { AnyFunction } from '../types';
2
+ import { AppError } from './app.error';
1
3
  /**
2
4
  * Calls a function, returns a Tuple of [error, value].
3
5
  * Allows to write shorter code that avoids `try/catch`.
@@ -22,3 +24,21 @@ export declare function _try<ERR = unknown, RETURN = void>(fn: () => RETURN): [e
22
24
  * but you should check for `err` presense first!
23
25
  */
24
26
  export declare function pTry<ERR = unknown, RETURN = void>(promise: Promise<RETURN>): Promise<[err: ERR | null, value: Awaited<RETURN>]>;
27
+ /**
28
+ * It is thrown when Error was expected, but didn't happen
29
+ * ("pass" happened instead).
30
+ * "Pass" means "no error".
31
+ */
32
+ export declare class UnexpectedPassError extends AppError {
33
+ constructor();
34
+ }
35
+ /**
36
+ * Calls `fn`, expects is to throw, catches the expected error and returns.
37
+ * If error was NOT thrown - throws UnexpectedPassError instead.
38
+ */
39
+ export declare function _expectedError<ERR = Error>(fn: AnyFunction): ERR;
40
+ /**
41
+ * Awaits passed `promise`, expects is to throw (reject), catches the expected error and returns.
42
+ * If error was NOT thrown - throws UnexpectedPassError instead.
43
+ */
44
+ export declare function pExpectedError<ERR = Error>(promise: Promise<any>): Promise<ERR>;
package/dist/error/try.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.pTry = exports._try = void 0;
3
+ exports.pExpectedError = exports._expectedError = exports.UnexpectedPassError = exports.pTry = exports._try = void 0;
4
+ const app_error_1 = require("./app.error");
4
5
  /**
5
6
  * Calls a function, returns a Tuple of [error, value].
6
7
  * Allows to write shorter code that avoids `try/catch`.
@@ -43,3 +44,48 @@ async function pTry(promise) {
43
44
  }
44
45
  }
45
46
  exports.pTry = pTry;
47
+ /**
48
+ * It is thrown when Error was expected, but didn't happen
49
+ * ("pass" happened instead).
50
+ * "Pass" means "no error".
51
+ */
52
+ class UnexpectedPassError extends app_error_1.AppError {
53
+ constructor() {
54
+ super('_expectedError passed unexpectedly');
55
+ }
56
+ }
57
+ exports.UnexpectedPassError = UnexpectedPassError;
58
+ /**
59
+ * Calls `fn`, expects is to throw, catches the expected error and returns.
60
+ * If error was NOT thrown - throws UnexpectedPassError instead.
61
+ */
62
+ function _expectedError(fn) {
63
+ try {
64
+ fn();
65
+ // Unexpected!
66
+ throw new UnexpectedPassError();
67
+ }
68
+ catch (err) {
69
+ if (err instanceof UnexpectedPassError)
70
+ throw err; // re-throw
71
+ return err; // this is expected!
72
+ }
73
+ }
74
+ exports._expectedError = _expectedError;
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
+ async function pExpectedError(promise) {
80
+ try {
81
+ await promise;
82
+ // Unexpected!
83
+ throw new UnexpectedPassError();
84
+ }
85
+ catch (err) {
86
+ if (err instanceof UnexpectedPassError)
87
+ throw err; // re-throw
88
+ return err; // this is expected!
89
+ }
90
+ }
91
+ exports.pExpectedError = pExpectedError;
package/dist/index.d.ts CHANGED
@@ -3,27 +3,27 @@ export * from './lazy';
3
3
  export * from './string/url.util';
4
4
  export * from './array/range';
5
5
  import { PromiseDecoratorCfg, PromiseDecoratorResp, _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';
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
11
  import { MemoCache } from './decorators/memo.util';
12
- import { _memoFn } from './decorators/memoFn';
13
- import { _Retry } from './decorators/retry.decorator';
14
- import { _Timeout } from './decorators/timeout.decorator';
15
- import { AppError } from './error/app.error';
16
- import { AssertionError, _assert, _assertDeepEquals, _assertEquals, _assertIsError, _assertIsNumber, _assertIsString, _assertTypeOf } from './error/assert';
12
+ export * from './decorators/memoFn';
13
+ export * from './decorators/retry.decorator';
14
+ export * from './decorators/timeout.decorator';
15
+ export * from './error/app.error';
16
+ export * from './error/assert';
17
17
  import { Admin401ErrorData, Admin403ErrorData, ErrorData, ErrorObject, HttpErrorData, HttpErrorResponse } from './error/error.model';
18
18
  export * from './error/error.util';
19
19
  import { ErrorMode } from './error/errorMode';
20
- import { HttpError } from './error/http.error';
21
- import { _try, pTry } from './error/try';
20
+ export * from './error/http.error';
21
+ export * from './error/try';
22
22
  import { TryCatchOptions, _TryCatch, _tryCatch } from './error/tryCatch';
23
- import { generateJsonSchemaFromData } from './json-schema/from-data/generateJsonSchemaFromData';
24
- import { JSON_SCHEMA_ORDER } from './json-schema/jsonSchema.cnst';
23
+ export * from './json-schema/from-data/generateJsonSchemaFromData';
24
+ export * from './json-schema/jsonSchema.cnst';
25
25
  import { JsonSchema, JsonSchemaAllOf, JsonSchemaAny, JsonSchemaAnyOf, JsonSchemaArray, JsonSchemaBoolean, JsonSchemaConst, JsonSchemaEnum, JsonSchemaNot, JsonSchemaNull, JsonSchemaNumber, JsonSchemaRootObject, JsonSchemaObject, JsonSchemaOneOf, JsonSchemaRef, JsonSchemaString, JsonSchemaTuple } from './json-schema/jsonSchema.model';
26
- import { mergeJsonSchemaObjects } from './json-schema/jsonSchema.util';
26
+ export * from './json-schema/jsonSchema.util';
27
27
  import { jsonSchema, JsonSchemaAnyBuilder, JsonSchemaBuilder } from './json-schema/jsonSchemaBuilder';
28
28
  export * from './math/math.util';
29
29
  export * from './math/sma';
@@ -43,21 +43,21 @@ import { pMap, PMapOptions } from './promise/pMap';
43
43
  export * from './promise/pProps';
44
44
  import { pRetry, PRetryOptions } from './promise/pRetry';
45
45
  export * from './promise/pState';
46
- import { pTimeout, PTimeoutOptions } from './promise/pTimeout';
46
+ import { pTimeout, pTimeoutFn, PTimeoutOptions } from './promise/pTimeout';
47
47
  export * from './promise/pTuple';
48
48
  export * from './string/case';
49
49
  export * from './string/json.util';
50
50
  export * from './string/string.util';
51
51
  import { JsonStringifyFunction, StringifyAnyOptions, _stringifyAny } from './string/stringifyAny';
52
- import { _ms, _since } from './time/time.util';
52
+ export * from './time/time.util';
53
53
  import { Class, ConditionalExcept, ConditionalPick, Merge, Promisable, ReadonlyDeep, Simplify } from './typeFest';
54
54
  import { AsyncMapper, AsyncPredicate, BaseDBEntity, CreatedUpdated, CreatedUpdatedId, ObjectWithId, AnyObjectWithId, Saved, Unsaved, BatchResult, InstanceId, IsoDate, IsoDateTime, KeyValueTuple, Mapper, ObjectMapper, ObjectPredicate, Predicate, PromiseMap, AnyObject, AnyFunction, Reviver, SavedDBEntity, StringMap, UnixTimestamp, ValueOf, ValuesOf, AbortableMapper, AbortableAsyncPredicate, AbortableAsyncMapper, AbortablePredicate, END, SKIP, _noop, _objectKeys, _passNothingPredicate, _passthroughMapper, _passthroughPredicate, _passUndefinedMapper, _stringMapEntries, _stringMapValues } from './types';
55
- import { _gb, _hb, _kb, _mb } from './unit/size.util';
55
+ export * from './unit/size.util';
56
56
  import { is } from './vendor/is';
57
57
  import { CommonLogLevel, CommonLogFunction, CommonLogger, commonLoggerMinLevel, commonLoggerNoop, commonLogLevelNumber, commonLoggerPipe, commonLoggerPrefix, CommonLogWithLevelFunction, commonLoggerCreate } from './log/commonLogger';
58
- import { _safeJsonStringify } from './string/safeJsonStringify';
58
+ export * from './string/safeJsonStringify';
59
59
  import { PQueue, PQueueCfg } from './promise/pQueue';
60
60
  export * from './seq/seq';
61
61
  export * from './math/stack.util';
62
62
  export type { AbortableMapper, AbortablePredicate, AbortableAsyncPredicate, AbortableAsyncMapper, PQueueCfg, MemoCache, PromiseDecoratorCfg, PromiseDecoratorResp, ErrorData, ErrorObject, HttpErrorData, HttpErrorResponse, Admin401ErrorData, Admin403ErrorData, StringMap, PromiseMap, AnyObject, AnyFunction, ValuesOf, ValueOf, KeyValueTuple, ObjectMapper, ObjectPredicate, InstanceId, IsoDate, IsoDateTime, Reviver, PMapOptions, Mapper, AsyncMapper, Predicate, AsyncPredicate, BatchResult, DeferredPromise, PRetryOptions, PTimeoutOptions, TryCatchOptions, StringifyAnyOptions, JsonStringifyFunction, Merge, ReadonlyDeep, Promisable, Simplify, ConditionalPick, ConditionalExcept, Class, UnixTimestamp, BaseDBEntity, SavedDBEntity, Saved, Unsaved, 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, };
63
- 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, };
63
+ 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, };
package/dist/index.js CHANGED
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.JsonSchemaAnyBuilder = exports.jsonSchema = exports.mergeJsonSchemaObjects = exports._kb = exports._mb = exports._gb = exports._hb = exports._since = exports._ms = exports._stringifyAny = exports.pTry = exports._try = exports._TryCatch = exports._tryCatch = exports._Timeout = exports._Retry = exports.pTimeout = exports.pRetry = exports.AggregatedError = exports.pDefer = exports.ErrorMode = exports._noop = exports._passNothingPredicate = exports._passthroughPredicate = exports._passUndefinedMapper = exports._passthroughMapper = exports.pMap = exports._Throttle = exports._Debounce = exports._throttle = exports._debounce = exports._objectKeys = exports._stringMapEntries = exports._stringMapValues = exports._assertTypeOf = exports._assertIsNumber = exports._assertIsString = exports._assertIsError = exports._assertDeepEquals = exports._assertEquals = exports._assert = exports.AssertionError = exports.HttpError = exports.AppError = exports._createPromiseDecorator = exports._getArgsSignature = exports._LogMethod = exports._memoFn = exports._Memo = exports.is = void 0;
4
- exports.SKIP = exports.END = exports.PQueue = exports._safeJsonStringify = exports.commonLoggerCreate = exports.commonLoggerPrefix = exports.commonLoggerPipe = exports.commonLogLevelNumber = exports.commonLoggerNoop = exports.commonLoggerMinLevel = exports.generateJsonSchemaFromData = exports.JSON_SCHEMA_ORDER = void 0;
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.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;
5
4
  const tslib_1 = require("tslib");
6
5
  (0, tslib_1.__exportStar)(require("./array/array.util"), exports);
7
6
  (0, tslib_1.__exportStar)(require("./lazy"), exports);
@@ -9,52 +8,27 @@ const tslib_1 = require("tslib");
9
8
  (0, tslib_1.__exportStar)(require("./array/range"), exports);
10
9
  const createPromiseDecorator_1 = require("./decorators/createPromiseDecorator");
11
10
  Object.defineProperty(exports, "_createPromiseDecorator", { enumerable: true, get: function () { return createPromiseDecorator_1._createPromiseDecorator; } });
12
- const debounce_1 = require("./decorators/debounce");
13
- Object.defineProperty(exports, "_debounce", { enumerable: true, get: function () { return debounce_1._debounce; } });
14
- Object.defineProperty(exports, "_throttle", { enumerable: true, get: function () { return debounce_1._throttle; } });
15
- const debounce_decorator_1 = require("./decorators/debounce.decorator");
16
- Object.defineProperty(exports, "_Debounce", { enumerable: true, get: function () { return debounce_decorator_1._Debounce; } });
17
- Object.defineProperty(exports, "_Throttle", { enumerable: true, get: function () { return debounce_decorator_1._Throttle; } });
18
- const decorator_util_1 = require("./decorators/decorator.util");
19
- Object.defineProperty(exports, "_getArgsSignature", { enumerable: true, get: function () { return decorator_util_1._getArgsSignature; } });
20
- const logMethod_decorator_1 = require("./decorators/logMethod.decorator");
21
- Object.defineProperty(exports, "_LogMethod", { enumerable: true, get: function () { return logMethod_decorator_1._LogMethod; } });
22
- const memo_decorator_1 = require("./decorators/memo.decorator");
23
- Object.defineProperty(exports, "_Memo", { enumerable: true, get: function () { return memo_decorator_1._Memo; } });
24
- const memoFn_1 = require("./decorators/memoFn");
25
- Object.defineProperty(exports, "_memoFn", { enumerable: true, get: function () { return memoFn_1._memoFn; } });
26
- const retry_decorator_1 = require("./decorators/retry.decorator");
27
- Object.defineProperty(exports, "_Retry", { enumerable: true, get: function () { return retry_decorator_1._Retry; } });
28
- const timeout_decorator_1 = require("./decorators/timeout.decorator");
29
- Object.defineProperty(exports, "_Timeout", { enumerable: true, get: function () { return timeout_decorator_1._Timeout; } });
30
- const app_error_1 = require("./error/app.error");
31
- Object.defineProperty(exports, "AppError", { enumerable: true, get: function () { return app_error_1.AppError; } });
32
- const assert_1 = require("./error/assert");
33
- Object.defineProperty(exports, "AssertionError", { enumerable: true, get: function () { return assert_1.AssertionError; } });
34
- Object.defineProperty(exports, "_assert", { enumerable: true, get: function () { return assert_1._assert; } });
35
- Object.defineProperty(exports, "_assertDeepEquals", { enumerable: true, get: function () { return assert_1._assertDeepEquals; } });
36
- Object.defineProperty(exports, "_assertEquals", { enumerable: true, get: function () { return assert_1._assertEquals; } });
37
- Object.defineProperty(exports, "_assertIsError", { enumerable: true, get: function () { return assert_1._assertIsError; } });
38
- Object.defineProperty(exports, "_assertIsNumber", { enumerable: true, get: function () { return assert_1._assertIsNumber; } });
39
- Object.defineProperty(exports, "_assertIsString", { enumerable: true, get: function () { return assert_1._assertIsString; } });
40
- Object.defineProperty(exports, "_assertTypeOf", { enumerable: true, get: function () { return assert_1._assertTypeOf; } });
11
+ (0, tslib_1.__exportStar)(require("./decorators/debounce"), exports);
12
+ (0, tslib_1.__exportStar)(require("./decorators/debounce.decorator"), exports);
13
+ (0, tslib_1.__exportStar)(require("./decorators/decorator.util"), exports);
14
+ (0, tslib_1.__exportStar)(require("./decorators/logMethod.decorator"), exports);
15
+ (0, tslib_1.__exportStar)(require("./decorators/memo.decorator"), exports);
16
+ (0, tslib_1.__exportStar)(require("./decorators/memoFn"), exports);
17
+ (0, tslib_1.__exportStar)(require("./decorators/retry.decorator"), exports);
18
+ (0, tslib_1.__exportStar)(require("./decorators/timeout.decorator"), exports);
19
+ (0, tslib_1.__exportStar)(require("./error/app.error"), exports);
20
+ (0, tslib_1.__exportStar)(require("./error/assert"), exports);
41
21
  (0, tslib_1.__exportStar)(require("./error/error.util"), exports);
42
22
  const errorMode_1 = require("./error/errorMode");
43
23
  Object.defineProperty(exports, "ErrorMode", { enumerable: true, get: function () { return errorMode_1.ErrorMode; } });
44
- const http_error_1 = require("./error/http.error");
45
- Object.defineProperty(exports, "HttpError", { enumerable: true, get: function () { return http_error_1.HttpError; } });
46
- const try_1 = require("./error/try");
47
- Object.defineProperty(exports, "_try", { enumerable: true, get: function () { return try_1._try; } });
48
- Object.defineProperty(exports, "pTry", { enumerable: true, get: function () { return try_1.pTry; } });
24
+ (0, tslib_1.__exportStar)(require("./error/http.error"), exports);
25
+ (0, tslib_1.__exportStar)(require("./error/try"), exports);
49
26
  const tryCatch_1 = require("./error/tryCatch");
50
27
  Object.defineProperty(exports, "_TryCatch", { enumerable: true, get: function () { return tryCatch_1._TryCatch; } });
51
28
  Object.defineProperty(exports, "_tryCatch", { enumerable: true, get: function () { return tryCatch_1._tryCatch; } });
52
- const generateJsonSchemaFromData_1 = require("./json-schema/from-data/generateJsonSchemaFromData");
53
- Object.defineProperty(exports, "generateJsonSchemaFromData", { enumerable: true, get: function () { return generateJsonSchemaFromData_1.generateJsonSchemaFromData; } });
54
- const jsonSchema_cnst_1 = require("./json-schema/jsonSchema.cnst");
55
- Object.defineProperty(exports, "JSON_SCHEMA_ORDER", { enumerable: true, get: function () { return jsonSchema_cnst_1.JSON_SCHEMA_ORDER; } });
56
- const jsonSchema_util_1 = require("./json-schema/jsonSchema.util");
57
- Object.defineProperty(exports, "mergeJsonSchemaObjects", { enumerable: true, get: function () { return jsonSchema_util_1.mergeJsonSchemaObjects; } });
29
+ (0, tslib_1.__exportStar)(require("./json-schema/from-data/generateJsonSchemaFromData"), exports);
30
+ (0, tslib_1.__exportStar)(require("./json-schema/jsonSchema.cnst"), exports);
31
+ (0, tslib_1.__exportStar)(require("./json-schema/jsonSchema.util"), exports);
58
32
  const jsonSchemaBuilder_1 = require("./json-schema/jsonSchemaBuilder");
59
33
  Object.defineProperty(exports, "jsonSchema", { enumerable: true, get: function () { return jsonSchemaBuilder_1.jsonSchema; } });
60
34
  Object.defineProperty(exports, "JsonSchemaAnyBuilder", { enumerable: true, get: function () { return jsonSchemaBuilder_1.JsonSchemaAnyBuilder; } });
@@ -82,15 +56,14 @@ Object.defineProperty(exports, "pRetry", { enumerable: true, get: function () {
82
56
  (0, tslib_1.__exportStar)(require("./promise/pState"), exports);
83
57
  const pTimeout_1 = require("./promise/pTimeout");
84
58
  Object.defineProperty(exports, "pTimeout", { enumerable: true, get: function () { return pTimeout_1.pTimeout; } });
59
+ Object.defineProperty(exports, "pTimeoutFn", { enumerable: true, get: function () { return pTimeout_1.pTimeoutFn; } });
85
60
  (0, tslib_1.__exportStar)(require("./promise/pTuple"), exports);
86
61
  (0, tslib_1.__exportStar)(require("./string/case"), exports);
87
62
  (0, tslib_1.__exportStar)(require("./string/json.util"), exports);
88
63
  (0, tslib_1.__exportStar)(require("./string/string.util"), exports);
89
64
  const stringifyAny_1 = require("./string/stringifyAny");
90
65
  Object.defineProperty(exports, "_stringifyAny", { enumerable: true, get: function () { return stringifyAny_1._stringifyAny; } });
91
- const time_util_1 = require("./time/time.util");
92
- Object.defineProperty(exports, "_ms", { enumerable: true, get: function () { return time_util_1._ms; } });
93
- Object.defineProperty(exports, "_since", { enumerable: true, get: function () { return time_util_1._since; } });
66
+ (0, tslib_1.__exportStar)(require("./time/time.util"), exports);
94
67
  const types_1 = require("./types");
95
68
  Object.defineProperty(exports, "END", { enumerable: true, get: function () { return types_1.END; } });
96
69
  Object.defineProperty(exports, "SKIP", { enumerable: true, get: function () { return types_1.SKIP; } });
@@ -102,11 +75,7 @@ Object.defineProperty(exports, "_passthroughPredicate", { enumerable: true, get:
102
75
  Object.defineProperty(exports, "_passUndefinedMapper", { enumerable: true, get: function () { return types_1._passUndefinedMapper; } });
103
76
  Object.defineProperty(exports, "_stringMapEntries", { enumerable: true, get: function () { return types_1._stringMapEntries; } });
104
77
  Object.defineProperty(exports, "_stringMapValues", { enumerable: true, get: function () { return types_1._stringMapValues; } });
105
- const size_util_1 = require("./unit/size.util");
106
- Object.defineProperty(exports, "_gb", { enumerable: true, get: function () { return size_util_1._gb; } });
107
- Object.defineProperty(exports, "_hb", { enumerable: true, get: function () { return size_util_1._hb; } });
108
- Object.defineProperty(exports, "_kb", { enumerable: true, get: function () { return size_util_1._kb; } });
109
- Object.defineProperty(exports, "_mb", { enumerable: true, get: function () { return size_util_1._mb; } });
78
+ (0, tslib_1.__exportStar)(require("./unit/size.util"), exports);
110
79
  const is_1 = require("./vendor/is");
111
80
  Object.defineProperty(exports, "is", { enumerable: true, get: function () { return is_1.is; } });
112
81
  const commonLogger_1 = require("./log/commonLogger");
@@ -116,8 +85,7 @@ Object.defineProperty(exports, "commonLogLevelNumber", { enumerable: true, get:
116
85
  Object.defineProperty(exports, "commonLoggerPipe", { enumerable: true, get: function () { return commonLogger_1.commonLoggerPipe; } });
117
86
  Object.defineProperty(exports, "commonLoggerPrefix", { enumerable: true, get: function () { return commonLogger_1.commonLoggerPrefix; } });
118
87
  Object.defineProperty(exports, "commonLoggerCreate", { enumerable: true, get: function () { return commonLogger_1.commonLoggerCreate; } });
119
- const safeJsonStringify_1 = require("./string/safeJsonStringify");
120
- Object.defineProperty(exports, "_safeJsonStringify", { enumerable: true, get: function () { return safeJsonStringify_1._safeJsonStringify; } });
88
+ (0, tslib_1.__exportStar)(require("./string/safeJsonStringify"), exports);
121
89
  const pQueue_1 = require("./promise/pQueue");
122
90
  Object.defineProperty(exports, "PQueue", { enumerable: true, get: function () { return pQueue_1.PQueue; } });
123
91
  (0, tslib_1.__exportStar)(require("./seq/seq"), exports);
@@ -1,5 +1,10 @@
1
- import { CommonLogger } from '..';
1
+ import { AnyFunction, CommonLogger } from '..';
2
2
  export interface PRetryOptions {
3
+ /**
4
+ * If set - will be included in the error message.
5
+ * Can be used to identify the place in the code that failed.
6
+ */
7
+ name?: string;
3
8
  /**
4
9
  * How many attempts to try.
5
10
  * First attempt is not a retry, but "initial try". It still counts.
@@ -62,4 +67,4 @@ export interface PRetryOptions {
62
67
  * Returns a Function (!), enhanced with retry capabilities.
63
68
  * Implements "Exponential back-off strategy" by multiplying the delay by `delayMultiplier` with each try.
64
69
  */
65
- export declare function pRetry<T extends Function>(fn: T, opt?: PRetryOptions): T;
70
+ export declare function pRetry<T extends AnyFunction>(fn: T, opt?: PRetryOptions): T;
@@ -8,7 +8,7 @@ const __1 = require("..");
8
8
  */
9
9
  // eslint-disable-next-line @typescript-eslint/ban-types
10
10
  function pRetry(fn, opt = {}) {
11
- const { maxAttempts = 4, delay: initialDelay = 1000, delayMultiplier = 2, predicate, logger = console, } = opt;
11
+ const { maxAttempts = 4, delay: initialDelay = 1000, delayMultiplier = 2, predicate, logger = console, name = fn.name, } = opt;
12
12
  let { logFirstAttempt = false, logRetries = true, logFailures = false, logSuccess = false } = opt;
13
13
  if (opt.logAll) {
14
14
  logFirstAttempt = logRetries = logFailures = true;
@@ -16,7 +16,7 @@ function pRetry(fn, opt = {}) {
16
16
  if (opt.logNone) {
17
17
  logSuccess = logFirstAttempt = logRetries = logFailures = false;
18
18
  }
19
- const fname = ['pRetry', fn.name].filter(Boolean).join('.');
19
+ const fname = ['pRetry', name].filter(Boolean).join('.');
20
20
  return async function (...args) {
21
21
  let delay = initialDelay;
22
22
  let attempt = 0;
@@ -36,9 +36,9 @@ function pRetry(fn, opt = {}) {
36
36
  }
37
37
  catch (err) {
38
38
  if (logFailures) {
39
- logger.warn(`${fname} attempt #${attempt} error in ${(0, __1._since)(started)}:\n${(0, __1._stringifyAny)(err, {
39
+ logger.warn(`${fname} attempt #${attempt} error in ${(0, __1._since)(started)}:`, (0, __1._stringifyAny)(err, {
40
40
  includeErrorData: true,
41
- })}`);
41
+ }));
42
42
  }
43
43
  if (attempt >= maxAttempts || (predicate && !predicate(err, attempt, maxAttempts))) {
44
44
  // Give up
@@ -1,4 +1,7 @@
1
+ import { AppError } from '../error/app.error';
1
2
  import { AnyFunction } from '../types';
3
+ export declare class TimeoutError extends AppError {
4
+ }
2
5
  export interface PTimeoutOptions {
3
6
  /**
4
7
  * Timeout in milliseconds.
@@ -20,4 +23,10 @@ export interface PTimeoutOptions {
20
23
  * Throws an Error if the Function is not resolved in a certain time.
21
24
  * If the Function rejects - passes this rejection further.
22
25
  */
23
- export declare function pTimeout<T extends AnyFunction>(fn: T, opt: PTimeoutOptions): T;
26
+ export declare function pTimeoutFn<T extends AnyFunction>(fn: T, opt: PTimeoutOptions): T;
27
+ /**
28
+ * Decorates a Function with a timeout and immediately calls it.
29
+ * Throws an Error if the Function is not resolved in a certain time.
30
+ * If the Function rejects - passes this rejection further.
31
+ */
32
+ export declare function pTimeout<T>(promise: Promise<T>, opt: PTimeoutOptions): Promise<T>;
@@ -1,41 +1,55 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.pTimeout = void 0;
3
+ exports.pTimeout = exports.pTimeoutFn = exports.TimeoutError = void 0;
4
+ const app_error_1 = require("../error/app.error");
5
+ class TimeoutError extends app_error_1.AppError {
6
+ }
7
+ exports.TimeoutError = TimeoutError;
4
8
  /**
5
9
  * Decorates a Function with a timeout.
6
10
  * Throws an Error if the Function is not resolved in a certain time.
7
11
  * If the Function rejects - passes this rejection further.
8
12
  */
9
- function pTimeout(fn, opt) {
10
- // const fname = fn.name || 'function'
13
+ function pTimeoutFn(fn, opt) {
14
+ opt.name || (opt.name = fn.name);
15
+ return async function pTimeoutInternalFn(...args) {
16
+ return await pTimeout(fn.apply(this, args), opt);
17
+ };
18
+ }
19
+ exports.pTimeoutFn = pTimeoutFn;
20
+ /**
21
+ * Decorates a Function with a timeout and immediately calls it.
22
+ * Throws an Error if the Function is not resolved in a certain time.
23
+ * If the Function rejects - passes this rejection further.
24
+ */
25
+ async function pTimeout(promise, opt) {
26
+ // todo: check how we can automatically infer function name (only applicable to named functions)
11
27
  const { timeout, name, onTimeout } = opt;
12
- return async function (...args) {
13
- // eslint-disable-next-line no-async-promise-executor
14
- return await new Promise(async (resolve, reject) => {
15
- // Prepare the timeout timer
16
- const timer = setTimeout(() => {
17
- if (onTimeout) {
18
- try {
19
- resolve(onTimeout());
20
- }
21
- catch (err) {
22
- reject(err);
23
- }
24
- return;
28
+ // eslint-disable-next-line no-async-promise-executor
29
+ return await new Promise(async (resolve, reject) => {
30
+ // Prepare the timeout timer
31
+ const timer = setTimeout(() => {
32
+ if (onTimeout) {
33
+ try {
34
+ resolve(onTimeout());
25
35
  }
26
- reject(new Error(`"${name || fn.name || 'pTimeout function'}" timed out after ${timeout} ms`));
27
- }, timeout);
28
- // Execute the Function
29
- try {
30
- resolve(await fn.apply(this, args));
31
- }
32
- catch (err) {
33
- reject(err);
34
- }
35
- finally {
36
- clearTimeout(timer);
36
+ catch (err) {
37
+ reject(err);
38
+ }
39
+ return;
37
40
  }
38
- });
39
- };
41
+ reject(new TimeoutError(`"${name || 'pTimeout function'}" timed out after ${timeout} ms`));
42
+ }, timeout);
43
+ // Execute the Function
44
+ try {
45
+ resolve(await promise);
46
+ }
47
+ catch (err) {
48
+ reject(err);
49
+ }
50
+ finally {
51
+ clearTimeout(timer);
52
+ }
53
+ });
40
54
  }
41
55
  exports.pTimeout = pTimeout;
package/dist/seq/seq.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AbortableMapper, AbortablePredicate, END } from '../types';
1
+ import { AbortableAsyncMapper, AbortableAsyncPredicate, AbortableMapper, AbortablePredicate, END } from '../types';
2
2
  /**
3
3
  * Inspired by Kotlin Sequences.
4
4
  * Similar to arrays, but with lazy evaluation, abortable.
@@ -7,14 +7,14 @@ import { AbortableMapper, AbortablePredicate, END } from '../types';
7
7
  *
8
8
  * @experimental
9
9
  */
10
- export declare class Seq<T> implements Iterable<T> {
10
+ export declare class Sequence<T> implements Iterable<T> {
11
11
  private nextFn;
12
12
  private constructor();
13
13
  [Symbol.iterator](): Iterator<T>;
14
- static create<T>(initialValue: T | typeof END, nextFn: AbortableMapper<T, T>): Seq<T>;
15
- static range(minIncl: number, maxExcl: number, step?: number): Seq<number>;
16
- static from<T>(a: Iterable<T>): Seq<T>;
17
- static empty<T = any>(): Seq<T>;
14
+ static create<T>(initialValue: T | typeof END, nextFn: AbortableMapper<T, T>): Sequence<T>;
15
+ static range(minIncl: number, maxExcl: number, step?: number): Sequence<number>;
16
+ static from<T>(a: Iterable<T>): Sequence<T>;
17
+ static empty<T = any>(): Sequence<T>;
18
18
  private currentValue;
19
19
  private sentInitialValue;
20
20
  private i;
@@ -23,8 +23,31 @@ export declare class Seq<T> implements Iterable<T> {
23
23
  some(predicate: AbortablePredicate<T>): boolean;
24
24
  every(predicate: AbortablePredicate<T>): boolean;
25
25
  toArray(): T[];
26
+ forEach(fn: (v: T, i: number) => void): void;
26
27
  }
27
28
  /**
28
29
  * Convenience function to create a Sequence.
29
30
  */
30
- export declare function _seq<T>(initialValue: T | typeof END, nextFn: AbortableMapper<T, T>): Seq<T>;
31
+ export declare function _seq<T>(initialValue: T | typeof END, nextFn: AbortableMapper<T, T>): Sequence<T>;
32
+ /**
33
+ * Experimental.
34
+ * Feasibility to be proven.
35
+ *
36
+ * @experimental
37
+ */
38
+ export declare class AsyncSequence<T> implements AsyncIterable<T> {
39
+ private nextFn;
40
+ private constructor();
41
+ [Symbol.asyncIterator](): AsyncIterator<T>;
42
+ static create<T>(initialValue: T | typeof END, nextFn: AbortableAsyncMapper<T, T>): AsyncSequence<T>;
43
+ static from<T>(a: AsyncIterable<T>): Promise<AsyncSequence<T>>;
44
+ static empty<T = any>(): AsyncSequence<T>;
45
+ private currentValue;
46
+ private sentInitialValue;
47
+ private i;
48
+ next(): Promise<T | typeof END>;
49
+ find(predicate: AbortableAsyncPredicate<T>): Promise<T | undefined>;
50
+ some(predicate: AbortableAsyncPredicate<T>): Promise<boolean>;
51
+ every(predicate: AbortableAsyncPredicate<T>): Promise<boolean>;
52
+ toArray(): Promise<T[]>;
53
+ }