@common.js/p-limit 4.0.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.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # @common.js/p-limit
2
+
3
+ The [p-limit](https://www.npmjs.com/package/p-limit) package exported as CommonJS modules.
4
+
5
+ Exported from [p-limit@4.0.0](https://www.npmjs.com/package/p-limit/v/4.0.0) using https://github.com/etienne-martin/common.js.
package/index.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ /* eslint-disable @typescript-eslint/member-ordering */
2
+
3
+ export interface LimitFunction {
4
+ /**
5
+ The number of promises that are currently running.
6
+ */
7
+ readonly activeCount: number;
8
+
9
+ /**
10
+ The number of promises that are waiting to run (i.e. their internal `fn` was not called yet).
11
+ */
12
+ readonly pendingCount: number;
13
+
14
+ /**
15
+ Discard pending promises that are waiting to run.
16
+
17
+ This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app.
18
+
19
+ Note: This does not cancel promises that are already running.
20
+ */
21
+ clearQueue: () => void;
22
+
23
+ /**
24
+ @param fn - Promise-returning/async function.
25
+ @param arguments - Any arguments to pass through to `fn`. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions.
26
+ @returns The promise returned by calling `fn(...arguments)`.
27
+ */
28
+ <Arguments extends unknown[], ReturnType>(
29
+ fn: (...arguments: Arguments) => PromiseLike<ReturnType> | ReturnType,
30
+ ...arguments: Arguments
31
+ ): Promise<ReturnType>;
32
+ }
33
+
34
+ /**
35
+ Run multiple promise-returning & async functions with limited concurrency.
36
+
37
+ @param concurrency - Concurrency limit. Minimum: `1`.
38
+ @returns A `limit` function.
39
+ */
40
+ export default function pLimit(concurrency: number): LimitFunction;
package/index.js ADDED
@@ -0,0 +1,282 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "default", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return pLimit;
9
+ }
10
+ });
11
+ var _yoctoQueue = /*#__PURE__*/ _interopRequireDefault(require("yocto-queue"));
12
+ function _arrayLikeToArray(arr, len) {
13
+ if (len == null || len > arr.length) len = arr.length;
14
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
15
+ return arr2;
16
+ }
17
+ function _arrayWithoutHoles(arr) {
18
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
19
+ }
20
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
21
+ try {
22
+ var info = gen[key](arg);
23
+ var value = info.value;
24
+ } catch (error) {
25
+ reject(error);
26
+ return;
27
+ }
28
+ if (info.done) {
29
+ resolve(value);
30
+ } else {
31
+ Promise.resolve(value).then(_next, _throw);
32
+ }
33
+ }
34
+ function _asyncToGenerator(fn) {
35
+ return function() {
36
+ var self = this, args = arguments;
37
+ return new Promise(function(resolve, reject) {
38
+ var gen = fn.apply(self, args);
39
+ function _next(value) {
40
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
41
+ }
42
+ function _throw(err) {
43
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
44
+ }
45
+ _next(undefined);
46
+ });
47
+ };
48
+ }
49
+ function _interopRequireDefault(obj) {
50
+ return obj && obj.__esModule ? obj : {
51
+ default: obj
52
+ };
53
+ }
54
+ function _iterableToArray(iter) {
55
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
56
+ }
57
+ function _nonIterableSpread() {
58
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
59
+ }
60
+ function _toConsumableArray(arr) {
61
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
62
+ }
63
+ function _unsupportedIterableToArray(o, minLen) {
64
+ if (!o) return;
65
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
66
+ var n = Object.prototype.toString.call(o).slice(8, -1);
67
+ if (n === "Object" && o.constructor) n = o.constructor.name;
68
+ if (n === "Map" || n === "Set") return Array.from(n);
69
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
70
+ }
71
+ var __generator = (void 0) && (void 0).__generator || function(thisArg, body) {
72
+ var f, y, t, g, _ = {
73
+ label: 0,
74
+ sent: function() {
75
+ if (t[0] & 1) throw t[1];
76
+ return t[1];
77
+ },
78
+ trys: [],
79
+ ops: []
80
+ };
81
+ return g = {
82
+ next: verb(0),
83
+ "throw": verb(1),
84
+ "return": verb(2)
85
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
86
+ return this;
87
+ }), g;
88
+ function verb(n) {
89
+ return function(v) {
90
+ return step([
91
+ n,
92
+ v
93
+ ]);
94
+ };
95
+ }
96
+ function step(op) {
97
+ if (f) throw new TypeError("Generator is already executing.");
98
+ while(_)try {
99
+ 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;
100
+ if (y = 0, t) op = [
101
+ op[0] & 2,
102
+ t.value
103
+ ];
104
+ switch(op[0]){
105
+ case 0:
106
+ case 1:
107
+ t = op;
108
+ break;
109
+ case 4:
110
+ _.label++;
111
+ return {
112
+ value: op[1],
113
+ done: false
114
+ };
115
+ case 5:
116
+ _.label++;
117
+ y = op[1];
118
+ op = [
119
+ 0
120
+ ];
121
+ continue;
122
+ case 7:
123
+ op = _.ops.pop();
124
+ _.trys.pop();
125
+ continue;
126
+ default:
127
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
128
+ _ = 0;
129
+ continue;
130
+ }
131
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
132
+ _.label = op[1];
133
+ break;
134
+ }
135
+ if (op[0] === 6 && _.label < t[1]) {
136
+ _.label = t[1];
137
+ t = op;
138
+ break;
139
+ }
140
+ if (t && _.label < t[2]) {
141
+ _.label = t[2];
142
+ _.ops.push(op);
143
+ break;
144
+ }
145
+ if (t[2]) _.ops.pop();
146
+ _.trys.pop();
147
+ continue;
148
+ }
149
+ op = body.call(thisArg, _);
150
+ } catch (e) {
151
+ op = [
152
+ 6,
153
+ e
154
+ ];
155
+ y = 0;
156
+ } finally{
157
+ f = t = 0;
158
+ }
159
+ if (op[0] & 5) throw op[1];
160
+ return {
161
+ value: op[0] ? op[1] : void 0,
162
+ done: true
163
+ };
164
+ }
165
+ };
166
+ function pLimit(concurrency) {
167
+ if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {
168
+ throw new TypeError("Expected `concurrency` to be a number from 1 and up");
169
+ }
170
+ var queue = new _yoctoQueue.default();
171
+ var activeCount = 0;
172
+ var next = function() {
173
+ activeCount--;
174
+ if (queue.size > 0) {
175
+ queue.dequeue()();
176
+ }
177
+ };
178
+ var run = function() {
179
+ var _ref = _asyncToGenerator(function(fn, resolve, args) {
180
+ var result, e;
181
+ return __generator(this, function(_state) {
182
+ switch(_state.label){
183
+ case 0:
184
+ activeCount++;
185
+ result = _asyncToGenerator(function() {
186
+ return __generator(this, function(_state) {
187
+ return [
188
+ 2,
189
+ fn.apply(void 0, _toConsumableArray(args))
190
+ ];
191
+ });
192
+ })();
193
+ resolve(result);
194
+ _state.label = 1;
195
+ case 1:
196
+ _state.trys.push([
197
+ 1,
198
+ 3,
199
+ ,
200
+ 4
201
+ ]);
202
+ return [
203
+ 4,
204
+ result
205
+ ];
206
+ case 2:
207
+ _state.sent();
208
+ return [
209
+ 3,
210
+ 4
211
+ ];
212
+ case 3:
213
+ e = _state.sent();
214
+ return [
215
+ 3,
216
+ 4
217
+ ];
218
+ case 4:
219
+ next();
220
+ return [
221
+ 2
222
+ ];
223
+ }
224
+ });
225
+ });
226
+ return function run(fn, resolve, args) {
227
+ return _ref.apply(this, arguments);
228
+ };
229
+ }();
230
+ var enqueue = function(fn, resolve, args) {
231
+ queue.enqueue(run.bind(undefined, fn, resolve, args));
232
+ _asyncToGenerator(function() {
233
+ return __generator(this, function(_state) {
234
+ switch(_state.label){
235
+ case 0:
236
+ // This function needs to wait until the next microtask before comparing
237
+ // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
238
+ // when the run function is dequeued and called. The comparison in the if-statement
239
+ // needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
240
+ return [
241
+ 4,
242
+ Promise.resolve()
243
+ ];
244
+ case 1:
245
+ _state.sent();
246
+ if (activeCount < concurrency && queue.size > 0) {
247
+ queue.dequeue()();
248
+ }
249
+ return [
250
+ 2
251
+ ];
252
+ }
253
+ });
254
+ })();
255
+ };
256
+ var generator = function(fn) {
257
+ for(var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
258
+ args[_key - 1] = arguments[_key];
259
+ }
260
+ return new Promise(function(resolve) {
261
+ enqueue(fn, resolve, args);
262
+ });
263
+ };
264
+ Object.defineProperties(generator, {
265
+ activeCount: {
266
+ get: function() {
267
+ return activeCount;
268
+ }
269
+ },
270
+ pendingCount: {
271
+ get: function() {
272
+ return queue.size;
273
+ }
274
+ },
275
+ clearQueue: {
276
+ value: function() {
277
+ queue.clear();
278
+ }
279
+ }
280
+ });
281
+ return generator;
282
+ }
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,33 @@
1
+ {
2
+ "name": "@common.js/p-limit",
3
+ "version": "4.0.0",
4
+ "description": "Run multiple promise-returning & async functions with limited concurrency",
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
+ "@common.js/yocto-queue": "^1.0.0"
21
+ },
22
+ "devDependencies": {
23
+ "ava": "^3.15.0",
24
+ "delay": "^5.0.0",
25
+ "in-range": "^3.0.0",
26
+ "random-int": "^3.0.0",
27
+ "time-span": "^5.0.0",
28
+ "tsd": "^0.17.0",
29
+ "xo": "^0.44.0"
30
+ },
31
+ "homepage": "https://github.com/etienne-martin/common.js#readme",
32
+ "main": "./index.js"
33
+ }
package/readme.md ADDED
@@ -0,0 +1,99 @@
1
+ # p-limit
2
+
3
+ > Run multiple promise-returning & async functions with limited concurrency
4
+
5
+ ## Install
6
+
7
+ ```
8
+ $ npm install p-limit
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```js
14
+ import pLimit from 'p-limit';
15
+
16
+ const limit = pLimit(1);
17
+
18
+ const input = [
19
+ limit(() => fetchSomething('foo')),
20
+ limit(() => fetchSomething('bar')),
21
+ limit(() => doSomething())
22
+ ];
23
+
24
+ // Only one promise is run at once
25
+ const result = await Promise.all(input);
26
+ console.log(result);
27
+ ```
28
+
29
+ ## API
30
+
31
+ ### pLimit(concurrency)
32
+
33
+ Returns a `limit` function.
34
+
35
+ #### concurrency
36
+
37
+ Type: `number`\
38
+ Minimum: `1`\
39
+ Default: `Infinity`
40
+
41
+ Concurrency limit.
42
+
43
+ ### limit(fn, ...args)
44
+
45
+ Returns the promise returned by calling `fn(...args)`.
46
+
47
+ #### fn
48
+
49
+ Type: `Function`
50
+
51
+ Promise-returning/async function.
52
+
53
+ #### args
54
+
55
+ Any arguments to pass through to `fn`.
56
+
57
+ Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions.
58
+
59
+ ### limit.activeCount
60
+
61
+ The number of promises that are currently running.
62
+
63
+ ### limit.pendingCount
64
+
65
+ The number of promises that are waiting to run (i.e. their internal `fn` was not called yet).
66
+
67
+ ### limit.clearQueue()
68
+
69
+ Discard pending promises that are waiting to run.
70
+
71
+ This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app.
72
+
73
+ Note: This does not cancel promises that are already running.
74
+
75
+ ## FAQ
76
+
77
+ ### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package?
78
+
79
+ This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue.
80
+
81
+ ## Related
82
+
83
+ - [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control
84
+ - [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions
85
+ - [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions
86
+ - [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency
87
+ - [More…](https://github.com/sindresorhus/promise-fun)
88
+
89
+ ---
90
+
91
+ <div align="center">
92
+ <b>
93
+ <a href="https://tidelift.com/subscription/pkg/npm-p-limit?utm_source=npm-p-limit&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
94
+ </b>
95
+ <br>
96
+ <sub>
97
+ Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
98
+ </sub>
99
+ </div>