@common.js/p-retry 5.1.2

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.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # @common.js/p-retry
2
+
3
+ The [p-retry](https://www.npmjs.com/package/p-retry) package exported as CommonJS modules.
4
+
5
+ Exported from [p-retry@5.1.2](https://www.npmjs.com/package/p-retry/v/5.1.2) using https://github.com/etienne-martin/common.js.
package/index.d.ts ADDED
@@ -0,0 +1,116 @@
1
+ import {OperationOptions} from 'retry';
2
+
3
+ export class AbortError extends Error {
4
+ readonly name: 'AbortError';
5
+ readonly originalError: Error;
6
+
7
+ /**
8
+ Abort retrying and reject the promise.
9
+
10
+ @param message - An error message or a custom error.
11
+ */
12
+ constructor(message: string | Error);
13
+ }
14
+
15
+ export interface FailedAttemptError extends Error {
16
+ readonly attemptNumber: number;
17
+ readonly retriesLeft: number;
18
+ }
19
+
20
+ export interface Options extends OperationOptions {
21
+ /**
22
+ Callback invoked on each retry. Receives the error thrown by `input` as the first argument with properties `attemptNumber` and `retriesLeft` which indicate the current attempt number and the number of attempts left, respectively.
23
+
24
+ The `onFailedAttempt` function can return a promise. For example, to add a [delay](https://github.com/sindresorhus/delay):
25
+
26
+ ```
27
+ import pRetry from 'p-retry';
28
+ import delay from 'delay';
29
+
30
+ const run = async () => { ... };
31
+
32
+ const result = await pRetry(run, {
33
+ onFailedAttempt: async error => {
34
+ console.log('Waiting for 1 second before retrying');
35
+ await delay(1000);
36
+ }
37
+ });
38
+ ```
39
+
40
+ If the `onFailedAttempt` function throws, all retries will be aborted and the original promise will reject with the thrown error.
41
+ */
42
+ readonly onFailedAttempt?: (error: FailedAttemptError) => void | Promise<void>;
43
+
44
+ /**
45
+ You can abort retrying using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
46
+
47
+ When `AbortController.abort(reason)` is called, the promise will be rejected with `reason` as the error message.
48
+
49
+ *Requires Node.js 16 or later.*
50
+
51
+ ```
52
+ import pRetry from 'p-retry';
53
+
54
+ const run = async () => { … };
55
+ const controller = new AbortController();
56
+
57
+ cancelButton.addEventListener('click', () => {
58
+ controller.abort('User clicked cancel button');
59
+ });
60
+
61
+ try {
62
+ await pRetry(run, {signal: controller.signal});
63
+ } catch (error) {
64
+ console.log(error.message);
65
+ //=> 'User clicked cancel button'
66
+ }
67
+ ```
68
+ */
69
+ readonly signal?: AbortSignal;
70
+ }
71
+
72
+ /**
73
+ Returns a `Promise` that is fulfilled when calling `input` returns a fulfilled promise. If calling `input` returns a rejected promise, `input` is called again until the max retries are reached, it then rejects with the last rejection reason.
74
+
75
+ Does not retry on most `TypeErrors`, with the exception of network errors. This is done on a best case basis as different browsers have different [messages](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful) to indicate this.
76
+ See [whatwg/fetch#526 (comment)](https://github.com/whatwg/fetch/issues/526#issuecomment-554604080)
77
+
78
+ @param input - Receives the number of attempts as the first argument and is expected to return a `Promise` or any value.
79
+ @param options - Options are passed to the [`retry`](https://github.com/tim-kos/node-retry#retryoperationoptions) module.
80
+
81
+ @example
82
+ ```
83
+ import pRetry, {AbortError} from 'p-retry';
84
+ import fetch from 'node-fetch';
85
+
86
+ const run = async () => {
87
+ const response = await fetch('https://sindresorhus.com/unicorn');
88
+
89
+ // Abort retrying if the resource doesn't exist
90
+ if (response.status === 404) {
91
+ throw new AbortError(response.statusText);
92
+ }
93
+
94
+ return response.blob();
95
+ };
96
+
97
+ console.log(await pRetry(run, {retries: 5}));
98
+
99
+ // With the `onFailedAttempt` option:
100
+ const result = await pRetry(run, {
101
+ onFailedAttempt: error => {
102
+ console.log(`Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left.`);
103
+ // 1st request => Attempt 1 failed. There are 4 retries left.
104
+ // 2nd request => Attempt 2 failed. There are 3 retries left.
105
+ // …
106
+ },
107
+ retries: 5
108
+ });
109
+
110
+ console.log(result);
111
+ ```
112
+ */
113
+ export default function pRetry<T>(
114
+ input: (attemptCount: number) => PromiseLike<T> | T,
115
+ options?: Options
116
+ ): Promise<T>;
package/index.js ADDED
@@ -0,0 +1,481 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ AbortError: function() {
13
+ return AbortError;
14
+ },
15
+ default: function() {
16
+ return pRetry;
17
+ }
18
+ });
19
+ var _retry = /*#__PURE__*/ _interopRequireDefault(require("retry"));
20
+ function _assertThisInitialized(self) {
21
+ if (self === void 0) {
22
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
23
+ }
24
+ return self;
25
+ }
26
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
27
+ try {
28
+ var info = gen[key](arg);
29
+ var value = info.value;
30
+ } catch (error) {
31
+ reject(error);
32
+ return;
33
+ }
34
+ if (info.done) {
35
+ resolve(value);
36
+ } else {
37
+ Promise.resolve(value).then(_next, _throw);
38
+ }
39
+ }
40
+ function _asyncToGenerator(fn) {
41
+ return function() {
42
+ var self = this, args = arguments;
43
+ return new Promise(function(resolve, reject) {
44
+ var gen = fn.apply(self, args);
45
+ function _next(value) {
46
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
47
+ }
48
+ function _throw(err) {
49
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
50
+ }
51
+ _next(undefined);
52
+ });
53
+ };
54
+ }
55
+ function _classCallCheck(instance, Constructor) {
56
+ if (!(instance instanceof Constructor)) {
57
+ throw new TypeError("Cannot call a class as a function");
58
+ }
59
+ }
60
+ function isNativeReflectConstruct() {
61
+ if (typeof Reflect === "undefined" || !Reflect.construct) return false;
62
+ if (Reflect.construct.sham) return false;
63
+ if (typeof Proxy === "function") return true;
64
+ try {
65
+ Date.prototype.toString.call(Reflect.construct(Date, [], function() {}));
66
+ return true;
67
+ } catch (e) {
68
+ return false;
69
+ }
70
+ }
71
+ function _construct(Parent, args, Class) {
72
+ if (isNativeReflectConstruct()) {
73
+ _construct = Reflect.construct;
74
+ } else {
75
+ _construct = function _construct(Parent, args, Class) {
76
+ var a = [
77
+ null
78
+ ];
79
+ a.push.apply(a, args);
80
+ var Constructor = Function.bind.apply(Parent, a);
81
+ var instance = new Constructor();
82
+ if (Class) _setPrototypeOf(instance, Class.prototype);
83
+ return instance;
84
+ };
85
+ }
86
+ return _construct.apply(null, arguments);
87
+ }
88
+ function _defineProperty(obj, key, value) {
89
+ if (key in obj) {
90
+ Object.defineProperty(obj, key, {
91
+ value: value,
92
+ enumerable: true,
93
+ configurable: true,
94
+ writable: true
95
+ });
96
+ } else {
97
+ obj[key] = value;
98
+ }
99
+ return obj;
100
+ }
101
+ function _getPrototypeOf(o) {
102
+ _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
103
+ return o.__proto__ || Object.getPrototypeOf(o);
104
+ };
105
+ return _getPrototypeOf(o);
106
+ }
107
+ function _inherits(subClass, superClass) {
108
+ if (typeof superClass !== "function" && superClass !== null) {
109
+ throw new TypeError("Super expression must either be null or a function");
110
+ }
111
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
112
+ constructor: {
113
+ value: subClass,
114
+ writable: true,
115
+ configurable: true
116
+ }
117
+ });
118
+ if (superClass) _setPrototypeOf(subClass, superClass);
119
+ }
120
+ function _instanceof(left, right) {
121
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
122
+ return !!right[Symbol.hasInstance](left);
123
+ } else {
124
+ return left instanceof right;
125
+ }
126
+ }
127
+ function _interopRequireDefault(obj) {
128
+ return obj && obj.__esModule ? obj : {
129
+ default: obj
130
+ };
131
+ }
132
+ function _isNativeFunction(fn) {
133
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
134
+ }
135
+ function _objectSpread(target) {
136
+ for(var i = 1; i < arguments.length; i++){
137
+ var source = arguments[i] != null ? arguments[i] : {};
138
+ var ownKeys = Object.keys(source);
139
+ if (typeof Object.getOwnPropertySymbols === "function") {
140
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
141
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
142
+ }));
143
+ }
144
+ ownKeys.forEach(function(key) {
145
+ _defineProperty(target, key, source[key]);
146
+ });
147
+ }
148
+ return target;
149
+ }
150
+ function _possibleConstructorReturn(self, call) {
151
+ if (call && (_typeof(call) === "object" || typeof call === "function")) {
152
+ return call;
153
+ }
154
+ return _assertThisInitialized(self);
155
+ }
156
+ function _setPrototypeOf(o, p) {
157
+ _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
158
+ o.__proto__ = p;
159
+ return o;
160
+ };
161
+ return _setPrototypeOf(o, p);
162
+ }
163
+ var _typeof = function(obj) {
164
+ "@swc/helpers - typeof";
165
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
166
+ };
167
+ function _wrapNativeSuper(Class) {
168
+ var _cache = typeof Map === "function" ? new Map() : undefined;
169
+ _wrapNativeSuper = function _wrapNativeSuper(Class) {
170
+ if (Class === null || !_isNativeFunction(Class)) return Class;
171
+ if (typeof Class !== "function") {
172
+ throw new TypeError("Super expression must either be null or a function");
173
+ }
174
+ if (typeof _cache !== "undefined") {
175
+ if (_cache.has(Class)) return _cache.get(Class);
176
+ _cache.set(Class, Wrapper);
177
+ }
178
+ function Wrapper() {
179
+ return _construct(Class, arguments, _getPrototypeOf(this).constructor);
180
+ }
181
+ Wrapper.prototype = Object.create(Class.prototype, {
182
+ constructor: {
183
+ value: Wrapper,
184
+ enumerable: false,
185
+ writable: true,
186
+ configurable: true
187
+ }
188
+ });
189
+ return _setPrototypeOf(Wrapper, Class);
190
+ };
191
+ return _wrapNativeSuper(Class);
192
+ }
193
+ function _isNativeReflectConstruct() {
194
+ if (typeof Reflect === "undefined" || !Reflect.construct) return false;
195
+ if (Reflect.construct.sham) return false;
196
+ if (typeof Proxy === "function") return true;
197
+ try {
198
+ Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
199
+ return true;
200
+ } catch (e) {
201
+ return false;
202
+ }
203
+ }
204
+ function _createSuper(Derived) {
205
+ var hasNativeReflectConstruct = _isNativeReflectConstruct();
206
+ return function _createSuperInternal() {
207
+ var Super = _getPrototypeOf(Derived), result;
208
+ if (hasNativeReflectConstruct) {
209
+ var NewTarget = _getPrototypeOf(this).constructor;
210
+ result = Reflect.construct(Super, arguments, NewTarget);
211
+ } else {
212
+ result = Super.apply(this, arguments);
213
+ }
214
+ return _possibleConstructorReturn(this, result);
215
+ };
216
+ }
217
+ var __generator = (void 0) && (void 0).__generator || function(thisArg, body) {
218
+ var f, y, t, g, _ = {
219
+ label: 0,
220
+ sent: function() {
221
+ if (t[0] & 1) throw t[1];
222
+ return t[1];
223
+ },
224
+ trys: [],
225
+ ops: []
226
+ };
227
+ return g = {
228
+ next: verb(0),
229
+ "throw": verb(1),
230
+ "return": verb(2)
231
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
232
+ return this;
233
+ }), g;
234
+ function verb(n) {
235
+ return function(v) {
236
+ return step([
237
+ n,
238
+ v
239
+ ]);
240
+ };
241
+ }
242
+ function step(op) {
243
+ if (f) throw new TypeError("Generator is already executing.");
244
+ while(_)try {
245
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
246
+ if (y = 0, t) op = [
247
+ op[0] & 2,
248
+ t.value
249
+ ];
250
+ switch(op[0]){
251
+ case 0:
252
+ case 1:
253
+ t = op;
254
+ break;
255
+ case 4:
256
+ _.label++;
257
+ return {
258
+ value: op[1],
259
+ done: false
260
+ };
261
+ case 5:
262
+ _.label++;
263
+ y = op[1];
264
+ op = [
265
+ 0
266
+ ];
267
+ continue;
268
+ case 7:
269
+ op = _.ops.pop();
270
+ _.trys.pop();
271
+ continue;
272
+ default:
273
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
274
+ _ = 0;
275
+ continue;
276
+ }
277
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
278
+ _.label = op[1];
279
+ break;
280
+ }
281
+ if (op[0] === 6 && _.label < t[1]) {
282
+ _.label = t[1];
283
+ t = op;
284
+ break;
285
+ }
286
+ if (t && _.label < t[2]) {
287
+ _.label = t[2];
288
+ _.ops.push(op);
289
+ break;
290
+ }
291
+ if (t[2]) _.ops.pop();
292
+ _.trys.pop();
293
+ continue;
294
+ }
295
+ op = body.call(thisArg, _);
296
+ } catch (e) {
297
+ op = [
298
+ 6,
299
+ e
300
+ ];
301
+ y = 0;
302
+ } finally{
303
+ f = t = 0;
304
+ }
305
+ if (op[0] & 5) throw op[1];
306
+ return {
307
+ value: op[0] ? op[1] : void 0,
308
+ done: true
309
+ };
310
+ }
311
+ };
312
+ var networkErrorMsgs = new Set([
313
+ "Failed to fetch",
314
+ "NetworkError when attempting to fetch resource.",
315
+ "The Internet connection appears to be offline.",
316
+ "Network request failed",
317
+ "fetch failed"
318
+ ]);
319
+ var AbortError = /*#__PURE__*/ function(Error1) {
320
+ "use strict";
321
+ _inherits(AbortError, Error1);
322
+ var _super = _createSuper(AbortError);
323
+ function AbortError(message) {
324
+ _classCallCheck(this, AbortError);
325
+ var _this;
326
+ _this = _super.call(this);
327
+ if (_instanceof(message, Error)) {
328
+ _this.originalError = message;
329
+ message = message.message;
330
+ } else {
331
+ _this.originalError = new Error(message);
332
+ _this.originalError.stack = _this.stack;
333
+ }
334
+ _this.name = "AbortError";
335
+ _this.message = message;
336
+ return _this;
337
+ }
338
+ return AbortError;
339
+ }(_wrapNativeSuper(Error));
340
+ var decorateErrorWithCounts = function(error, attemptNumber, options) {
341
+ // Minus 1 from attemptNumber because the first attempt does not count as a retry
342
+ var retriesLeft = options.retries - (attemptNumber - 1);
343
+ error.attemptNumber = attemptNumber;
344
+ error.retriesLeft = retriesLeft;
345
+ return error;
346
+ };
347
+ var isNetworkError = function(errorMessage) {
348
+ return networkErrorMsgs.has(errorMessage);
349
+ };
350
+ var getDOMException = function(errorMessage) {
351
+ return globalThis.DOMException === undefined ? new Error(errorMessage) : new DOMException(errorMessage);
352
+ };
353
+ function pRetry(input, options) {
354
+ return _pRetry.apply(this, arguments);
355
+ }
356
+ function _pRetry() {
357
+ _pRetry = _asyncToGenerator(function(input, options) {
358
+ return __generator(this, function(_state) {
359
+ return [
360
+ 2,
361
+ new Promise(function(resolve, reject) {
362
+ options = _objectSpread({
363
+ onFailedAttempt: function onFailedAttempt() {},
364
+ retries: 10
365
+ }, options);
366
+ var operation = _retry.default.operation(options);
367
+ operation.attempt(function() {
368
+ var _ref = _asyncToGenerator(function(attemptNumber) {
369
+ var error, error1;
370
+ return __generator(this, function(_state) {
371
+ switch(_state.label){
372
+ case 0:
373
+ _state.trys.push([
374
+ 0,
375
+ 2,
376
+ ,
377
+ 10
378
+ ]);
379
+ return [
380
+ 4,
381
+ input(attemptNumber)
382
+ ];
383
+ case 1:
384
+ resolve.apply(void 0, [
385
+ _state.sent()
386
+ ]);
387
+ return [
388
+ 3,
389
+ 10
390
+ ];
391
+ case 2:
392
+ error = _state.sent();
393
+ if (!_instanceof(error, Error)) {
394
+ reject(new TypeError('Non-error was thrown: "'.concat(error, '". You should only throw errors.')));
395
+ return [
396
+ 2
397
+ ];
398
+ }
399
+ if (!_instanceof(error, AbortError)) return [
400
+ 3,
401
+ 3
402
+ ];
403
+ operation.stop();
404
+ reject(error.originalError);
405
+ return [
406
+ 3,
407
+ 9
408
+ ];
409
+ case 3:
410
+ if (!(_instanceof(error, TypeError) && !isNetworkError(error.message))) return [
411
+ 3,
412
+ 4
413
+ ];
414
+ operation.stop();
415
+ reject(error);
416
+ return [
417
+ 3,
418
+ 9
419
+ ];
420
+ case 4:
421
+ decorateErrorWithCounts(error, attemptNumber, options);
422
+ _state.label = 5;
423
+ case 5:
424
+ _state.trys.push([
425
+ 5,
426
+ 7,
427
+ ,
428
+ 8
429
+ ]);
430
+ return [
431
+ 4,
432
+ options.onFailedAttempt(error)
433
+ ];
434
+ case 6:
435
+ _state.sent();
436
+ return [
437
+ 3,
438
+ 8
439
+ ];
440
+ case 7:
441
+ error1 = _state.sent();
442
+ reject(error1);
443
+ return [
444
+ 2
445
+ ];
446
+ case 8:
447
+ if (!operation.retry(error)) {
448
+ reject(operation.mainError());
449
+ }
450
+ _state.label = 9;
451
+ case 9:
452
+ return [
453
+ 3,
454
+ 10
455
+ ];
456
+ case 10:
457
+ return [
458
+ 2
459
+ ];
460
+ }
461
+ });
462
+ });
463
+ return function(attemptNumber) {
464
+ return _ref.apply(this, arguments);
465
+ };
466
+ }());
467
+ if (options.signal && !options.signal.aborted) {
468
+ options.signal.addEventListener("abort", function() {
469
+ operation.stop();
470
+ var reason = options.signal.reason === undefined ? getDOMException("The operation was aborted.") : options.signal.reason;
471
+ reject(_instanceof(reason, Error) ? reason : getDOMException(reason));
472
+ }, {
473
+ once: true
474
+ });
475
+ }
476
+ })
477
+ ];
478
+ });
479
+ });
480
+ return _pRetry.apply(this, arguments);
481
+ }
package/license ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "@common.js/p-retry",
3
+ "version": "5.1.2",
4
+ "description": "p-retry package exported as CommonJS modules",
5
+ "license": "MIT",
6
+ "repository": "etienne-martin/common.js",
7
+ "funding": "https://github.com/sponsors/sindresorhus",
8
+ "type": "commonjs",
9
+ "engines": {
10
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
11
+ },
12
+ "scripts": {
13
+ "test": "xo && ava && tsd"
14
+ },
15
+ "files": [
16
+ "index.js",
17
+ "index.d.ts"
18
+ ],
19
+ "dependencies": {
20
+ "@types/retry": "0.12.1",
21
+ "retry": "^0.13.1"
22
+ },
23
+ "devDependencies": {
24
+ "ava": "^4.1.0",
25
+ "delay": "^5.0.0",
26
+ "tsd": "^0.19.1",
27
+ "xo": "^0.48.0"
28
+ },
29
+ "homepage": "https://github.com/etienne-martin/common.js#readme",
30
+ "main": "./index.js"
31
+ }