UNPKG

161 kBJavaScriptView Raw
1/**
2 * This file contains the full Bottleneck library (MIT) compiled to ES5.
3 * https://github.com/SGrondin/bottleneck
4 * It also contains the regenerator-runtime (MIT), necessary for Babel-generated ES5 code to execute promise and async/await code.
5 * See the following link for Copyright and License information:
6 * https://github.com/facebook/regenerator/blob/master/packages/regenerator-runtime/runtime.js
7 */
8(function (global, factory) {
9 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
10 typeof define === 'function' && define.amd ? define(factory) :
11 (global.Bottleneck = factory());
12}(this, (function () { 'use strict';
13
14 var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
15
16 function createCommonjsModule(fn, module) {
17 return module = { exports: {} }, fn(module, module.exports), module.exports;
18 }
19
20 function getCjsExportFromNamespace (n) {
21 return n && n.default || n;
22 }
23
24 var runtime = createCommonjsModule(function (module) {
25 /**
26 * Copyright (c) 2014-present, Facebook, Inc.
27 *
28 * This source code is licensed under the MIT license found in the
29 * LICENSE file in the root directory of this source tree.
30 */
31
32 !(function(global) {
33
34 var Op = Object.prototype;
35 var hasOwn = Op.hasOwnProperty;
36 var undefined; // More compressible than void 0.
37 var $Symbol = typeof Symbol === "function" ? Symbol : {};
38 var iteratorSymbol = $Symbol.iterator || "@@iterator";
39 var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
40 var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
41 var runtime = global.regeneratorRuntime;
42 if (runtime) {
43 {
44 // If regeneratorRuntime is defined globally and we're in a module,
45 // make the exports object identical to regeneratorRuntime.
46 module.exports = runtime;
47 }
48 // Don't bother evaluating the rest of this file if the runtime was
49 // already defined globally.
50 return;
51 }
52
53 // Define the runtime globally (as expected by generated code) as either
54 // module.exports (if we're in a module) or a new, empty object.
55 runtime = global.regeneratorRuntime = module.exports;
56
57 function wrap(innerFn, outerFn, self, tryLocsList) {
58 // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
59 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
60 var generator = Object.create(protoGenerator.prototype);
61 var context = new Context(tryLocsList || []);
62
63 // The ._invoke method unifies the implementations of the .next,
64 // .throw, and .return methods.
65 generator._invoke = makeInvokeMethod(innerFn, self, context);
66
67 return generator;
68 }
69 runtime.wrap = wrap;
70
71 // Try/catch helper to minimize deoptimizations. Returns a completion
72 // record like context.tryEntries[i].completion. This interface could
73 // have been (and was previously) designed to take a closure to be
74 // invoked without arguments, but in all the cases we care about we
75 // already have an existing method we want to call, so there's no need
76 // to create a new function object. We can even get away with assuming
77 // the method takes exactly one argument, since that happens to be true
78 // in every case, so we don't have to touch the arguments object. The
79 // only additional allocation required is the completion record, which
80 // has a stable shape and so hopefully should be cheap to allocate.
81 function tryCatch(fn, obj, arg) {
82 try {
83 return { type: "normal", arg: fn.call(obj, arg) };
84 } catch (err) {
85 return { type: "throw", arg: err };
86 }
87 }
88
89 var GenStateSuspendedStart = "suspendedStart";
90 var GenStateSuspendedYield = "suspendedYield";
91 var GenStateExecuting = "executing";
92 var GenStateCompleted = "completed";
93
94 // Returning this object from the innerFn has the same effect as
95 // breaking out of the dispatch switch statement.
96 var ContinueSentinel = {};
97
98 // Dummy constructor functions that we use as the .constructor and
99 // .constructor.prototype properties for functions that return Generator
100 // objects. For full spec compliance, you may wish to configure your
101 // minifier not to mangle the names of these two functions.
102 function Generator() {}
103 function GeneratorFunction() {}
104 function GeneratorFunctionPrototype() {}
105
106 // This is a polyfill for %IteratorPrototype% for environments that
107 // don't natively support it.
108 var IteratorPrototype = {};
109 IteratorPrototype[iteratorSymbol] = function () {
110 return this;
111 };
112
113 var getProto = Object.getPrototypeOf;
114 var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
115 if (NativeIteratorPrototype &&
116 NativeIteratorPrototype !== Op &&
117 hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
118 // This environment has a native %IteratorPrototype%; use it instead
119 // of the polyfill.
120 IteratorPrototype = NativeIteratorPrototype;
121 }
122
123 var Gp = GeneratorFunctionPrototype.prototype =
124 Generator.prototype = Object.create(IteratorPrototype);
125 GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
126 GeneratorFunctionPrototype.constructor = GeneratorFunction;
127 GeneratorFunctionPrototype[toStringTagSymbol] =
128 GeneratorFunction.displayName = "GeneratorFunction";
129
130 // Helper for defining the .next, .throw, and .return methods of the
131 // Iterator interface in terms of a single ._invoke method.
132 function defineIteratorMethods(prototype) {
133 ["next", "throw", "return"].forEach(function(method) {
134 prototype[method] = function(arg) {
135 return this._invoke(method, arg);
136 };
137 });
138 }
139
140 runtime.isGeneratorFunction = function(genFun) {
141 var ctor = typeof genFun === "function" && genFun.constructor;
142 return ctor
143 ? ctor === GeneratorFunction ||
144 // For the native GeneratorFunction constructor, the best we can
145 // do is to check its .name property.
146 (ctor.displayName || ctor.name) === "GeneratorFunction"
147 : false;
148 };
149
150 runtime.mark = function(genFun) {
151 if (Object.setPrototypeOf) {
152 Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
153 } else {
154 genFun.__proto__ = GeneratorFunctionPrototype;
155 if (!(toStringTagSymbol in genFun)) {
156 genFun[toStringTagSymbol] = "GeneratorFunction";
157 }
158 }
159 genFun.prototype = Object.create(Gp);
160 return genFun;
161 };
162
163 // Within the body of any async function, `await x` is transformed to
164 // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
165 // `hasOwn.call(value, "__await")` to determine if the yielded value is
166 // meant to be awaited.
167 runtime.awrap = function(arg) {
168 return { __await: arg };
169 };
170
171 function AsyncIterator(generator) {
172 function invoke(method, arg, resolve, reject) {
173 var record = tryCatch(generator[method], generator, arg);
174 if (record.type === "throw") {
175 reject(record.arg);
176 } else {
177 var result = record.arg;
178 var value = result.value;
179 if (value &&
180 typeof value === "object" &&
181 hasOwn.call(value, "__await")) {
182 return Promise.resolve(value.__await).then(function(value) {
183 invoke("next", value, resolve, reject);
184 }, function(err) {
185 invoke("throw", err, resolve, reject);
186 });
187 }
188
189 return Promise.resolve(value).then(function(unwrapped) {
190 // When a yielded Promise is resolved, its final value becomes
191 // the .value of the Promise<{value,done}> result for the
192 // current iteration.
193 result.value = unwrapped;
194 resolve(result);
195 }, function(error) {
196 // If a rejected Promise was yielded, throw the rejection back
197 // into the async generator function so it can be handled there.
198 return invoke("throw", error, resolve, reject);
199 });
200 }
201 }
202
203 var previousPromise;
204
205 function enqueue(method, arg) {
206 function callInvokeWithMethodAndArg() {
207 return new Promise(function(resolve, reject) {
208 invoke(method, arg, resolve, reject);
209 });
210 }
211
212 return previousPromise =
213 // If enqueue has been called before, then we want to wait until
214 // all previous Promises have been resolved before calling invoke,
215 // so that results are always delivered in the correct order. If
216 // enqueue has not been called before, then it is important to
217 // call invoke immediately, without waiting on a callback to fire,
218 // so that the async generator function has the opportunity to do
219 // any necessary setup in a predictable way. This predictability
220 // is why the Promise constructor synchronously invokes its
221 // executor callback, and why async functions synchronously
222 // execute code before the first await. Since we implement simple
223 // async functions in terms of async generators, it is especially
224 // important to get this right, even though it requires care.
225 previousPromise ? previousPromise.then(
226 callInvokeWithMethodAndArg,
227 // Avoid propagating failures to Promises returned by later
228 // invocations of the iterator.
229 callInvokeWithMethodAndArg
230 ) : callInvokeWithMethodAndArg();
231 }
232
233 // Define the unified helper method that is used to implement .next,
234 // .throw, and .return (see defineIteratorMethods).
235 this._invoke = enqueue;
236 }
237
238 defineIteratorMethods(AsyncIterator.prototype);
239 AsyncIterator.prototype[asyncIteratorSymbol] = function () {
240 return this;
241 };
242 runtime.AsyncIterator = AsyncIterator;
243
244 // Note that simple async functions are implemented on top of
245 // AsyncIterator objects; they just return a Promise for the value of
246 // the final result produced by the iterator.
247 runtime.async = function(innerFn, outerFn, self, tryLocsList) {
248 var iter = new AsyncIterator(
249 wrap(innerFn, outerFn, self, tryLocsList)
250 );
251
252 return runtime.isGeneratorFunction(outerFn)
253 ? iter // If outerFn is a generator, return the full iterator.
254 : iter.next().then(function(result) {
255 return result.done ? result.value : iter.next();
256 });
257 };
258
259 function makeInvokeMethod(innerFn, self, context) {
260 var state = GenStateSuspendedStart;
261
262 return function invoke(method, arg) {
263 if (state === GenStateExecuting) {
264 throw new Error("Generator is already running");
265 }
266
267 if (state === GenStateCompleted) {
268 if (method === "throw") {
269 throw arg;
270 }
271
272 // Be forgiving, per 25.3.3.3.3 of the spec:
273 // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
274 return doneResult();
275 }
276
277 context.method = method;
278 context.arg = arg;
279
280 while (true) {
281 var delegate = context.delegate;
282 if (delegate) {
283 var delegateResult = maybeInvokeDelegate(delegate, context);
284 if (delegateResult) {
285 if (delegateResult === ContinueSentinel) continue;
286 return delegateResult;
287 }
288 }
289
290 if (context.method === "next") {
291 // Setting context._sent for legacy support of Babel's
292 // function.sent implementation.
293 context.sent = context._sent = context.arg;
294
295 } else if (context.method === "throw") {
296 if (state === GenStateSuspendedStart) {
297 state = GenStateCompleted;
298 throw context.arg;
299 }
300
301 context.dispatchException(context.arg);
302
303 } else if (context.method === "return") {
304 context.abrupt("return", context.arg);
305 }
306
307 state = GenStateExecuting;
308
309 var record = tryCatch(innerFn, self, context);
310 if (record.type === "normal") {
311 // If an exception is thrown from innerFn, we leave state ===
312 // GenStateExecuting and loop back for another invocation.
313 state = context.done
314 ? GenStateCompleted
315 : GenStateSuspendedYield;
316
317 if (record.arg === ContinueSentinel) {
318 continue;
319 }
320
321 return {
322 value: record.arg,
323 done: context.done
324 };
325
326 } else if (record.type === "throw") {
327 state = GenStateCompleted;
328 // Dispatch the exception by looping back around to the
329 // context.dispatchException(context.arg) call above.
330 context.method = "throw";
331 context.arg = record.arg;
332 }
333 }
334 };
335 }
336
337 // Call delegate.iterator[context.method](context.arg) and handle the
338 // result, either by returning a { value, done } result from the
339 // delegate iterator, or by modifying context.method and context.arg,
340 // setting context.delegate to null, and returning the ContinueSentinel.
341 function maybeInvokeDelegate(delegate, context) {
342 var method = delegate.iterator[context.method];
343 if (method === undefined) {
344 // A .throw or .return when the delegate iterator has no .throw
345 // method always terminates the yield* loop.
346 context.delegate = null;
347
348 if (context.method === "throw") {
349 if (delegate.iterator.return) {
350 // If the delegate iterator has a return method, give it a
351 // chance to clean up.
352 context.method = "return";
353 context.arg = undefined;
354 maybeInvokeDelegate(delegate, context);
355
356 if (context.method === "throw") {
357 // If maybeInvokeDelegate(context) changed context.method from
358 // "return" to "throw", let that override the TypeError below.
359 return ContinueSentinel;
360 }
361 }
362
363 context.method = "throw";
364 context.arg = new TypeError(
365 "The iterator does not provide a 'throw' method");
366 }
367
368 return ContinueSentinel;
369 }
370
371 var record = tryCatch(method, delegate.iterator, context.arg);
372
373 if (record.type === "throw") {
374 context.method = "throw";
375 context.arg = record.arg;
376 context.delegate = null;
377 return ContinueSentinel;
378 }
379
380 var info = record.arg;
381
382 if (! info) {
383 context.method = "throw";
384 context.arg = new TypeError("iterator result is not an object");
385 context.delegate = null;
386 return ContinueSentinel;
387 }
388
389 if (info.done) {
390 // Assign the result of the finished delegate to the temporary
391 // variable specified by delegate.resultName (see delegateYield).
392 context[delegate.resultName] = info.value;
393
394 // Resume execution at the desired location (see delegateYield).
395 context.next = delegate.nextLoc;
396
397 // If context.method was "throw" but the delegate handled the
398 // exception, let the outer generator proceed normally. If
399 // context.method was "next", forget context.arg since it has been
400 // "consumed" by the delegate iterator. If context.method was
401 // "return", allow the original .return call to continue in the
402 // outer generator.
403 if (context.method !== "return") {
404 context.method = "next";
405 context.arg = undefined;
406 }
407
408 } else {
409 // Re-yield the result returned by the delegate method.
410 return info;
411 }
412
413 // The delegate iterator is finished, so forget it and continue with
414 // the outer generator.
415 context.delegate = null;
416 return ContinueSentinel;
417 }
418
419 // Define Generator.prototype.{next,throw,return} in terms of the
420 // unified ._invoke helper method.
421 defineIteratorMethods(Gp);
422
423 Gp[toStringTagSymbol] = "Generator";
424
425 // A Generator should always return itself as the iterator object when the
426 // @@iterator function is called on it. Some browsers' implementations of the
427 // iterator prototype chain incorrectly implement this, causing the Generator
428 // object to not be returned from this call. This ensures that doesn't happen.
429 // See https://github.com/facebook/regenerator/issues/274 for more details.
430 Gp[iteratorSymbol] = function() {
431 return this;
432 };
433
434 Gp.toString = function() {
435 return "[object Generator]";
436 };
437
438 function pushTryEntry(locs) {
439 var entry = { tryLoc: locs[0] };
440
441 if (1 in locs) {
442 entry.catchLoc = locs[1];
443 }
444
445 if (2 in locs) {
446 entry.finallyLoc = locs[2];
447 entry.afterLoc = locs[3];
448 }
449
450 this.tryEntries.push(entry);
451 }
452
453 function resetTryEntry(entry) {
454 var record = entry.completion || {};
455 record.type = "normal";
456 delete record.arg;
457 entry.completion = record;
458 }
459
460 function Context(tryLocsList) {
461 // The root entry object (effectively a try statement without a catch
462 // or a finally block) gives us a place to store values thrown from
463 // locations where there is no enclosing try statement.
464 this.tryEntries = [{ tryLoc: "root" }];
465 tryLocsList.forEach(pushTryEntry, this);
466 this.reset(true);
467 }
468
469 runtime.keys = function(object) {
470 var keys = [];
471 for (var key in object) {
472 keys.push(key);
473 }
474 keys.reverse();
475
476 // Rather than returning an object with a next method, we keep
477 // things simple and return the next function itself.
478 return function next() {
479 while (keys.length) {
480 var key = keys.pop();
481 if (key in object) {
482 next.value = key;
483 next.done = false;
484 return next;
485 }
486 }
487
488 // To avoid creating an additional object, we just hang the .value
489 // and .done properties off the next function object itself. This
490 // also ensures that the minifier will not anonymize the function.
491 next.done = true;
492 return next;
493 };
494 };
495
496 function values(iterable) {
497 if (iterable) {
498 var iteratorMethod = iterable[iteratorSymbol];
499 if (iteratorMethod) {
500 return iteratorMethod.call(iterable);
501 }
502
503 if (typeof iterable.next === "function") {
504 return iterable;
505 }
506
507 if (!isNaN(iterable.length)) {
508 var i = -1, next = function next() {
509 while (++i < iterable.length) {
510 if (hasOwn.call(iterable, i)) {
511 next.value = iterable[i];
512 next.done = false;
513 return next;
514 }
515 }
516
517 next.value = undefined;
518 next.done = true;
519
520 return next;
521 };
522
523 return next.next = next;
524 }
525 }
526
527 // Return an iterator with no values.
528 return { next: doneResult };
529 }
530 runtime.values = values;
531
532 function doneResult() {
533 return { value: undefined, done: true };
534 }
535
536 Context.prototype = {
537 constructor: Context,
538
539 reset: function(skipTempReset) {
540 this.prev = 0;
541 this.next = 0;
542 // Resetting context._sent for legacy support of Babel's
543 // function.sent implementation.
544 this.sent = this._sent = undefined;
545 this.done = false;
546 this.delegate = null;
547
548 this.method = "next";
549 this.arg = undefined;
550
551 this.tryEntries.forEach(resetTryEntry);
552
553 if (!skipTempReset) {
554 for (var name in this) {
555 // Not sure about the optimal order of these conditions:
556 if (name.charAt(0) === "t" &&
557 hasOwn.call(this, name) &&
558 !isNaN(+name.slice(1))) {
559 this[name] = undefined;
560 }
561 }
562 }
563 },
564
565 stop: function() {
566 this.done = true;
567
568 var rootEntry = this.tryEntries[0];
569 var rootRecord = rootEntry.completion;
570 if (rootRecord.type === "throw") {
571 throw rootRecord.arg;
572 }
573
574 return this.rval;
575 },
576
577 dispatchException: function(exception) {
578 if (this.done) {
579 throw exception;
580 }
581
582 var context = this;
583 function handle(loc, caught) {
584 record.type = "throw";
585 record.arg = exception;
586 context.next = loc;
587
588 if (caught) {
589 // If the dispatched exception was caught by a catch block,
590 // then let that catch block handle the exception normally.
591 context.method = "next";
592 context.arg = undefined;
593 }
594
595 return !! caught;
596 }
597
598 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
599 var entry = this.tryEntries[i];
600 var record = entry.completion;
601
602 if (entry.tryLoc === "root") {
603 // Exception thrown outside of any try block that could handle
604 // it, so set the completion value of the entire function to
605 // throw the exception.
606 return handle("end");
607 }
608
609 if (entry.tryLoc <= this.prev) {
610 var hasCatch = hasOwn.call(entry, "catchLoc");
611 var hasFinally = hasOwn.call(entry, "finallyLoc");
612
613 if (hasCatch && hasFinally) {
614 if (this.prev < entry.catchLoc) {
615 return handle(entry.catchLoc, true);
616 } else if (this.prev < entry.finallyLoc) {
617 return handle(entry.finallyLoc);
618 }
619
620 } else if (hasCatch) {
621 if (this.prev < entry.catchLoc) {
622 return handle(entry.catchLoc, true);
623 }
624
625 } else if (hasFinally) {
626 if (this.prev < entry.finallyLoc) {
627 return handle(entry.finallyLoc);
628 }
629
630 } else {
631 throw new Error("try statement without catch or finally");
632 }
633 }
634 }
635 },
636
637 abrupt: function(type, arg) {
638 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
639 var entry = this.tryEntries[i];
640 if (entry.tryLoc <= this.prev &&
641 hasOwn.call(entry, "finallyLoc") &&
642 this.prev < entry.finallyLoc) {
643 var finallyEntry = entry;
644 break;
645 }
646 }
647
648 if (finallyEntry &&
649 (type === "break" ||
650 type === "continue") &&
651 finallyEntry.tryLoc <= arg &&
652 arg <= finallyEntry.finallyLoc) {
653 // Ignore the finally entry if control is not jumping to a
654 // location outside the try/catch block.
655 finallyEntry = null;
656 }
657
658 var record = finallyEntry ? finallyEntry.completion : {};
659 record.type = type;
660 record.arg = arg;
661
662 if (finallyEntry) {
663 this.method = "next";
664 this.next = finallyEntry.finallyLoc;
665 return ContinueSentinel;
666 }
667
668 return this.complete(record);
669 },
670
671 complete: function(record, afterLoc) {
672 if (record.type === "throw") {
673 throw record.arg;
674 }
675
676 if (record.type === "break" ||
677 record.type === "continue") {
678 this.next = record.arg;
679 } else if (record.type === "return") {
680 this.rval = this.arg = record.arg;
681 this.method = "return";
682 this.next = "end";
683 } else if (record.type === "normal" && afterLoc) {
684 this.next = afterLoc;
685 }
686
687 return ContinueSentinel;
688 },
689
690 finish: function(finallyLoc) {
691 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
692 var entry = this.tryEntries[i];
693 if (entry.finallyLoc === finallyLoc) {
694 this.complete(entry.completion, entry.afterLoc);
695 resetTryEntry(entry);
696 return ContinueSentinel;
697 }
698 }
699 },
700
701 "catch": function(tryLoc) {
702 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
703 var entry = this.tryEntries[i];
704 if (entry.tryLoc === tryLoc) {
705 var record = entry.completion;
706 if (record.type === "throw") {
707 var thrown = record.arg;
708 resetTryEntry(entry);
709 }
710 return thrown;
711 }
712 }
713
714 // The context.catch method must only be called with a location
715 // argument that corresponds to a known catch block.
716 throw new Error("illegal catch attempt");
717 },
718
719 delegateYield: function(iterable, resultName, nextLoc) {
720 this.delegate = {
721 iterator: values(iterable),
722 resultName: resultName,
723 nextLoc: nextLoc
724 };
725
726 if (this.method === "next") {
727 // Deliberately forget the last sent value so that we don't
728 // accidentally pass it on to the delegate.
729 this.arg = undefined;
730 }
731
732 return ContinueSentinel;
733 }
734 };
735 })(
736 // In sloppy mode, unbound `this` refers to the global object, fallback to
737 // Function constructor if we're in global strict mode. That is sadly a form
738 // of indirect eval which violates Content Security Policy.
739 (function() {
740 return this || (typeof self === "object" && self);
741 })() || Function("return this")()
742 );
743 });
744
745 function _typeof(obj) {
746 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
747 _typeof = function (obj) {
748 return typeof obj;
749 };
750 } else {
751 _typeof = function (obj) {
752 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
753 };
754 }
755
756 return _typeof(obj);
757 }
758
759 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
760 try {
761 var info = gen[key](arg);
762 var value = info.value;
763 } catch (error) {
764 reject(error);
765 return;
766 }
767
768 if (info.done) {
769 resolve(value);
770 } else {
771 Promise.resolve(value).then(_next, _throw);
772 }
773 }
774
775 function _asyncToGenerator(fn) {
776 return function () {
777 var self = this,
778 args = arguments;
779 return new Promise(function (resolve, reject) {
780 var gen = fn.apply(self, args);
781
782 function _next(value) {
783 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
784 }
785
786 function _throw(err) {
787 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
788 }
789
790 _next(undefined);
791 });
792 };
793 }
794
795 function _classCallCheck(instance, Constructor) {
796 if (!(instance instanceof Constructor)) {
797 throw new TypeError("Cannot call a class as a function");
798 }
799 }
800
801 function _defineProperties(target, props) {
802 for (var i = 0; i < props.length; i++) {
803 var descriptor = props[i];
804 descriptor.enumerable = descriptor.enumerable || false;
805 descriptor.configurable = true;
806 if ("value" in descriptor) descriptor.writable = true;
807 Object.defineProperty(target, descriptor.key, descriptor);
808 }
809 }
810
811 function _createClass(Constructor, protoProps, staticProps) {
812 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
813 if (staticProps) _defineProperties(Constructor, staticProps);
814 return Constructor;
815 }
816
817 function _inherits(subClass, superClass) {
818 if (typeof superClass !== "function" && superClass !== null) {
819 throw new TypeError("Super expression must either be null or a function");
820 }
821
822 subClass.prototype = Object.create(superClass && superClass.prototype, {
823 constructor: {
824 value: subClass,
825 writable: true,
826 configurable: true
827 }
828 });
829 if (superClass) _setPrototypeOf(subClass, superClass);
830 }
831
832 function _getPrototypeOf(o) {
833 _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
834 return o.__proto__ || Object.getPrototypeOf(o);
835 };
836 return _getPrototypeOf(o);
837 }
838
839 function _setPrototypeOf(o, p) {
840 _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
841 o.__proto__ = p;
842 return o;
843 };
844
845 return _setPrototypeOf(o, p);
846 }
847
848 function isNativeReflectConstruct() {
849 if (typeof Reflect === "undefined" || !Reflect.construct) return false;
850 if (Reflect.construct.sham) return false;
851 if (typeof Proxy === "function") return true;
852
853 try {
854 Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
855 return true;
856 } catch (e) {
857 return false;
858 }
859 }
860
861 function _construct(Parent, args, Class) {
862 if (isNativeReflectConstruct()) {
863 _construct = Reflect.construct;
864 } else {
865 _construct = function _construct(Parent, args, Class) {
866 var a = [null];
867 a.push.apply(a, args);
868 var Constructor = Function.bind.apply(Parent, a);
869 var instance = new Constructor();
870 if (Class) _setPrototypeOf(instance, Class.prototype);
871 return instance;
872 };
873 }
874
875 return _construct.apply(null, arguments);
876 }
877
878 function _isNativeFunction(fn) {
879 return Function.toString.call(fn).indexOf("[native code]") !== -1;
880 }
881
882 function _wrapNativeSuper(Class) {
883 var _cache = typeof Map === "function" ? new Map() : undefined;
884
885 _wrapNativeSuper = function _wrapNativeSuper(Class) {
886 if (Class === null || !_isNativeFunction(Class)) return Class;
887
888 if (typeof Class !== "function") {
889 throw new TypeError("Super expression must either be null or a function");
890 }
891
892 if (typeof _cache !== "undefined") {
893 if (_cache.has(Class)) return _cache.get(Class);
894
895 _cache.set(Class, Wrapper);
896 }
897
898 function Wrapper() {
899 return _construct(Class, arguments, _getPrototypeOf(this).constructor);
900 }
901
902 Wrapper.prototype = Object.create(Class.prototype, {
903 constructor: {
904 value: Wrapper,
905 enumerable: false,
906 writable: true,
907 configurable: true
908 }
909 });
910 return _setPrototypeOf(Wrapper, Class);
911 };
912
913 return _wrapNativeSuper(Class);
914 }
915
916 function _assertThisInitialized(self) {
917 if (self === void 0) {
918 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
919 }
920
921 return self;
922 }
923
924 function _possibleConstructorReturn(self, call) {
925 if (call && (typeof call === "object" || typeof call === "function")) {
926 return call;
927 }
928
929 return _assertThisInitialized(self);
930 }
931
932 function _slicedToArray(arr, i) {
933 return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
934 }
935
936 function _toArray(arr) {
937 return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest();
938 }
939
940 function _toConsumableArray(arr) {
941 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
942 }
943
944 function _arrayWithoutHoles(arr) {
945 if (Array.isArray(arr)) {
946 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
947
948 return arr2;
949 }
950 }
951
952 function _arrayWithHoles(arr) {
953 if (Array.isArray(arr)) return arr;
954 }
955
956 function _iterableToArray(iter) {
957 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
958 }
959
960 function _iterableToArrayLimit(arr, i) {
961 var _arr = [];
962 var _n = true;
963 var _d = false;
964 var _e = undefined;
965
966 try {
967 for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
968 _arr.push(_s.value);
969
970 if (i && _arr.length === i) break;
971 }
972 } catch (err) {
973 _d = true;
974 _e = err;
975 } finally {
976 try {
977 if (!_n && _i["return"] != null) _i["return"]();
978 } finally {
979 if (_d) throw _e;
980 }
981 }
982
983 return _arr;
984 }
985
986 function _nonIterableSpread() {
987 throw new TypeError("Invalid attempt to spread non-iterable instance");
988 }
989
990 function _nonIterableRest() {
991 throw new TypeError("Invalid attempt to destructure non-iterable instance");
992 }
993
994 var load = function load(received, defaults) {
995 var onto = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
996 var k, ref, v;
997
998 for (k in defaults) {
999 v = defaults[k];
1000 onto[k] = (ref = received[k]) != null ? ref : v;
1001 }
1002
1003 return onto;
1004 };
1005
1006 var overwrite = function overwrite(received, defaults) {
1007 var onto = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1008 var k, v;
1009
1010 for (k in received) {
1011 v = received[k];
1012
1013 if (defaults[k] !== void 0) {
1014 onto[k] = v;
1015 }
1016 }
1017
1018 return onto;
1019 };
1020
1021 var parser = {
1022 load: load,
1023 overwrite: overwrite
1024 };
1025
1026 var DLList;
1027
1028 DLList =
1029 /*#__PURE__*/
1030 function () {
1031 function DLList(_queues) {
1032 _classCallCheck(this, DLList);
1033
1034 this._queues = _queues;
1035 this._first = null;
1036 this._last = null;
1037 this.length = 0;
1038 }
1039
1040 _createClass(DLList, [{
1041 key: "push",
1042 value: function push(value) {
1043 var node, ref1;
1044 this.length++;
1045
1046 if ((ref1 = this._queues) != null) {
1047 ref1.incr();
1048 }
1049
1050 node = {
1051 value: value,
1052 next: null
1053 };
1054
1055 if (this._last != null) {
1056 this._last.next = node;
1057 this._last = node;
1058 } else {
1059 this._first = this._last = node;
1060 }
1061
1062 return void 0;
1063 }
1064 }, {
1065 key: "shift",
1066 value: function shift() {
1067 var ref1, ref2, value;
1068
1069 if (this._first == null) {
1070 return void 0;
1071 } else {
1072 this.length--;
1073
1074 if ((ref1 = this._queues) != null) {
1075 ref1.decr();
1076 }
1077 }
1078
1079 value = this._first.value;
1080 this._first = (ref2 = this._first.next) != null ? ref2 : this._last = null;
1081 return value;
1082 }
1083 }, {
1084 key: "first",
1085 value: function first() {
1086 if (this._first != null) {
1087 return this._first.value;
1088 }
1089 }
1090 }, {
1091 key: "getArray",
1092 value: function getArray() {
1093 var node, ref, results;
1094 node = this._first;
1095 results = [];
1096
1097 while (node != null) {
1098 results.push((ref = node, node = node.next, ref.value));
1099 }
1100
1101 return results;
1102 }
1103 }, {
1104 key: "forEachShift",
1105 value: function forEachShift(cb) {
1106 var node;
1107 node = this.shift();
1108
1109 while (node != null) {
1110 cb(node), node = this.shift();
1111 }
1112
1113 return void 0;
1114 }
1115 }]);
1116
1117 return DLList;
1118 }();
1119
1120 var DLList_1 = DLList;
1121
1122 var Events;
1123
1124 Events =
1125 /*#__PURE__*/
1126 function () {
1127 function Events(instance) {
1128 var _this = this;
1129
1130 _classCallCheck(this, Events);
1131
1132 this.instance = instance;
1133 this._events = {};
1134
1135 if (this.instance.on != null || this.instance.once != null || this.instance.removeAllListeners != null) {
1136 throw new Error("An Emitter already exists for this object");
1137 }
1138
1139 this.instance.on = function (name, cb) {
1140 return _this._addListener(name, "many", cb);
1141 };
1142
1143 this.instance.once = function (name, cb) {
1144 return _this._addListener(name, "once", cb);
1145 };
1146
1147 this.instance.removeAllListeners = function () {
1148 var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
1149
1150 if (name != null) {
1151 return delete _this._events[name];
1152 } else {
1153 return _this._events = {};
1154 }
1155 };
1156 }
1157
1158 _createClass(Events, [{
1159 key: "_addListener",
1160 value: function _addListener(name, status, cb) {
1161 var base;
1162
1163 if ((base = this._events)[name] == null) {
1164 base[name] = [];
1165 }
1166
1167 this._events[name].push({
1168 cb: cb,
1169 status: status
1170 });
1171
1172 return this.instance;
1173 }
1174 }, {
1175 key: "listenerCount",
1176 value: function listenerCount(name) {
1177 if (this._events[name] != null) {
1178 return this._events[name].length;
1179 } else {
1180 return 0;
1181 }
1182 }
1183 }, {
1184 key: "trigger",
1185 value: function () {
1186 var _trigger = _asyncToGenerator(
1187 /*#__PURE__*/
1188 regeneratorRuntime.mark(function _callee2(name) {
1189 var _this2 = this;
1190
1191 var _len,
1192 args,
1193 _key,
1194 e,
1195 promises,
1196 _args2 = arguments;
1197
1198 return regeneratorRuntime.wrap(function _callee2$(_context2) {
1199 while (1) {
1200 switch (_context2.prev = _context2.next) {
1201 case 0:
1202 for (_len = _args2.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
1203 args[_key - 1] = _args2[_key];
1204 }
1205
1206 _context2.prev = 1;
1207
1208 if (name !== "debug") {
1209 this.trigger("debug", "Event triggered: ".concat(name), args);
1210 }
1211
1212 if (!(this._events[name] == null)) {
1213 _context2.next = 5;
1214 break;
1215 }
1216
1217 return _context2.abrupt("return");
1218
1219 case 5:
1220 this._events[name] = this._events[name].filter(function (listener) {
1221 return listener.status !== "none";
1222 });
1223 promises = this._events[name].map(
1224 /*#__PURE__*/
1225 function () {
1226 var _ref = _asyncToGenerator(
1227 /*#__PURE__*/
1228 regeneratorRuntime.mark(function _callee(listener) {
1229 var e, returned;
1230 return regeneratorRuntime.wrap(function _callee$(_context) {
1231 while (1) {
1232 switch (_context.prev = _context.next) {
1233 case 0:
1234 if (!(listener.status === "none")) {
1235 _context.next = 2;
1236 break;
1237 }
1238
1239 return _context.abrupt("return");
1240
1241 case 2:
1242 if (listener.status === "once") {
1243 listener.status = "none";
1244 }
1245
1246 _context.prev = 3;
1247 returned = typeof listener.cb === "function" ? listener.cb.apply(listener, args) : void 0;
1248
1249 if (!(typeof (returned != null ? returned.then : void 0) === "function")) {
1250 _context.next = 11;
1251 break;
1252 }
1253
1254 _context.next = 8;
1255 return returned;
1256
1257 case 8:
1258 return _context.abrupt("return", _context.sent);
1259
1260 case 11:
1261 return _context.abrupt("return", returned);
1262
1263 case 12:
1264 _context.next = 19;
1265 break;
1266
1267 case 14:
1268 _context.prev = 14;
1269 _context.t0 = _context["catch"](3);
1270 e = _context.t0;
1271
1272 {
1273 _this2.trigger("error", e);
1274 }
1275
1276 return _context.abrupt("return", null);
1277
1278 case 19:
1279 case "end":
1280 return _context.stop();
1281 }
1282 }
1283 }, _callee, this, [[3, 14]]);
1284 }));
1285
1286 return function (_x2) {
1287 return _ref.apply(this, arguments);
1288 };
1289 }());
1290 _context2.next = 9;
1291 return Promise.all(promises);
1292
1293 case 9:
1294 _context2.t0 = function (x) {
1295 return x != null;
1296 };
1297
1298 return _context2.abrupt("return", _context2.sent.find(_context2.t0));
1299
1300 case 13:
1301 _context2.prev = 13;
1302 _context2.t1 = _context2["catch"](1);
1303 e = _context2.t1;
1304
1305 {
1306 this.trigger("error", e);
1307 }
1308
1309 return _context2.abrupt("return", null);
1310
1311 case 18:
1312 case "end":
1313 return _context2.stop();
1314 }
1315 }
1316 }, _callee2, this, [[1, 13]]);
1317 }));
1318
1319 return function trigger(_x) {
1320 return _trigger.apply(this, arguments);
1321 };
1322 }()
1323 }]);
1324
1325 return Events;
1326 }();
1327
1328 var Events_1 = Events;
1329
1330 var DLList$1, Events$1, Queues;
1331 DLList$1 = DLList_1;
1332 Events$1 = Events_1;
1333
1334 Queues =
1335 /*#__PURE__*/
1336 function () {
1337 function Queues(num_priorities) {
1338 _classCallCheck(this, Queues);
1339
1340 var i;
1341 this.Events = new Events$1(this);
1342 this._length = 0;
1343
1344 this._lists = function () {
1345 var j, ref, results;
1346 results = [];
1347
1348 for (i = j = 1, ref = num_priorities; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) {
1349 results.push(new DLList$1(this));
1350 }
1351
1352 return results;
1353 }.call(this);
1354 }
1355
1356 _createClass(Queues, [{
1357 key: "incr",
1358 value: function incr() {
1359 if (this._length++ === 0) {
1360 return this.Events.trigger("leftzero");
1361 }
1362 }
1363 }, {
1364 key: "decr",
1365 value: function decr() {
1366 if (--this._length === 0) {
1367 return this.Events.trigger("zero");
1368 }
1369 }
1370 }, {
1371 key: "push",
1372 value: function push(priority, job) {
1373 return this._lists[priority].push(job);
1374 }
1375 }, {
1376 key: "queued",
1377 value: function queued(priority) {
1378 if (priority != null) {
1379 return this._lists[priority].length;
1380 } else {
1381 return this._length;
1382 }
1383 }
1384 }, {
1385 key: "shiftAll",
1386 value: function shiftAll(fn) {
1387 return this._lists.forEach(function (list) {
1388 return list.forEachShift(fn);
1389 });
1390 }
1391 }, {
1392 key: "getFirst",
1393 value: function getFirst() {
1394 var arr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this._lists;
1395 var j, len, list;
1396
1397 for (j = 0, len = arr.length; j < len; j++) {
1398 list = arr[j];
1399
1400 if (list.length > 0) {
1401 return list;
1402 }
1403 }
1404
1405 return [];
1406 }
1407 }, {
1408 key: "shiftLastFrom",
1409 value: function shiftLastFrom(priority) {
1410 return this.getFirst(this._lists.slice(priority).reverse()).shift();
1411 }
1412 }]);
1413
1414 return Queues;
1415 }();
1416
1417 var Queues_1 = Queues;
1418
1419 var BottleneckError;
1420
1421 BottleneckError =
1422 /*#__PURE__*/
1423 function (_Error) {
1424 _inherits(BottleneckError, _Error);
1425
1426 function BottleneckError() {
1427 _classCallCheck(this, BottleneckError);
1428
1429 return _possibleConstructorReturn(this, _getPrototypeOf(BottleneckError).apply(this, arguments));
1430 }
1431
1432 return BottleneckError;
1433 }(_wrapNativeSuper(Error));
1434
1435 var BottleneckError_1 = BottleneckError;
1436
1437 var BottleneckError$1, LocalDatastore, parser$1;
1438 parser$1 = parser;
1439 BottleneckError$1 = BottleneckError_1;
1440
1441 LocalDatastore =
1442 /*#__PURE__*/
1443 function () {
1444 function LocalDatastore(instance, storeOptions, storeInstanceOptions) {
1445 _classCallCheck(this, LocalDatastore);
1446
1447 this.instance = instance;
1448 this.storeOptions = storeOptions;
1449 this.clientId = this.instance._randomIndex();
1450 parser$1.load(storeInstanceOptions, storeInstanceOptions, this);
1451 this._nextRequest = this._lastReservoirRefresh = Date.now();
1452 this._running = 0;
1453 this._done = 0;
1454 this._unblockTime = 0;
1455 this.ready = this.Promise.resolve();
1456 this.clients = {};
1457
1458 this._startHeartbeat();
1459 }
1460
1461 _createClass(LocalDatastore, [{
1462 key: "_startHeartbeat",
1463 value: function _startHeartbeat() {
1464 var _this = this;
1465
1466 var base;
1467
1468 if (this.heartbeat == null && this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null) {
1469 return typeof (base = this.heartbeat = setInterval(function () {
1470 var now;
1471 now = Date.now();
1472
1473 if (now >= _this._lastReservoirRefresh + _this.storeOptions.reservoirRefreshInterval) {
1474 _this.storeOptions.reservoir = _this.storeOptions.reservoirRefreshAmount;
1475 _this._lastReservoirRefresh = now;
1476 return _this.instance._drainAll(_this.computeCapacity());
1477 }
1478 }, this.heartbeatInterval)).unref === "function" ? base.unref() : void 0;
1479 } else {
1480 return clearInterval(this.heartbeat);
1481 }
1482 }
1483 }, {
1484 key: "__publish__",
1485 value: function () {
1486 var _publish__ = _asyncToGenerator(
1487 /*#__PURE__*/
1488 regeneratorRuntime.mark(function _callee(message) {
1489 return regeneratorRuntime.wrap(function _callee$(_context) {
1490 while (1) {
1491 switch (_context.prev = _context.next) {
1492 case 0:
1493 _context.next = 2;
1494 return this.yieldLoop();
1495
1496 case 2:
1497 return _context.abrupt("return", this.instance.Events.trigger("message", message.toString()));
1498
1499 case 3:
1500 case "end":
1501 return _context.stop();
1502 }
1503 }
1504 }, _callee, this);
1505 }));
1506
1507 return function __publish__(_x) {
1508 return _publish__.apply(this, arguments);
1509 };
1510 }()
1511 }, {
1512 key: "__disconnect__",
1513 value: function () {
1514 var _disconnect__ = _asyncToGenerator(
1515 /*#__PURE__*/
1516 regeneratorRuntime.mark(function _callee2(flush) {
1517 return regeneratorRuntime.wrap(function _callee2$(_context2) {
1518 while (1) {
1519 switch (_context2.prev = _context2.next) {
1520 case 0:
1521 _context2.next = 2;
1522 return this.yieldLoop();
1523
1524 case 2:
1525 clearInterval(this.heartbeat);
1526 return _context2.abrupt("return", this.Promise.resolve());
1527
1528 case 4:
1529 case "end":
1530 return _context2.stop();
1531 }
1532 }
1533 }, _callee2, this);
1534 }));
1535
1536 return function __disconnect__(_x2) {
1537 return _disconnect__.apply(this, arguments);
1538 };
1539 }()
1540 }, {
1541 key: "yieldLoop",
1542 value: function yieldLoop() {
1543 var t = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
1544 return new this.Promise(function (resolve, reject) {
1545 return setTimeout(resolve, t);
1546 });
1547 }
1548 }, {
1549 key: "computePenalty",
1550 value: function computePenalty() {
1551 var ref;
1552 return (ref = this.storeOptions.penalty) != null ? ref : 15 * this.storeOptions.minTime || 5000;
1553 }
1554 }, {
1555 key: "__updateSettings__",
1556 value: function () {
1557 var _updateSettings__ = _asyncToGenerator(
1558 /*#__PURE__*/
1559 regeneratorRuntime.mark(function _callee3(options) {
1560 return regeneratorRuntime.wrap(function _callee3$(_context3) {
1561 while (1) {
1562 switch (_context3.prev = _context3.next) {
1563 case 0:
1564 _context3.next = 2;
1565 return this.yieldLoop();
1566
1567 case 2:
1568 parser$1.overwrite(options, options, this.storeOptions);
1569
1570 this._startHeartbeat();
1571
1572 this.instance._drainAll(this.computeCapacity());
1573
1574 return _context3.abrupt("return", true);
1575
1576 case 6:
1577 case "end":
1578 return _context3.stop();
1579 }
1580 }
1581 }, _callee3, this);
1582 }));
1583
1584 return function __updateSettings__(_x3) {
1585 return _updateSettings__.apply(this, arguments);
1586 };
1587 }()
1588 }, {
1589 key: "__running__",
1590 value: function () {
1591 var _running__ = _asyncToGenerator(
1592 /*#__PURE__*/
1593 regeneratorRuntime.mark(function _callee4() {
1594 return regeneratorRuntime.wrap(function _callee4$(_context4) {
1595 while (1) {
1596 switch (_context4.prev = _context4.next) {
1597 case 0:
1598 _context4.next = 2;
1599 return this.yieldLoop();
1600
1601 case 2:
1602 return _context4.abrupt("return", this._running);
1603
1604 case 3:
1605 case "end":
1606 return _context4.stop();
1607 }
1608 }
1609 }, _callee4, this);
1610 }));
1611
1612 return function __running__() {
1613 return _running__.apply(this, arguments);
1614 };
1615 }()
1616 }, {
1617 key: "__queued__",
1618 value: function () {
1619 var _queued__ = _asyncToGenerator(
1620 /*#__PURE__*/
1621 regeneratorRuntime.mark(function _callee5() {
1622 return regeneratorRuntime.wrap(function _callee5$(_context5) {
1623 while (1) {
1624 switch (_context5.prev = _context5.next) {
1625 case 0:
1626 _context5.next = 2;
1627 return this.yieldLoop();
1628
1629 case 2:
1630 return _context5.abrupt("return", this.instance.queued());
1631
1632 case 3:
1633 case "end":
1634 return _context5.stop();
1635 }
1636 }
1637 }, _callee5, this);
1638 }));
1639
1640 return function __queued__() {
1641 return _queued__.apply(this, arguments);
1642 };
1643 }()
1644 }, {
1645 key: "__done__",
1646 value: function () {
1647 var _done__ = _asyncToGenerator(
1648 /*#__PURE__*/
1649 regeneratorRuntime.mark(function _callee6() {
1650 return regeneratorRuntime.wrap(function _callee6$(_context6) {
1651 while (1) {
1652 switch (_context6.prev = _context6.next) {
1653 case 0:
1654 _context6.next = 2;
1655 return this.yieldLoop();
1656
1657 case 2:
1658 return _context6.abrupt("return", this._done);
1659
1660 case 3:
1661 case "end":
1662 return _context6.stop();
1663 }
1664 }
1665 }, _callee6, this);
1666 }));
1667
1668 return function __done__() {
1669 return _done__.apply(this, arguments);
1670 };
1671 }()
1672 }, {
1673 key: "__groupCheck__",
1674 value: function () {
1675 var _groupCheck__ = _asyncToGenerator(
1676 /*#__PURE__*/
1677 regeneratorRuntime.mark(function _callee7(time) {
1678 return regeneratorRuntime.wrap(function _callee7$(_context7) {
1679 while (1) {
1680 switch (_context7.prev = _context7.next) {
1681 case 0:
1682 _context7.next = 2;
1683 return this.yieldLoop();
1684
1685 case 2:
1686 return _context7.abrupt("return", this._nextRequest + this.timeout < time);
1687
1688 case 3:
1689 case "end":
1690 return _context7.stop();
1691 }
1692 }
1693 }, _callee7, this);
1694 }));
1695
1696 return function __groupCheck__(_x4) {
1697 return _groupCheck__.apply(this, arguments);
1698 };
1699 }()
1700 }, {
1701 key: "computeCapacity",
1702 value: function computeCapacity() {
1703 var maxConcurrent, reservoir;
1704 var _this$storeOptions = this.storeOptions;
1705 maxConcurrent = _this$storeOptions.maxConcurrent;
1706 reservoir = _this$storeOptions.reservoir;
1707
1708 if (maxConcurrent != null && reservoir != null) {
1709 return Math.min(maxConcurrent - this._running, reservoir);
1710 } else if (maxConcurrent != null) {
1711 return maxConcurrent - this._running;
1712 } else if (reservoir != null) {
1713 return reservoir;
1714 } else {
1715 return null;
1716 }
1717 }
1718 }, {
1719 key: "conditionsCheck",
1720 value: function conditionsCheck(weight) {
1721 var capacity;
1722 capacity = this.computeCapacity();
1723 return capacity == null || weight <= capacity;
1724 }
1725 }, {
1726 key: "__incrementReservoir__",
1727 value: function () {
1728 var _incrementReservoir__ = _asyncToGenerator(
1729 /*#__PURE__*/
1730 regeneratorRuntime.mark(function _callee8(incr) {
1731 var reservoir;
1732 return regeneratorRuntime.wrap(function _callee8$(_context8) {
1733 while (1) {
1734 switch (_context8.prev = _context8.next) {
1735 case 0:
1736 _context8.next = 2;
1737 return this.yieldLoop();
1738
1739 case 2:
1740 reservoir = this.storeOptions.reservoir += incr;
1741
1742 this.instance._drainAll(this.computeCapacity());
1743
1744 return _context8.abrupt("return", reservoir);
1745
1746 case 5:
1747 case "end":
1748 return _context8.stop();
1749 }
1750 }
1751 }, _callee8, this);
1752 }));
1753
1754 return function __incrementReservoir__(_x5) {
1755 return _incrementReservoir__.apply(this, arguments);
1756 };
1757 }()
1758 }, {
1759 key: "__currentReservoir__",
1760 value: function () {
1761 var _currentReservoir__ = _asyncToGenerator(
1762 /*#__PURE__*/
1763 regeneratorRuntime.mark(function _callee9() {
1764 return regeneratorRuntime.wrap(function _callee9$(_context9) {
1765 while (1) {
1766 switch (_context9.prev = _context9.next) {
1767 case 0:
1768 _context9.next = 2;
1769 return this.yieldLoop();
1770
1771 case 2:
1772 return _context9.abrupt("return", this.storeOptions.reservoir);
1773
1774 case 3:
1775 case "end":
1776 return _context9.stop();
1777 }
1778 }
1779 }, _callee9, this);
1780 }));
1781
1782 return function __currentReservoir__() {
1783 return _currentReservoir__.apply(this, arguments);
1784 };
1785 }()
1786 }, {
1787 key: "isBlocked",
1788 value: function isBlocked(now) {
1789 return this._unblockTime >= now;
1790 }
1791 }, {
1792 key: "check",
1793 value: function check(weight, now) {
1794 return this.conditionsCheck(weight) && this._nextRequest - now <= 0;
1795 }
1796 }, {
1797 key: "__check__",
1798 value: function () {
1799 var _check__ = _asyncToGenerator(
1800 /*#__PURE__*/
1801 regeneratorRuntime.mark(function _callee10(weight) {
1802 var now;
1803 return regeneratorRuntime.wrap(function _callee10$(_context10) {
1804 while (1) {
1805 switch (_context10.prev = _context10.next) {
1806 case 0:
1807 _context10.next = 2;
1808 return this.yieldLoop();
1809
1810 case 2:
1811 now = Date.now();
1812 return _context10.abrupt("return", this.check(weight, now));
1813
1814 case 4:
1815 case "end":
1816 return _context10.stop();
1817 }
1818 }
1819 }, _callee10, this);
1820 }));
1821
1822 return function __check__(_x6) {
1823 return _check__.apply(this, arguments);
1824 };
1825 }()
1826 }, {
1827 key: "__register__",
1828 value: function () {
1829 var _register__ = _asyncToGenerator(
1830 /*#__PURE__*/
1831 regeneratorRuntime.mark(function _callee11(index, weight, expiration) {
1832 var now, wait;
1833 return regeneratorRuntime.wrap(function _callee11$(_context11) {
1834 while (1) {
1835 switch (_context11.prev = _context11.next) {
1836 case 0:
1837 _context11.next = 2;
1838 return this.yieldLoop();
1839
1840 case 2:
1841 now = Date.now();
1842
1843 if (!this.conditionsCheck(weight)) {
1844 _context11.next = 11;
1845 break;
1846 }
1847
1848 this._running += weight;
1849
1850 if (this.storeOptions.reservoir != null) {
1851 this.storeOptions.reservoir -= weight;
1852 }
1853
1854 wait = Math.max(this._nextRequest - now, 0);
1855 this._nextRequest = now + wait + this.storeOptions.minTime;
1856 return _context11.abrupt("return", {
1857 success: true,
1858 wait: wait,
1859 reservoir: this.storeOptions.reservoir
1860 });
1861
1862 case 11:
1863 return _context11.abrupt("return", {
1864 success: false
1865 });
1866
1867 case 12:
1868 case "end":
1869 return _context11.stop();
1870 }
1871 }
1872 }, _callee11, this);
1873 }));
1874
1875 return function __register__(_x7, _x8, _x9) {
1876 return _register__.apply(this, arguments);
1877 };
1878 }()
1879 }, {
1880 key: "strategyIsBlock",
1881 value: function strategyIsBlock() {
1882 return this.storeOptions.strategy === 3;
1883 }
1884 }, {
1885 key: "__submit__",
1886 value: function () {
1887 var _submit__ = _asyncToGenerator(
1888 /*#__PURE__*/
1889 regeneratorRuntime.mark(function _callee12(queueLength, weight) {
1890 var blocked, now, reachedHWM;
1891 return regeneratorRuntime.wrap(function _callee12$(_context12) {
1892 while (1) {
1893 switch (_context12.prev = _context12.next) {
1894 case 0:
1895 _context12.next = 2;
1896 return this.yieldLoop();
1897
1898 case 2:
1899 if (!(this.storeOptions.maxConcurrent != null && weight > this.storeOptions.maxConcurrent)) {
1900 _context12.next = 4;
1901 break;
1902 }
1903
1904 throw new BottleneckError$1("Impossible to add a job having a weight of ".concat(weight, " to a limiter having a maxConcurrent setting of ").concat(this.storeOptions.maxConcurrent));
1905
1906 case 4:
1907 now = Date.now();
1908 reachedHWM = this.storeOptions.highWater != null && queueLength === this.storeOptions.highWater && !this.check(weight, now);
1909 blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now));
1910
1911 if (blocked) {
1912 this._unblockTime = now + this.computePenalty();
1913 this._nextRequest = this._unblockTime + this.storeOptions.minTime;
1914
1915 this.instance._dropAllQueued();
1916 }
1917
1918 return _context12.abrupt("return", {
1919 reachedHWM: reachedHWM,
1920 blocked: blocked,
1921 strategy: this.storeOptions.strategy
1922 });
1923
1924 case 9:
1925 case "end":
1926 return _context12.stop();
1927 }
1928 }
1929 }, _callee12, this);
1930 }));
1931
1932 return function __submit__(_x10, _x11) {
1933 return _submit__.apply(this, arguments);
1934 };
1935 }()
1936 }, {
1937 key: "__free__",
1938 value: function () {
1939 var _free__ = _asyncToGenerator(
1940 /*#__PURE__*/
1941 regeneratorRuntime.mark(function _callee13(index, weight) {
1942 return regeneratorRuntime.wrap(function _callee13$(_context13) {
1943 while (1) {
1944 switch (_context13.prev = _context13.next) {
1945 case 0:
1946 _context13.next = 2;
1947 return this.yieldLoop();
1948
1949 case 2:
1950 this._running -= weight;
1951 this._done += weight;
1952
1953 this.instance._drainAll(this.computeCapacity());
1954
1955 return _context13.abrupt("return", {
1956 running: this._running
1957 });
1958
1959 case 6:
1960 case "end":
1961 return _context13.stop();
1962 }
1963 }
1964 }, _callee13, this);
1965 }));
1966
1967 return function __free__(_x12, _x13) {
1968 return _free__.apply(this, arguments);
1969 };
1970 }()
1971 }]);
1972
1973 return LocalDatastore;
1974 }();
1975
1976 var LocalDatastore_1 = LocalDatastore;
1977
1978 var lua = {
1979 "blacklist_client.lua": "local blacklist = ARGV[3]\n\nredis.call('zadd', client_last_seen_key, 0, blacklist)\n\nreturn {}\n",
1980 "check.lua": "local weight = tonumber(ARGV[3])\n\nlocal capacity = process_tick(now, false)['capacity']\nlocal nextRequest = tonumber(redis.call('hget', settings_key, 'nextRequest'))\n\nreturn conditions_check(capacity, weight) and nextRequest - now <= 0\n",
1981 "conditions_check.lua": "local conditions_check = function (capacity, weight)\n return capacity == nil or weight <= capacity\nend\n",
1982 "current_reservoir.lua": "return process_tick(now, false)['reservoir']\n",
1983 "done.lua": "process_tick(now, false)\n\nreturn tonumber(redis.call('hget', settings_key, 'done'))\n",
1984 "free.lua": "local index = ARGV[3]\n\nredis.call('zadd', job_expirations_key, 0, index)\n\nreturn process_tick(now, false)['running']\n",
1985 "get_time.lua": "redis.replicate_commands()\n\nlocal get_time = function ()\n local time = redis.call('time')\n\n return tonumber(time[1]..string.sub(time[2], 1, 3))\nend\n",
1986 "group_check.lua": "return not (redis.call('exists', settings_key) == 1)\n",
1987 "heartbeat.lua": "process_tick(now, true)\n",
1988 "increment_reservoir.lua": "local incr = tonumber(ARGV[3])\n\nredis.call('hincrby', settings_key, 'reservoir', incr)\n\nlocal reservoir = process_tick(now, true)['reservoir']\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn reservoir\n",
1989 "init.lua": "local clear = tonumber(ARGV[3])\nlocal limiter_version = ARGV[4]\nlocal num_static_argv = 4\n\nif clear == 1 then\n redis.call('del', unpack(KEYS))\nend\n\nif redis.call('exists', settings_key) == 0 then\n -- Create\n local args = {'hmset', settings_key}\n\n for i = num_static_argv + 1, #ARGV do\n table.insert(args, ARGV[i])\n end\n\n redis.call(unpack(args))\n redis.call('hmset', settings_key,\n 'nextRequest', now,\n 'lastReservoirRefresh', now,\n 'running', 0,\n 'done', 0,\n 'unblockTime', 0,\n 'capacityPriorityCounter', 0\n )\n\nelse\n -- Apply migrations\n local settings = redis.call('hmget', settings_key,\n 'id',\n 'version'\n )\n local id = settings[1]\n local current_version = settings[2]\n\n if current_version ~= limiter_version then\n local version_digits = {}\n for k, v in string.gmatch(current_version, \"([^.]+)\") do\n table.insert(version_digits, tonumber(k))\n end\n\n -- 2.10.0\n if version_digits[2] < 10 then\n redis.call('hsetnx', settings_key, 'reservoirRefreshInterval', '')\n redis.call('hsetnx', settings_key, 'reservoirRefreshAmount', '')\n redis.call('hsetnx', settings_key, 'lastReservoirRefresh', '')\n redis.call('hsetnx', settings_key, 'done', 0)\n redis.call('hset', settings_key, 'version', '2.10.0')\n end\n\n -- 2.11.1\n if version_digits[2] < 11 and version_digits[3] < 1 then\n if redis.call('hstrlen', settings_key, 'lastReservoirRefresh') == 0 then\n redis.call('hmset', settings_key,\n 'lastReservoirRefresh', now,\n 'version', '2.11.1'\n )\n end\n end\n\n -- 2.14.0\n if version_digits[2] < 14 then\n local old_running_key = 'b_'..id..'_running'\n local old_executing_key = 'b_'..id..'_executing'\n\n if redis.call('exists', old_running_key) == 1 then\n redis.call('rename', old_running_key, job_weights_key)\n end\n if redis.call('exists', old_executing_key) == 1 then\n redis.call('rename', old_executing_key, job_expirations_key)\n end\n redis.call('hset', settings_key, 'version', '2.14.0')\n end\n\n -- 2.15.2\n if version_digits[2] < 15 and version_digits[3] < 2 then\n redis.call('hsetnx', settings_key, 'capacityPriorityCounter', 0)\n redis.call('hset', settings_key, 'version', '2.15.2')\n end\n\n end\n\n process_tick(now, false)\nend\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn {}\n",
1990 "process_tick.lua": "local process_tick = function (now, always_publish)\n\n local compute_capacity = function (maxConcurrent, running, reservoir)\n if maxConcurrent ~= nil and reservoir ~= nil then\n return math.min((maxConcurrent - running), reservoir)\n elseif maxConcurrent ~= nil then\n return maxConcurrent - running\n elseif reservoir ~= nil then\n return reservoir\n else\n return nil\n end\n end\n\n local settings = redis.call('hmget', settings_key,\n 'id',\n 'maxConcurrent',\n 'running',\n 'reservoir',\n 'reservoirRefreshInterval',\n 'reservoirRefreshAmount',\n 'lastReservoirRefresh',\n 'capacityPriorityCounter'\n )\n local id = settings[1]\n local maxConcurrent = tonumber(settings[2])\n local running = tonumber(settings[3])\n local reservoir = tonumber(settings[4])\n local reservoirRefreshInterval = tonumber(settings[5])\n local reservoirRefreshAmount = tonumber(settings[6])\n local lastReservoirRefresh = tonumber(settings[7])\n local capacityPriorityCounter = tonumber(settings[8])\n\n local initial_capacity = compute_capacity(maxConcurrent, running, reservoir)\n\n --\n -- Process 'running' changes\n --\n local expired = redis.call('zrangebyscore', job_expirations_key, '-inf', '('..now)\n\n if #expired > 0 then\n redis.call('zremrangebyscore', job_expirations_key, '-inf', '('..now)\n\n local flush_batch = function (batch, acc)\n local weights = redis.call('hmget', job_weights_key, unpack(batch))\n redis.call('hdel', job_weights_key, unpack(batch))\n local clients = redis.call('hmget', job_clients_key, unpack(batch))\n redis.call('hdel', job_clients_key, unpack(batch))\n\n -- Calculate sum of removed weights\n for i = 1, #weights do\n acc['total'] = acc['total'] + (tonumber(weights[i]) or 0)\n end\n\n -- Calculate sum of removed weights by client\n local client_weights = {}\n for i = 1, #clients do\n if weights[i] ~= nil then\n acc['client_weights'][clients[i]] = (acc['client_weights'][clients[i]] or 0) + tonumber(weights[i])\n end\n end\n end\n\n local acc = {\n ['total'] = 0,\n ['client_weights'] = {}\n }\n local batch_size = 1000\n\n -- Compute changes to Zsets and apply changes to Hashes\n for i = 1, #expired, batch_size do\n local batch = {}\n for j = i, math.min(i + batch_size - 1, #expired) do\n table.insert(batch, expired[j])\n end\n\n flush_batch(batch, acc)\n end\n\n -- Apply changes to Zsets\n if acc['total'] > 0 then\n redis.call('hincrby', settings_key, 'done', acc['total'])\n running = tonumber(redis.call('hincrby', settings_key, 'running', -acc['total']))\n end\n\n for client, weight in pairs(acc['client_weights']) do\n redis.call('zincrby', client_running_key, -weight, client)\n end\n end\n\n --\n -- Process 'reservoir' changes\n --\n local reservoirRefreshActive = reservoirRefreshInterval ~= nil and reservoirRefreshAmount ~= nil\n if reservoirRefreshActive and now >= lastReservoirRefresh + reservoirRefreshInterval then\n reservoir = reservoirRefreshAmount\n redis.call('hmset', settings_key,\n 'reservoir', reservoir,\n 'lastReservoirRefresh', now\n )\n end\n\n --\n -- Broadcast capacity changes\n --\n local final_capacity = compute_capacity(maxConcurrent, running, reservoir)\n\n if always_publish or (initial_capacity ~= nil and final_capacity == nil) then\n -- always_publish or was not unlimited, now unlimited\n redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))\n\n elseif initial_capacity ~= nil and final_capacity ~= nil and final_capacity > initial_capacity then\n -- capacity was increased\n -- send the capacity message to the limiter having the lowest number of running jobs\n -- the tiebreaker is the limiter having not registered a job in the longest time\n\n local lowest_concurrency_value = nil\n local lowest_concurrency_clients = {}\n local lowest_concurrency_last_registered = {}\n local client_concurrencies = redis.call('zrange', client_running_key, 0, -1, 'withscores')\n local valid_clients = redis.call('zrangebyscore', client_last_seen_key, (now - 10000), 'inf')\n local valid_clients_lookup = {}\n for i = 1, #valid_clients do\n valid_clients_lookup[valid_clients[i]] = true\n end\n\n for i = 1, #client_concurrencies, 2 do\n local client = client_concurrencies[i]\n local concurrency = tonumber(client_concurrencies[i+1])\n\n if (\n lowest_concurrency_value == nil or lowest_concurrency_value == concurrency\n ) and (\n valid_clients_lookup[client]\n ) and (\n tonumber(redis.call('hget', client_num_queued_key, client)) > 0\n ) then\n lowest_concurrency_value = concurrency\n table.insert(lowest_concurrency_clients, client)\n local last_registered = tonumber(redis.call('zscore', client_last_registered_key, client))\n table.insert(lowest_concurrency_last_registered, last_registered)\n end\n end\n\n if #lowest_concurrency_clients > 0 then\n local position = 1\n local earliest = lowest_concurrency_last_registered[1]\n\n for i,v in ipairs(lowest_concurrency_last_registered) do\n if v < earliest then\n position = i\n earliest = v\n end\n end\n\n local next_client = lowest_concurrency_clients[position]\n redis.call('publish', 'b_'..id,\n 'capacity-priority:'..(final_capacity or '')..\n ':'..next_client..\n ':'..capacityPriorityCounter\n )\n redis.call('hincrby', settings_key, 'capacityPriorityCounter', '1')\n else\n redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))\n end\n end\n\n return {\n ['capacity'] = final_capacity,\n ['running'] = running,\n ['reservoir'] = reservoir\n }\nend\n",
1991 "queued.lua": "local valid_clients = redis.call('zrangebyscore', client_last_seen_key, (now - 10000), 'inf')\nlocal client_queued = redis.call('hmget', client_num_queued_key, unpack(valid_clients))\n\nlocal sum = 0\nfor i = 1, #client_queued do\n sum = sum + tonumber(client_queued[i])\nend\n\nreturn sum\n",
1992 "refresh_expiration.lua": "local refresh_expiration = function (now, nextRequest, groupTimeout)\n\n if groupTimeout ~= nil then\n local ttl = (nextRequest + groupTimeout) - now\n\n for i = 1, #KEYS do\n redis.call('pexpire', KEYS[i], ttl)\n end\n end\n\nend\n",
1993 "refs.lua": "local settings_key = KEYS[1]\nlocal job_weights_key = KEYS[2]\nlocal job_expirations_key = KEYS[3]\nlocal job_clients_key = KEYS[4]\nlocal client_running_key = KEYS[5]\nlocal client_num_queued_key = KEYS[6]\nlocal client_last_registered_key = KEYS[7]\nlocal client_last_seen_key = KEYS[8]\n\nlocal now = tonumber(ARGV[1])\nlocal client = ARGV[2]\n\nredis.call('zadd', client_last_seen_key, now, client)\n",
1994 "register.lua": "local index = ARGV[3]\nlocal weight = tonumber(ARGV[4])\nlocal expiration = tonumber(ARGV[5])\n\nlocal state = process_tick(now, false)\nlocal capacity = state['capacity']\nlocal reservoir = state['reservoir']\n\nlocal settings = redis.call('hmget', settings_key,\n 'nextRequest',\n 'minTime',\n 'groupTimeout'\n)\nlocal nextRequest = tonumber(settings[1])\nlocal minTime = tonumber(settings[2])\nlocal groupTimeout = tonumber(settings[3])\n\nif conditions_check(capacity, weight) then\n\n redis.call('hincrby', settings_key, 'running', weight)\n redis.call('hset', job_weights_key, index, weight)\n if expiration ~= nil then\n redis.call('zadd', job_expirations_key, now + expiration, index)\n end\n redis.call('hset', job_clients_key, index, client)\n redis.call('zincrby', client_running_key, weight, client)\n redis.call('hincrby', client_num_queued_key, client, -1)\n redis.call('zadd', client_last_registered_key, now, client)\n\n local wait = math.max(nextRequest - now, 0)\n local newNextRequest = now + wait + minTime\n\n if reservoir == nil then\n redis.call('hset', settings_key,\n 'nextRequest', newNextRequest\n )\n else\n reservoir = reservoir - weight\n redis.call('hmset', settings_key,\n 'reservoir', reservoir,\n 'nextRequest', newNextRequest\n )\n end\n\n refresh_expiration(now, newNextRequest, groupTimeout)\n\n return {true, wait, reservoir}\n\nelse\n return {false}\nend\n",
1995 "register_client.lua": "local queued = tonumber(ARGV[3])\n\nredis.call('zadd', client_running_key, 0, client)\nredis.call('hset', client_num_queued_key, client, queued)\nredis.call('zadd', client_last_registered_key, 0, client)\n\nreturn {}\n",
1996 "running.lua": "return process_tick(now, false)['running']\n",
1997 "submit.lua": "local queueLength = tonumber(ARGV[3])\nlocal weight = tonumber(ARGV[4])\n\nlocal capacity = process_tick(now, false)['capacity']\n\nlocal settings = redis.call('hmget', settings_key,\n 'id',\n 'maxConcurrent',\n 'highWater',\n 'nextRequest',\n 'strategy',\n 'unblockTime',\n 'penalty',\n 'minTime',\n 'groupTimeout'\n)\nlocal id = settings[1]\nlocal maxConcurrent = tonumber(settings[2])\nlocal highWater = tonumber(settings[3])\nlocal nextRequest = tonumber(settings[4])\nlocal strategy = tonumber(settings[5])\nlocal unblockTime = tonumber(settings[6])\nlocal penalty = tonumber(settings[7])\nlocal minTime = tonumber(settings[8])\nlocal groupTimeout = tonumber(settings[9])\n\nif maxConcurrent ~= nil and weight > maxConcurrent then\n return redis.error_reply('OVERWEIGHT:'..weight..':'..maxConcurrent)\nend\n\nlocal reachedHWM = (highWater ~= nil and queueLength == highWater\n and not (\n conditions_check(capacity, weight)\n and nextRequest - now <= 0\n )\n)\n\nlocal blocked = strategy == 3 and (reachedHWM or unblockTime >= now)\n\nif blocked then\n local computedPenalty = penalty\n if computedPenalty == nil then\n if minTime == 0 then\n computedPenalty = 5000\n else\n computedPenalty = 15 * minTime\n end\n end\n\n local newNextRequest = now + computedPenalty + minTime\n\n redis.call('hmset', settings_key,\n 'unblockTime', now + computedPenalty,\n 'nextRequest', newNextRequest\n )\n\n local clients_queued_reset = redis.call('hkeys', client_num_queued_key)\n local queued_reset = {}\n for i = 1, #clients_queued_reset do\n table.insert(queued_reset, clients_queued_reset[i])\n table.insert(queued_reset, 0)\n end\n redis.call('hmset', client_num_queued_key, unpack(queued_reset))\n\n redis.call('publish', 'b_'..id, 'blocked:')\n\n refresh_expiration(now, newNextRequest, groupTimeout)\nend\n\nif not blocked and not reachedHWM then\n redis.call('hincrby', client_num_queued_key, client, 1)\nend\n\nreturn {reachedHWM, blocked, strategy}\n",
1998 "update_settings.lua": "local num_static_argv = 2\n\nlocal args = {'hmset', settings_key}\n\nfor i = num_static_argv + 1, #ARGV do\n table.insert(args, ARGV[i])\nend\n\nredis.call(unpack(args))\n\nprocess_tick(now, true)\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn {}\n",
1999 "validate_keys.lua": "if not (redis.call('exists', settings_key) == 1) then\n return redis.error_reply('SETTINGS_KEY_NOT_FOUND')\nend\n"
2000 };
2001
2002 var lua$1 = /*#__PURE__*/Object.freeze({
2003 default: lua
2004 });
2005
2006 var require$$0 = getCjsExportFromNamespace(lua$1);
2007
2008 var Scripts = createCommonjsModule(function (module, exports) {
2009 var headers, lua, templates;
2010 lua = require$$0;
2011 headers = {
2012 refs: lua["refs.lua"],
2013 validate_keys: lua["validate_keys.lua"],
2014 refresh_expiration: lua["refresh_expiration.lua"],
2015 process_tick: lua["process_tick.lua"],
2016 conditions_check: lua["conditions_check.lua"],
2017 get_time: lua["get_time.lua"]
2018 };
2019
2020 exports.allKeys = function (id) {
2021 return [
2022 /*
2023 HASH
2024 */
2025 "b_".concat(id, "_settings"),
2026 /*
2027 HASH
2028 job index -> weight
2029 */
2030 "b_".concat(id, "_job_weights"),
2031 /*
2032 ZSET
2033 job index -> expiration
2034 */
2035 "b_".concat(id, "_job_expirations"),
2036 /*
2037 HASH
2038 job index -> client
2039 */
2040 "b_".concat(id, "_job_clients"),
2041 /*
2042 ZSET
2043 client -> sum running
2044 */
2045 "b_".concat(id, "_client_running"),
2046 /*
2047 HASH
2048 client -> num queued
2049 */
2050 "b_".concat(id, "_client_num_queued"),
2051 /*
2052 ZSET
2053 client -> last job registered
2054 */
2055 "b_".concat(id, "_client_last_registered"),
2056 /*
2057 ZSET
2058 client -> last seen
2059 */
2060 "b_".concat(id, "_client_last_seen")];
2061 };
2062
2063 templates = {
2064 init: {
2065 keys: exports.allKeys,
2066 headers: ["process_tick"],
2067 refresh_expiration: true,
2068 code: lua["init.lua"]
2069 },
2070 group_check: {
2071 keys: exports.allKeys,
2072 headers: [],
2073 refresh_expiration: false,
2074 code: lua["group_check.lua"]
2075 },
2076 register_client: {
2077 keys: exports.allKeys,
2078 headers: ["validate_keys"],
2079 refresh_expiration: false,
2080 code: lua["register_client.lua"]
2081 },
2082 blacklist_client: {
2083 keys: exports.allKeys,
2084 headers: ["validate_keys"],
2085 refresh_expiration: false,
2086 code: lua["blacklist_client.lua"]
2087 },
2088 heartbeat: {
2089 keys: exports.allKeys,
2090 headers: ["validate_keys", "process_tick"],
2091 refresh_expiration: false,
2092 code: lua["heartbeat.lua"]
2093 },
2094 update_settings: {
2095 keys: exports.allKeys,
2096 headers: ["validate_keys", "process_tick"],
2097 refresh_expiration: true,
2098 code: lua["update_settings.lua"]
2099 },
2100 running: {
2101 keys: exports.allKeys,
2102 headers: ["validate_keys", "process_tick"],
2103 refresh_expiration: false,
2104 code: lua["running.lua"]
2105 },
2106 queued: {
2107 keys: exports.allKeys,
2108 headers: ["validate_keys"],
2109 refresh_expiration: false,
2110 code: lua["queued.lua"]
2111 },
2112 done: {
2113 keys: exports.allKeys,
2114 headers: ["validate_keys", "process_tick"],
2115 refresh_expiration: false,
2116 code: lua["done.lua"]
2117 },
2118 check: {
2119 keys: exports.allKeys,
2120 headers: ["validate_keys", "process_tick", "conditions_check"],
2121 refresh_expiration: false,
2122 code: lua["check.lua"]
2123 },
2124 submit: {
2125 keys: exports.allKeys,
2126 headers: ["validate_keys", "process_tick", "conditions_check"],
2127 refresh_expiration: true,
2128 code: lua["submit.lua"]
2129 },
2130 register: {
2131 keys: exports.allKeys,
2132 headers: ["validate_keys", "process_tick", "conditions_check"],
2133 refresh_expiration: true,
2134 code: lua["register.lua"]
2135 },
2136 free: {
2137 keys: exports.allKeys,
2138 headers: ["validate_keys", "process_tick"],
2139 refresh_expiration: false,
2140 code: lua["free.lua"]
2141 },
2142 current_reservoir: {
2143 keys: exports.allKeys,
2144 headers: ["validate_keys", "process_tick"],
2145 refresh_expiration: false,
2146 code: lua["current_reservoir.lua"]
2147 },
2148 increment_reservoir: {
2149 keys: exports.allKeys,
2150 headers: ["validate_keys", "process_tick"],
2151 refresh_expiration: true,
2152 code: lua["increment_reservoir.lua"]
2153 }
2154 };
2155 exports.names = Object.keys(templates);
2156
2157 exports.keys = function (name, id) {
2158 return templates[name].keys(id);
2159 };
2160
2161 exports.payload = function (name) {
2162 var template;
2163 template = templates[name];
2164 return Array.prototype.concat(headers.refs, template.headers.map(function (h) {
2165 return headers[h];
2166 }), template.refresh_expiration ? headers.refresh_expiration : "", template.code).join("\n");
2167 };
2168 });
2169 var Scripts_1 = Scripts.allKeys;
2170 var Scripts_2 = Scripts.names;
2171 var Scripts_3 = Scripts.keys;
2172 var Scripts_4 = Scripts.payload;
2173
2174 var Events$2, RedisConnection, Scripts$1, parser$2;
2175 parser$2 = parser;
2176 Events$2 = Events_1;
2177 Scripts$1 = Scripts;
2178
2179 RedisConnection = function () {
2180 var RedisConnection =
2181 /*#__PURE__*/
2182 function () {
2183 function RedisConnection() {
2184 var _this = this;
2185
2186 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2187
2188 _classCallCheck(this, RedisConnection);
2189
2190 var Redis;
2191 Redis = eval("require")("redis"); // Obfuscated or else Webpack/Angular will try to inline the optional redis module
2192
2193 parser$2.load(options, this.defaults, this);
2194
2195 if (this.Events == null) {
2196 this.Events = new Events$2(this);
2197 }
2198
2199 this.terminated = false;
2200
2201 if (this.client == null) {
2202 this.client = Redis.createClient(this.clientOptions);
2203 }
2204
2205 this.subscriber = this.client.duplicate();
2206 this.limiters = {};
2207 this.shas = {};
2208 this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(function () {
2209 return _this._loadScripts();
2210 }).then(function () {
2211 return {
2212 client: _this.client,
2213 subscriber: _this.subscriber
2214 };
2215 });
2216 }
2217
2218 _createClass(RedisConnection, [{
2219 key: "_setup",
2220 value: function _setup(client, sub) {
2221 var _this2 = this;
2222
2223 client.setMaxListeners(0);
2224 return new this.Promise(function (resolve, reject) {
2225 client.on("error", function (e) {
2226 return _this2.Events.trigger("error", e);
2227 });
2228
2229 if (sub) {
2230 client.on("message", function (channel, message) {
2231 var ref;
2232 return (ref = _this2.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0;
2233 });
2234 }
2235
2236 if (client.ready) {
2237 return resolve();
2238 } else {
2239 return client.once("ready", resolve);
2240 }
2241 });
2242 }
2243 }, {
2244 key: "_loadScript",
2245 value: function _loadScript(name) {
2246 var _this3 = this;
2247
2248 return new this.Promise(function (resolve, reject) {
2249 var payload;
2250 payload = Scripts$1.payload(name);
2251 return _this3.client.multi([["script", "load", payload]]).exec(function (err, replies) {
2252 if (err != null) {
2253 return reject(err);
2254 }
2255
2256 _this3.shas[name] = replies[0];
2257 return resolve(replies[0]);
2258 });
2259 });
2260 }
2261 }, {
2262 key: "_loadScripts",
2263 value: function _loadScripts() {
2264 var _this4 = this;
2265
2266 return this.Promise.all(Scripts$1.names.map(function (k) {
2267 return _this4._loadScript(k);
2268 }));
2269 }
2270 }, {
2271 key: "__runCommand__",
2272 value: function () {
2273 var _runCommand__ = _asyncToGenerator(
2274 /*#__PURE__*/
2275 regeneratorRuntime.mark(function _callee(cmd) {
2276 var _this5 = this;
2277
2278 return regeneratorRuntime.wrap(function _callee$(_context) {
2279 while (1) {
2280 switch (_context.prev = _context.next) {
2281 case 0:
2282 _context.next = 2;
2283 return this.ready;
2284
2285 case 2:
2286 return _context.abrupt("return", new this.Promise(function (resolve, reject) {
2287 return _this5.client.multi([cmd]).exec_atomic(function (err, replies) {
2288 if (err != null) {
2289 return reject(err);
2290 } else {
2291 return resolve(replies[0]);
2292 }
2293 });
2294 }));
2295
2296 case 3:
2297 case "end":
2298 return _context.stop();
2299 }
2300 }
2301 }, _callee, this);
2302 }));
2303
2304 return function __runCommand__(_x) {
2305 return _runCommand__.apply(this, arguments);
2306 };
2307 }()
2308 }, {
2309 key: "__addLimiter__",
2310 value: function __addLimiter__(instance) {
2311 var _this6 = this;
2312
2313 return this.Promise.all([instance.channel(), instance.channel_client()].map(function (channel) {
2314 return new _this6.Promise(function (resolve, reject) {
2315 var _handler;
2316
2317 _handler = function handler(chan) {
2318 if (chan === channel) {
2319 _this6.subscriber.removeListener("subscribe", _handler);
2320
2321 _this6.limiters[channel] = instance;
2322 return resolve();
2323 }
2324 };
2325
2326 _this6.subscriber.on("subscribe", _handler);
2327
2328 return _this6.subscriber.subscribe(channel);
2329 });
2330 }));
2331 }
2332 }, {
2333 key: "__removeLimiter__",
2334 value: function __removeLimiter__(instance) {
2335 var _this7 = this;
2336
2337 return this.Promise.all([instance.channel(), instance.channel_client()].map(
2338 /*#__PURE__*/
2339 function () {
2340 var _ref = _asyncToGenerator(
2341 /*#__PURE__*/
2342 regeneratorRuntime.mark(function _callee2(channel) {
2343 return regeneratorRuntime.wrap(function _callee2$(_context2) {
2344 while (1) {
2345 switch (_context2.prev = _context2.next) {
2346 case 0:
2347 if (_this7.terminated) {
2348 _context2.next = 3;
2349 break;
2350 }
2351
2352 _context2.next = 3;
2353 return new _this7.Promise(function (resolve, reject) {
2354 return _this7.subscriber.unsubscribe(channel, function (err, chan) {
2355 if (err != null) {
2356 return reject(err);
2357 }
2358
2359 if (chan === channel) {
2360 return resolve();
2361 }
2362 });
2363 });
2364
2365 case 3:
2366 return _context2.abrupt("return", delete _this7.limiters[channel]);
2367
2368 case 4:
2369 case "end":
2370 return _context2.stop();
2371 }
2372 }
2373 }, _callee2, this);
2374 }));
2375
2376 return function (_x2) {
2377 return _ref.apply(this, arguments);
2378 };
2379 }()));
2380 }
2381 }, {
2382 key: "__scriptArgs__",
2383 value: function __scriptArgs__(name, id, args, cb) {
2384 var keys;
2385 keys = Scripts$1.keys(name, id);
2386 return [this.shas[name], keys.length].concat(keys, args, cb);
2387 }
2388 }, {
2389 key: "__scriptFn__",
2390 value: function __scriptFn__(name) {
2391 return this.client.evalsha.bind(this.client);
2392 }
2393 }, {
2394 key: "disconnect",
2395 value: function disconnect() {
2396 var flush = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
2397 var i, k, len, ref;
2398 ref = Object.keys(this.limiters);
2399
2400 for (i = 0, len = ref.length; i < len; i++) {
2401 k = ref[i];
2402 clearInterval(this.limiters[k]._store.heartbeat);
2403 }
2404
2405 this.limiters = {};
2406 this.terminated = true;
2407 this.client.end(flush);
2408 this.subscriber.end(flush);
2409 return this.Promise.resolve();
2410 }
2411 }]);
2412
2413 return RedisConnection;
2414 }();
2415 RedisConnection.prototype.datastore = "redis";
2416 RedisConnection.prototype.defaults = {
2417 clientOptions: {},
2418 client: null,
2419 Promise: Promise,
2420 Events: null
2421 };
2422 return RedisConnection;
2423 }.call(commonjsGlobal);
2424
2425 var RedisConnection_1 = RedisConnection;
2426
2427 var Events$3, IORedisConnection, Scripts$2, parser$3;
2428 parser$3 = parser;
2429 Events$3 = Events_1;
2430 Scripts$2 = Scripts;
2431
2432 IORedisConnection = function () {
2433 var IORedisConnection =
2434 /*#__PURE__*/
2435 function () {
2436 function IORedisConnection() {
2437 var _this = this;
2438
2439 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2440
2441 _classCallCheck(this, IORedisConnection);
2442
2443 var Redis;
2444 Redis = eval("require")("ioredis"); // Obfuscated or else Webpack/Angular will try to inline the optional ioredis module
2445
2446 parser$3.load(options, this.defaults, this);
2447
2448 if (this.Events == null) {
2449 this.Events = new Events$3(this);
2450 }
2451
2452 this.terminated = false;
2453
2454 if (this.clusterNodes != null) {
2455 this.client = new Redis.Cluster(this.clusterNodes, this.clientOptions);
2456 this.subscriber = new Redis.Cluster(this.clusterNodes, this.clientOptions);
2457 } else {
2458 if (this.client == null) {
2459 this.client = new Redis(this.clientOptions);
2460 }
2461
2462 this.subscriber = this.client.duplicate();
2463 }
2464
2465 this.limiters = {};
2466 this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(function () {
2467 _this._loadScripts();
2468
2469 return {
2470 client: _this.client,
2471 subscriber: _this.subscriber
2472 };
2473 });
2474 }
2475
2476 _createClass(IORedisConnection, [{
2477 key: "_setup",
2478 value: function _setup(client, sub) {
2479 var _this2 = this;
2480
2481 client.setMaxListeners(0);
2482 return new this.Promise(function (resolve, reject) {
2483 client.on("error", function (e) {
2484 return _this2.Events.trigger("error", e);
2485 });
2486
2487 if (sub) {
2488 client.on("message", function (channel, message) {
2489 var ref;
2490 return (ref = _this2.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0;
2491 });
2492 }
2493
2494 if (client.status === "ready") {
2495 return resolve();
2496 } else {
2497 return client.once("ready", resolve);
2498 }
2499 });
2500 }
2501 }, {
2502 key: "_loadScripts",
2503 value: function _loadScripts() {
2504 var _this3 = this;
2505
2506 return Scripts$2.names.forEach(function (name) {
2507 return _this3.client.defineCommand(name, {
2508 lua: Scripts$2.payload(name)
2509 });
2510 });
2511 }
2512 }, {
2513 key: "__runCommand__",
2514 value: function () {
2515 var _runCommand__ = _asyncToGenerator(
2516 /*#__PURE__*/
2517 regeneratorRuntime.mark(function _callee(cmd) {
2518 var _, deleted, _ref, _ref2, _ref2$;
2519
2520 return regeneratorRuntime.wrap(function _callee$(_context) {
2521 while (1) {
2522 switch (_context.prev = _context.next) {
2523 case 0:
2524 _context.next = 2;
2525 return this.ready;
2526
2527 case 2:
2528 _context.next = 4;
2529 return this.client.pipeline([cmd]).exec();
2530
2531 case 4:
2532 _ref = _context.sent;
2533 _ref2 = _slicedToArray(_ref, 1);
2534 _ref2$ = _slicedToArray(_ref2[0], 2);
2535 _ = _ref2$[0];
2536 deleted = _ref2$[1];
2537 return _context.abrupt("return", deleted);
2538
2539 case 10:
2540 case "end":
2541 return _context.stop();
2542 }
2543 }
2544 }, _callee, this);
2545 }));
2546
2547 return function __runCommand__(_x) {
2548 return _runCommand__.apply(this, arguments);
2549 };
2550 }()
2551 }, {
2552 key: "__addLimiter__",
2553 value: function __addLimiter__(instance) {
2554 var _this4 = this;
2555
2556 return this.Promise.all([instance.channel(), instance.channel_client()].map(function (channel) {
2557 return new _this4.Promise(function (resolve, reject) {
2558 return _this4.subscriber.subscribe(channel, function () {
2559 _this4.limiters[channel] = instance;
2560 return resolve();
2561 });
2562 });
2563 }));
2564 }
2565 }, {
2566 key: "__removeLimiter__",
2567 value: function __removeLimiter__(instance) {
2568 var _this5 = this;
2569
2570 return [instance.channel(), instance.channel_client()].forEach(
2571 /*#__PURE__*/
2572 function () {
2573 var _ref3 = _asyncToGenerator(
2574 /*#__PURE__*/
2575 regeneratorRuntime.mark(function _callee2(channel) {
2576 return regeneratorRuntime.wrap(function _callee2$(_context2) {
2577 while (1) {
2578 switch (_context2.prev = _context2.next) {
2579 case 0:
2580 if (_this5.terminated) {
2581 _context2.next = 3;
2582 break;
2583 }
2584
2585 _context2.next = 3;
2586 return _this5.subscriber.unsubscribe(channel);
2587
2588 case 3:
2589 return _context2.abrupt("return", delete _this5.limiters[channel]);
2590
2591 case 4:
2592 case "end":
2593 return _context2.stop();
2594 }
2595 }
2596 }, _callee2, this);
2597 }));
2598
2599 return function (_x2) {
2600 return _ref3.apply(this, arguments);
2601 };
2602 }());
2603 }
2604 }, {
2605 key: "__scriptArgs__",
2606 value: function __scriptArgs__(name, id, args, cb) {
2607 var keys;
2608 keys = Scripts$2.keys(name, id);
2609 return [keys.length].concat(keys, args, cb);
2610 }
2611 }, {
2612 key: "__scriptFn__",
2613 value: function __scriptFn__(name) {
2614 return this.client[name].bind(this.client);
2615 }
2616 }, {
2617 key: "disconnect",
2618 value: function disconnect() {
2619 var flush = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
2620 var i, k, len, ref;
2621 ref = Object.keys(this.limiters);
2622
2623 for (i = 0, len = ref.length; i < len; i++) {
2624 k = ref[i];
2625 clearInterval(this.limiters[k]._store.heartbeat);
2626 }
2627
2628 this.limiters = {};
2629 this.terminated = true;
2630
2631 if (flush) {
2632 return this.Promise.all([this.client.quit(), this.subscriber.quit()]);
2633 } else {
2634 this.client.disconnect();
2635 this.subscriber.disconnect();
2636 return this.Promise.resolve();
2637 }
2638 }
2639 }]);
2640
2641 return IORedisConnection;
2642 }();
2643 IORedisConnection.prototype.datastore = "ioredis";
2644 IORedisConnection.prototype.defaults = {
2645 clientOptions: {},
2646 clusterNodes: null,
2647 client: null,
2648 Promise: Promise,
2649 Events: null
2650 };
2651 return IORedisConnection;
2652 }.call(commonjsGlobal);
2653
2654 var IORedisConnection_1 = IORedisConnection;
2655
2656 var BottleneckError$2, IORedisConnection$1, RedisConnection$1, RedisDatastore, parser$4;
2657 parser$4 = parser;
2658 BottleneckError$2 = BottleneckError_1;
2659 RedisConnection$1 = RedisConnection_1;
2660 IORedisConnection$1 = IORedisConnection_1;
2661
2662 RedisDatastore =
2663 /*#__PURE__*/
2664 function () {
2665 function RedisDatastore(instance, storeOptions, storeInstanceOptions) {
2666 var _this = this;
2667
2668 _classCallCheck(this, RedisDatastore);
2669
2670 this.instance = instance;
2671 this.storeOptions = storeOptions;
2672 this.originalId = this.instance.id;
2673 this.clientId = this.instance._randomIndex();
2674 parser$4.load(storeInstanceOptions, storeInstanceOptions, this);
2675 this.clients = {};
2676 this.capacityPriorityCounters = {};
2677 this.sharedConnection = this.connection != null;
2678
2679 if (this.connection == null) {
2680 this.connection = this.instance.datastore === "redis" ? new RedisConnection$1({
2681 clientOptions: this.clientOptions,
2682 Promise: this.Promise,
2683 Events: this.instance.Events
2684 }) : this.instance.datastore === "ioredis" ? new IORedisConnection$1({
2685 clientOptions: this.clientOptions,
2686 clusterNodes: this.clusterNodes,
2687 Promise: this.Promise,
2688 Events: this.instance.Events
2689 }) : void 0;
2690 }
2691
2692 this.instance.connection = this.connection;
2693 this.instance.datastore = this.connection.datastore;
2694 this.ready = this.connection.ready.then(function (clients) {
2695 _this.clients = clients;
2696 return _this.runScript("init", _this.prepareInitSettings(_this.clearDatastore));
2697 }).then(function () {
2698 return _this.connection.__addLimiter__(_this.instance);
2699 }).then(function () {
2700 return _this.runScript("register_client", [_this.instance.queued()]);
2701 }).then(function () {
2702 var base;
2703
2704 if (typeof (base = _this.heartbeat = setInterval(function () {
2705 return _this.runScript("heartbeat", []).catch(function (e) {
2706 return _this.instance.Events.trigger("error", e);
2707 });
2708 }, _this.heartbeatInterval)).unref === "function") {
2709 base.unref();
2710 }
2711
2712 return _this.clients;
2713 });
2714 }
2715
2716 _createClass(RedisDatastore, [{
2717 key: "__publish__",
2718 value: function () {
2719 var _publish__ = _asyncToGenerator(
2720 /*#__PURE__*/
2721 regeneratorRuntime.mark(function _callee(message) {
2722 var client, _ref;
2723
2724 return regeneratorRuntime.wrap(function _callee$(_context) {
2725 while (1) {
2726 switch (_context.prev = _context.next) {
2727 case 0:
2728 _context.next = 2;
2729 return this.ready;
2730
2731 case 2:
2732 _ref = _context.sent;
2733 client = _ref.client;
2734 return _context.abrupt("return", client.publish(this.instance.channel(), "message:".concat(message.toString())));
2735
2736 case 5:
2737 case "end":
2738 return _context.stop();
2739 }
2740 }
2741 }, _callee, this);
2742 }));
2743
2744 return function __publish__(_x) {
2745 return _publish__.apply(this, arguments);
2746 };
2747 }()
2748 }, {
2749 key: "onMessage",
2750 value: function () {
2751 var _onMessage = _asyncToGenerator(
2752 /*#__PURE__*/
2753 regeneratorRuntime.mark(function _callee3(channel, message) {
2754 var _this2 = this;
2755
2756 var capacity, counter, data, drained, e, newCapacity, pos, priorityClient, rawCapacity, type, _ref2, _data$split, _data$split2;
2757
2758 return regeneratorRuntime.wrap(function _callee3$(_context3) {
2759 while (1) {
2760 switch (_context3.prev = _context3.next) {
2761 case 0:
2762 _context3.prev = 0;
2763 pos = message.indexOf(":");
2764 _ref2 = [message.slice(0, pos), message.slice(pos + 1)];
2765 type = _ref2[0];
2766 data = _ref2[1];
2767
2768 if (!(type === "capacity")) {
2769 _context3.next = 11;
2770 break;
2771 }
2772
2773 _context3.next = 8;
2774 return this.instance._drainAll(data.length > 0 ? ~~data : void 0);
2775
2776 case 8:
2777 return _context3.abrupt("return", _context3.sent);
2778
2779 case 11:
2780 if (!(type === "capacity-priority")) {
2781 _context3.next = 37;
2782 break;
2783 }
2784
2785 _data$split = data.split(":");
2786 _data$split2 = _slicedToArray(_data$split, 3);
2787 rawCapacity = _data$split2[0];
2788 priorityClient = _data$split2[1];
2789 counter = _data$split2[2];
2790 capacity = rawCapacity.length > 0 ? ~~rawCapacity : void 0;
2791
2792 if (!(priorityClient === this.clientId)) {
2793 _context3.next = 28;
2794 break;
2795 }
2796
2797 _context3.next = 21;
2798 return this.instance._drainAll(capacity);
2799
2800 case 21:
2801 drained = _context3.sent;
2802 newCapacity = capacity != null ? capacity - (drained || 0) : "";
2803 _context3.next = 25;
2804 return this.clients.client.publish(this.instance.channel(), "capacity-priority:".concat(newCapacity, "::").concat(counter));
2805
2806 case 25:
2807 return _context3.abrupt("return", _context3.sent);
2808
2809 case 28:
2810 if (!(priorityClient === "")) {
2811 _context3.next = 34;
2812 break;
2813 }
2814
2815 clearTimeout(this.capacityPriorityCounters[counter]);
2816 delete this.capacityPriorityCounters[counter];
2817 return _context3.abrupt("return", this.instance._drainAll(capacity));
2818
2819 case 34:
2820 return _context3.abrupt("return", this.capacityPriorityCounters[counter] = setTimeout(
2821 /*#__PURE__*/
2822 _asyncToGenerator(
2823 /*#__PURE__*/
2824 regeneratorRuntime.mark(function _callee2() {
2825 var e;
2826 return regeneratorRuntime.wrap(function _callee2$(_context2) {
2827 while (1) {
2828 switch (_context2.prev = _context2.next) {
2829 case 0:
2830 _context2.prev = 0;
2831 delete _this2.capacityPriorityCounters[counter];
2832 _context2.next = 4;
2833 return _this2.runScript("blacklist_client", [priorityClient]);
2834
2835 case 4:
2836 _context2.next = 6;
2837 return _this2.instance._drainAll(capacity);
2838
2839 case 6:
2840 return _context2.abrupt("return", _context2.sent);
2841
2842 case 9:
2843 _context2.prev = 9;
2844 _context2.t0 = _context2["catch"](0);
2845 e = _context2.t0;
2846 return _context2.abrupt("return", _this2.instance.Events.trigger("error", e));
2847
2848 case 13:
2849 case "end":
2850 return _context2.stop();
2851 }
2852 }
2853 }, _callee2, this, [[0, 9]]);
2854 })), 1000));
2855
2856 case 35:
2857 _context3.next = 45;
2858 break;
2859
2860 case 37:
2861 if (!(type === "message")) {
2862 _context3.next = 41;
2863 break;
2864 }
2865
2866 return _context3.abrupt("return", this.instance.Events.trigger("message", data));
2867
2868 case 41:
2869 if (!(type === "blocked")) {
2870 _context3.next = 45;
2871 break;
2872 }
2873
2874 _context3.next = 44;
2875 return this.instance._dropAllQueued();
2876
2877 case 44:
2878 return _context3.abrupt("return", _context3.sent);
2879
2880 case 45:
2881 _context3.next = 51;
2882 break;
2883
2884 case 47:
2885 _context3.prev = 47;
2886 _context3.t0 = _context3["catch"](0);
2887 e = _context3.t0;
2888 return _context3.abrupt("return", this.instance.Events.trigger("error", e));
2889
2890 case 51:
2891 case "end":
2892 return _context3.stop();
2893 }
2894 }
2895 }, _callee3, this, [[0, 47]]);
2896 }));
2897
2898 return function onMessage(_x2, _x3) {
2899 return _onMessage.apply(this, arguments);
2900 };
2901 }()
2902 }, {
2903 key: "__disconnect__",
2904 value: function __disconnect__(flush) {
2905 clearInterval(this.heartbeat);
2906
2907 if (this.sharedConnection) {
2908 return this.connection.__removeLimiter__(this.instance);
2909 } else {
2910 return this.connection.disconnect(flush);
2911 }
2912 }
2913 }, {
2914 key: "runScript",
2915 value: function () {
2916 var _runScript = _asyncToGenerator(
2917 /*#__PURE__*/
2918 regeneratorRuntime.mark(function _callee4(name, args) {
2919 var _this3 = this;
2920
2921 return regeneratorRuntime.wrap(function _callee4$(_context4) {
2922 while (1) {
2923 switch (_context4.prev = _context4.next) {
2924 case 0:
2925 if (name === "init" || name === "heartbeat" || name === "register_client") {
2926 _context4.next = 3;
2927 break;
2928 }
2929
2930 _context4.next = 3;
2931 return this.ready;
2932
2933 case 3:
2934 return _context4.abrupt("return", new this.Promise(function (resolve, reject) {
2935 var args_ts, arr;
2936 args_ts = [Date.now(), _this3.clientId].concat(args);
2937
2938 _this3.instance.Events.trigger("debug", "Calling Redis script: ".concat(name, ".lua"), args_ts);
2939
2940 arr = _this3.connection.__scriptArgs__(name, _this3.originalId, args_ts, function (err, replies) {
2941 if (err != null) {
2942 return reject(err);
2943 }
2944
2945 return resolve(replies);
2946 });
2947 return _this3.connection.__scriptFn__(name).apply(void 0, _toConsumableArray(arr));
2948 }).catch(function (e) {
2949 if (e.message === "SETTINGS_KEY_NOT_FOUND" && name !== "heartbeat") {
2950 return _this3.runScript("init", _this3.prepareInitSettings(false)).then(function () {
2951 return _this3.runScript(name, args);
2952 });
2953 } else if (name === "heartbeat") {
2954 return _this3.Promise.resolve();
2955 } else {
2956 return _this3.Promise.reject(e);
2957 }
2958 }));
2959
2960 case 4:
2961 case "end":
2962 return _context4.stop();
2963 }
2964 }
2965 }, _callee4, this);
2966 }));
2967
2968 return function runScript(_x4, _x5) {
2969 return _runScript.apply(this, arguments);
2970 };
2971 }()
2972 }, {
2973 key: "prepareArray",
2974 value: function prepareArray(arr) {
2975 var i, len, results, x;
2976 results = [];
2977
2978 for (i = 0, len = arr.length; i < len; i++) {
2979 x = arr[i];
2980 results.push(x != null ? x.toString() : "");
2981 }
2982
2983 return results;
2984 }
2985 }, {
2986 key: "prepareObject",
2987 value: function prepareObject(obj) {
2988 var arr, k, v;
2989 arr = [];
2990
2991 for (k in obj) {
2992 v = obj[k];
2993 arr.push(k, v != null ? v.toString() : "");
2994 }
2995
2996 return arr;
2997 }
2998 }, {
2999 key: "prepareInitSettings",
3000 value: function prepareInitSettings(clear) {
3001 var args;
3002 args = this.prepareObject(Object.assign({}, this.storeOptions, {
3003 id: this.originalId,
3004 version: this.instance.version,
3005 groupTimeout: this.timeout
3006 }));
3007 args.unshift(clear ? 1 : 0, this.instance.version);
3008 return args;
3009 }
3010 }, {
3011 key: "convertBool",
3012 value: function convertBool(b) {
3013 return !!b;
3014 }
3015 }, {
3016 key: "__updateSettings__",
3017 value: function () {
3018 var _updateSettings__ = _asyncToGenerator(
3019 /*#__PURE__*/
3020 regeneratorRuntime.mark(function _callee5(options) {
3021 return regeneratorRuntime.wrap(function _callee5$(_context5) {
3022 while (1) {
3023 switch (_context5.prev = _context5.next) {
3024 case 0:
3025 _context5.next = 2;
3026 return this.runScript("update_settings", this.prepareObject(options));
3027
3028 case 2:
3029 return _context5.abrupt("return", parser$4.overwrite(options, options, this.storeOptions));
3030
3031 case 3:
3032 case "end":
3033 return _context5.stop();
3034 }
3035 }
3036 }, _callee5, this);
3037 }));
3038
3039 return function __updateSettings__(_x6) {
3040 return _updateSettings__.apply(this, arguments);
3041 };
3042 }()
3043 }, {
3044 key: "__running__",
3045 value: function __running__() {
3046 return this.runScript("running", []);
3047 }
3048 }, {
3049 key: "__queued__",
3050 value: function __queued__() {
3051 return this.runScript("queued", []);
3052 }
3053 }, {
3054 key: "__done__",
3055 value: function __done__() {
3056 return this.runScript("done", []);
3057 }
3058 }, {
3059 key: "__groupCheck__",
3060 value: function () {
3061 var _groupCheck__ = _asyncToGenerator(
3062 /*#__PURE__*/
3063 regeneratorRuntime.mark(function _callee6() {
3064 return regeneratorRuntime.wrap(function _callee6$(_context6) {
3065 while (1) {
3066 switch (_context6.prev = _context6.next) {
3067 case 0:
3068 _context6.t0 = this;
3069 _context6.next = 3;
3070 return this.runScript("group_check", []);
3071
3072 case 3:
3073 _context6.t1 = _context6.sent;
3074 return _context6.abrupt("return", _context6.t0.convertBool.call(_context6.t0, _context6.t1));
3075
3076 case 5:
3077 case "end":
3078 return _context6.stop();
3079 }
3080 }
3081 }, _callee6, this);
3082 }));
3083
3084 return function __groupCheck__() {
3085 return _groupCheck__.apply(this, arguments);
3086 };
3087 }()
3088 }, {
3089 key: "__incrementReservoir__",
3090 value: function __incrementReservoir__(incr) {
3091 return this.runScript("increment_reservoir", [incr]);
3092 }
3093 }, {
3094 key: "__currentReservoir__",
3095 value: function __currentReservoir__() {
3096 return this.runScript("current_reservoir", []);
3097 }
3098 }, {
3099 key: "__check__",
3100 value: function () {
3101 var _check__ = _asyncToGenerator(
3102 /*#__PURE__*/
3103 regeneratorRuntime.mark(function _callee7(weight) {
3104 return regeneratorRuntime.wrap(function _callee7$(_context7) {
3105 while (1) {
3106 switch (_context7.prev = _context7.next) {
3107 case 0:
3108 _context7.t0 = this;
3109 _context7.next = 3;
3110 return this.runScript("check", this.prepareArray([weight]));
3111
3112 case 3:
3113 _context7.t1 = _context7.sent;
3114 return _context7.abrupt("return", _context7.t0.convertBool.call(_context7.t0, _context7.t1));
3115
3116 case 5:
3117 case "end":
3118 return _context7.stop();
3119 }
3120 }
3121 }, _callee7, this);
3122 }));
3123
3124 return function __check__(_x7) {
3125 return _check__.apply(this, arguments);
3126 };
3127 }()
3128 }, {
3129 key: "__register__",
3130 value: function () {
3131 var _register__ = _asyncToGenerator(
3132 /*#__PURE__*/
3133 regeneratorRuntime.mark(function _callee8(index, weight, expiration) {
3134 var reservoir, success, wait, _ref4, _ref5;
3135
3136 return regeneratorRuntime.wrap(function _callee8$(_context8) {
3137 while (1) {
3138 switch (_context8.prev = _context8.next) {
3139 case 0:
3140 _context8.next = 2;
3141 return this.runScript("register", this.prepareArray([index, weight, expiration]));
3142
3143 case 2:
3144 _ref4 = _context8.sent;
3145 _ref5 = _slicedToArray(_ref4, 3);
3146 success = _ref5[0];
3147 wait = _ref5[1];
3148 reservoir = _ref5[2];
3149 return _context8.abrupt("return", {
3150 success: this.convertBool(success),
3151 wait: wait,
3152 reservoir: reservoir
3153 });
3154
3155 case 8:
3156 case "end":
3157 return _context8.stop();
3158 }
3159 }
3160 }, _callee8, this);
3161 }));
3162
3163 return function __register__(_x8, _x9, _x10) {
3164 return _register__.apply(this, arguments);
3165 };
3166 }()
3167 }, {
3168 key: "__submit__",
3169 value: function () {
3170 var _submit__ = _asyncToGenerator(
3171 /*#__PURE__*/
3172 regeneratorRuntime.mark(function _callee9(queueLength, weight) {
3173 var blocked, e, maxConcurrent, overweight, reachedHWM, strategy, _ref6, _ref7, _e$message$split, _e$message$split2;
3174
3175 return regeneratorRuntime.wrap(function _callee9$(_context9) {
3176 while (1) {
3177 switch (_context9.prev = _context9.next) {
3178 case 0:
3179 _context9.prev = 0;
3180 _context9.next = 3;
3181 return this.runScript("submit", this.prepareArray([queueLength, weight]));
3182
3183 case 3:
3184 _ref6 = _context9.sent;
3185 _ref7 = _slicedToArray(_ref6, 3);
3186 reachedHWM = _ref7[0];
3187 blocked = _ref7[1];
3188 strategy = _ref7[2];
3189 return _context9.abrupt("return", {
3190 reachedHWM: this.convertBool(reachedHWM),
3191 blocked: this.convertBool(blocked),
3192 strategy: strategy
3193 });
3194
3195 case 11:
3196 _context9.prev = 11;
3197 _context9.t0 = _context9["catch"](0);
3198 e = _context9.t0;
3199
3200 if (!(e.message.indexOf("OVERWEIGHT") === 0)) {
3201 _context9.next = 23;
3202 break;
3203 }
3204
3205 _e$message$split = e.message.split(":");
3206 _e$message$split2 = _slicedToArray(_e$message$split, 3);
3207 overweight = _e$message$split2[0];
3208 weight = _e$message$split2[1];
3209 maxConcurrent = _e$message$split2[2];
3210 throw new BottleneckError$2("Impossible to add a job having a weight of ".concat(weight, " to a limiter having a maxConcurrent setting of ").concat(maxConcurrent));
3211
3212 case 23:
3213 throw e;
3214
3215 case 24:
3216 case "end":
3217 return _context9.stop();
3218 }
3219 }
3220 }, _callee9, this, [[0, 11]]);
3221 }));
3222
3223 return function __submit__(_x11, _x12) {
3224 return _submit__.apply(this, arguments);
3225 };
3226 }()
3227 }, {
3228 key: "__free__",
3229 value: function () {
3230 var _free__ = _asyncToGenerator(
3231 /*#__PURE__*/
3232 regeneratorRuntime.mark(function _callee10(index, weight) {
3233 var running;
3234 return regeneratorRuntime.wrap(function _callee10$(_context10) {
3235 while (1) {
3236 switch (_context10.prev = _context10.next) {
3237 case 0:
3238 _context10.next = 2;
3239 return this.runScript("free", this.prepareArray([index]));
3240
3241 case 2:
3242 running = _context10.sent;
3243 return _context10.abrupt("return", {
3244 running: running
3245 });
3246
3247 case 4:
3248 case "end":
3249 return _context10.stop();
3250 }
3251 }
3252 }, _callee10, this);
3253 }));
3254
3255 return function __free__(_x13, _x14) {
3256 return _free__.apply(this, arguments);
3257 };
3258 }()
3259 }]);
3260
3261 return RedisDatastore;
3262 }();
3263
3264 var RedisDatastore_1 = RedisDatastore;
3265
3266 var BottleneckError$3, States;
3267 BottleneckError$3 = BottleneckError_1;
3268
3269 States =
3270 /*#__PURE__*/
3271 function () {
3272 function States(status1) {
3273 _classCallCheck(this, States);
3274
3275 this.status = status1;
3276 this.jobs = {};
3277 this.counts = this.status.map(function () {
3278 return 0;
3279 });
3280 }
3281
3282 _createClass(States, [{
3283 key: "next",
3284 value: function next(id) {
3285 var current, next;
3286 current = this.jobs[id];
3287 next = current + 1;
3288
3289 if (current != null && next < this.status.length) {
3290 this.counts[current]--;
3291 this.counts[next]++;
3292 return this.jobs[id]++;
3293 } else if (current != null) {
3294 this.counts[current]--;
3295 return delete this.jobs[id];
3296 }
3297 }
3298 }, {
3299 key: "start",
3300 value: function start(id) {
3301 var initial;
3302 initial = 0;
3303 this.jobs[id] = initial;
3304 return this.counts[initial]++;
3305 }
3306 }, {
3307 key: "remove",
3308 value: function remove(id) {
3309 var current;
3310 current = this.jobs[id];
3311
3312 if (current != null) {
3313 this.counts[current]--;
3314 delete this.jobs[id];
3315 }
3316
3317 return current != null;
3318 }
3319 }, {
3320 key: "jobStatus",
3321 value: function jobStatus(id) {
3322 var ref;
3323 return (ref = this.status[this.jobs[id]]) != null ? ref : null;
3324 }
3325 }, {
3326 key: "statusJobs",
3327 value: function statusJobs(status) {
3328 var k, pos, ref, results, v;
3329
3330 if (status != null) {
3331 pos = this.status.indexOf(status);
3332
3333 if (pos < 0) {
3334 throw new BottleneckError$3("status must be one of ".concat(this.status.join(', ')));
3335 }
3336
3337 ref = this.jobs;
3338 results = [];
3339
3340 for (k in ref) {
3341 v = ref[k];
3342
3343 if (v === pos) {
3344 results.push(k);
3345 }
3346 }
3347
3348 return results;
3349 } else {
3350 return Object.keys(this.jobs);
3351 }
3352 }
3353 }, {
3354 key: "statusCounts",
3355 value: function statusCounts() {
3356 var _this = this;
3357
3358 return this.counts.reduce(function (acc, v, i) {
3359 acc[_this.status[i]] = v;
3360 return acc;
3361 }, {});
3362 }
3363 }]);
3364
3365 return States;
3366 }();
3367
3368 var States_1 = States;
3369
3370 var DLList$2,
3371 Sync,
3372 splice = [].splice;
3373 DLList$2 = DLList_1;
3374
3375 Sync =
3376 /*#__PURE__*/
3377 function () {
3378 function Sync(name, Promise) {
3379 _classCallCheck(this, Sync);
3380
3381 this.submit = this.submit.bind(this);
3382 this.name = name;
3383 this.Promise = Promise;
3384 this._running = 0;
3385 this._queue = new DLList$2();
3386 }
3387
3388 _createClass(Sync, [{
3389 key: "isEmpty",
3390 value: function isEmpty() {
3391 return this._queue.length === 0;
3392 }
3393 }, {
3394 key: "_tryToRun",
3395 value: function _tryToRun() {
3396 var _this = this;
3397
3398 var next;
3399
3400 if (this._running < 1 && this._queue.length > 0) {
3401 var _next;
3402
3403 this._running++;
3404 next = this._queue.shift();
3405 return (_next = next).task.apply(_next, _toConsumableArray(next.args).concat([function () {
3406 var _next2;
3407
3408 _this._running--;
3409
3410 _this._tryToRun();
3411
3412 return typeof next.cb === "function" ? (_next2 = next).cb.apply(_next2, arguments) : void 0;
3413 }]));
3414 }
3415 }
3416 }, {
3417 key: "submit",
3418 value: function submit(task) {
3419 var _ref, _ref2, _splice$call, _splice$call2;
3420
3421 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
3422 args[_key - 1] = arguments[_key];
3423 }
3424
3425 var cb, ref;
3426 ref = args, (_ref = ref, _ref2 = _toArray(_ref), args = _ref2.slice(0), _ref), (_splice$call = splice.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call);
3427
3428 this._queue.push({
3429 task: task,
3430 args: args,
3431 cb: cb
3432 });
3433
3434 return this._tryToRun();
3435 }
3436 }, {
3437 key: "schedule",
3438 value: function schedule(task) {
3439 var _this2 = this;
3440
3441 for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
3442 args[_key2 - 1] = arguments[_key2];
3443 }
3444
3445 var wrapped;
3446
3447 wrapped = function wrapped() {
3448 var _ref3, _ref4, _splice$call3, _splice$call4;
3449
3450 for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
3451 args[_key3] = arguments[_key3];
3452 }
3453
3454 var cb, ref;
3455 ref = args, (_ref3 = ref, _ref4 = _toArray(_ref3), args = _ref4.slice(0), _ref3), (_splice$call3 = splice.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3);
3456 return task.apply(void 0, _toConsumableArray(args)).then(function () {
3457 for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
3458 args[_key4] = arguments[_key4];
3459 }
3460
3461 return cb.apply(void 0, [null].concat(args));
3462 }).catch(function () {
3463 return cb.apply(void 0, arguments);
3464 });
3465 };
3466
3467 return new this.Promise(function (resolve, reject) {
3468 return _this2.submit.apply(_this2, [wrapped].concat(args, [function () {
3469 for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
3470 args[_key5] = arguments[_key5];
3471 }
3472
3473 return (args[0] != null ? reject : (args.shift(), resolve)).apply(void 0, args);
3474 }]));
3475 });
3476 }
3477 }]);
3478
3479 return Sync;
3480 }();
3481
3482 var Sync_1 = Sync;
3483
3484 var version = "2.16.0";
3485 var version$1 = {
3486 version: version
3487 };
3488
3489 var version$2 = /*#__PURE__*/Object.freeze({
3490 version: version,
3491 default: version$1
3492 });
3493
3494 var Events$4, Group, IORedisConnection$2, RedisConnection$2, Scripts$3, parser$5;
3495 parser$5 = parser;
3496 Events$4 = Events_1;
3497 RedisConnection$2 = RedisConnection_1;
3498 IORedisConnection$2 = IORedisConnection_1;
3499 Scripts$3 = Scripts;
3500
3501 Group = function () {
3502 var Group =
3503 /*#__PURE__*/
3504 function () {
3505 function Group() {
3506 var limiterOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3507
3508 _classCallCheck(this, Group);
3509
3510 this.deleteKey = this.deleteKey.bind(this);
3511 this.updateSettings = this.updateSettings.bind(this);
3512 this.limiterOptions = limiterOptions;
3513 parser$5.load(this.limiterOptions, this.defaults, this);
3514 this.Events = new Events$4(this);
3515 this.instances = {};
3516 this.Bottleneck = Bottleneck_1;
3517
3518 this._startAutoCleanup();
3519
3520 this.sharedConnection = this.connection != null;
3521
3522 if (this.connection == null) {
3523 if (this.limiterOptions.datastore === "redis") {
3524 this.connection = new RedisConnection$2(Object.assign({}, this.limiterOptions, {
3525 Events: this.Events
3526 }));
3527 } else if (this.limiterOptions.datastore === "ioredis") {
3528 this.connection = new IORedisConnection$2(Object.assign({}, this.limiterOptions, {
3529 Events: this.Events
3530 }));
3531 }
3532 }
3533 }
3534
3535 _createClass(Group, [{
3536 key: "key",
3537 value: function key() {
3538 var _this = this;
3539
3540 var _key = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
3541
3542 var ref;
3543 return (ref = this.instances[_key]) != null ? ref : function () {
3544 var limiter;
3545 limiter = _this.instances[_key] = new _this.Bottleneck(Object.assign(_this.limiterOptions, {
3546 id: "".concat(_this.id, "-").concat(_key),
3547 timeout: _this.timeout,
3548 connection: _this.connection
3549 }));
3550
3551 _this.Events.trigger("created", limiter, _key);
3552
3553 return limiter;
3554 }();
3555 }
3556 }, {
3557 key: "deleteKey",
3558 value: function () {
3559 var _deleteKey = _asyncToGenerator(
3560 /*#__PURE__*/
3561 regeneratorRuntime.mark(function _callee() {
3562 var key,
3563 deleted,
3564 instance,
3565 _args = arguments;
3566 return regeneratorRuntime.wrap(function _callee$(_context) {
3567 while (1) {
3568 switch (_context.prev = _context.next) {
3569 case 0:
3570 key = _args.length > 0 && _args[0] !== undefined ? _args[0] : "";
3571 instance = this.instances[key];
3572
3573 if (!this.connection) {
3574 _context.next = 6;
3575 break;
3576 }
3577
3578 _context.next = 5;
3579 return this.connection.__runCommand__(['del'].concat(_toConsumableArray(Scripts$3.allKeys("".concat(this.id, "-").concat(key)))));
3580
3581 case 5:
3582 deleted = _context.sent;
3583
3584 case 6:
3585 if (!(instance != null)) {
3586 _context.next = 10;
3587 break;
3588 }
3589
3590 delete this.instances[key];
3591 _context.next = 10;
3592 return instance.disconnect();
3593
3594 case 10:
3595 return _context.abrupt("return", instance != null || deleted > 0);
3596
3597 case 11:
3598 case "end":
3599 return _context.stop();
3600 }
3601 }
3602 }, _callee, this);
3603 }));
3604
3605 return function deleteKey() {
3606 return _deleteKey.apply(this, arguments);
3607 };
3608 }()
3609 }, {
3610 key: "limiters",
3611 value: function limiters() {
3612 var k, ref, results, v;
3613 ref = this.instances;
3614 results = [];
3615
3616 for (k in ref) {
3617 v = ref[k];
3618 results.push({
3619 key: k,
3620 limiter: v
3621 });
3622 }
3623
3624 return results;
3625 }
3626 }, {
3627 key: "keys",
3628 value: function keys() {
3629 return Object.keys(this.instances);
3630 }
3631 }, {
3632 key: "clusterKeys",
3633 value: function () {
3634 var _clusterKeys = _asyncToGenerator(
3635 /*#__PURE__*/
3636 regeneratorRuntime.mark(function _callee2() {
3637 var cursor, end, found, i, k, keys, len, next, start, _ref, _ref2;
3638
3639 return regeneratorRuntime.wrap(function _callee2$(_context2) {
3640 while (1) {
3641 switch (_context2.prev = _context2.next) {
3642 case 0:
3643 if (!(this.connection == null)) {
3644 _context2.next = 2;
3645 break;
3646 }
3647
3648 return _context2.abrupt("return", this.Promise.resolve(this.keys()));
3649
3650 case 2:
3651 keys = [];
3652 cursor = null;
3653 start = "b_".concat(this.id, "-").length;
3654 end = "_settings".length;
3655
3656 case 6:
3657 if (!(cursor !== 0)) {
3658 _context2.next = 17;
3659 break;
3660 }
3661
3662 _context2.next = 9;
3663 return this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", "b_".concat(this.id, "-*_settings"), "count", 10000]);
3664
3665 case 9:
3666 _ref = _context2.sent;
3667 _ref2 = _slicedToArray(_ref, 2);
3668 next = _ref2[0];
3669 found = _ref2[1];
3670 cursor = ~~next;
3671
3672 for (i = 0, len = found.length; i < len; i++) {
3673 k = found[i];
3674 keys.push(k.slice(start, -end));
3675 }
3676
3677 _context2.next = 6;
3678 break;
3679
3680 case 17:
3681 return _context2.abrupt("return", keys);
3682
3683 case 18:
3684 case "end":
3685 return _context2.stop();
3686 }
3687 }
3688 }, _callee2, this);
3689 }));
3690
3691 return function clusterKeys() {
3692 return _clusterKeys.apply(this, arguments);
3693 };
3694 }()
3695 }, {
3696 key: "_startAutoCleanup",
3697 value: function _startAutoCleanup() {
3698 var _this2 = this;
3699
3700 var base;
3701 clearInterval(this.interval);
3702 return typeof (base = this.interval = setInterval(
3703 /*#__PURE__*/
3704 _asyncToGenerator(
3705 /*#__PURE__*/
3706 regeneratorRuntime.mark(function _callee3() {
3707 var e, k, ref, results, time, v;
3708 return regeneratorRuntime.wrap(function _callee3$(_context3) {
3709 while (1) {
3710 switch (_context3.prev = _context3.next) {
3711 case 0:
3712 time = Date.now();
3713 ref = _this2.instances;
3714 results = [];
3715 _context3.t0 = regeneratorRuntime.keys(ref);
3716
3717 case 4:
3718 if ((_context3.t1 = _context3.t0()).done) {
3719 _context3.next = 23;
3720 break;
3721 }
3722
3723 k = _context3.t1.value;
3724 v = ref[k];
3725 _context3.prev = 7;
3726 _context3.next = 10;
3727 return v._store.__groupCheck__(time);
3728
3729 case 10:
3730 if (!_context3.sent) {
3731 _context3.next = 14;
3732 break;
3733 }
3734
3735 results.push(_this2.deleteKey(k));
3736 _context3.next = 15;
3737 break;
3738
3739 case 14:
3740 results.push(void 0);
3741
3742 case 15:
3743 _context3.next = 21;
3744 break;
3745
3746 case 17:
3747 _context3.prev = 17;
3748 _context3.t2 = _context3["catch"](7);
3749 e = _context3.t2;
3750 results.push(v.Events.trigger("error", e));
3751
3752 case 21:
3753 _context3.next = 4;
3754 break;
3755
3756 case 23:
3757 return _context3.abrupt("return", results);
3758
3759 case 24:
3760 case "end":
3761 return _context3.stop();
3762 }
3763 }
3764 }, _callee3, this, [[7, 17]]);
3765 })), this.timeout / 2)).unref === "function" ? base.unref() : void 0;
3766 }
3767 }, {
3768 key: "updateSettings",
3769 value: function updateSettings() {
3770 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3771 parser$5.overwrite(options, this.defaults, this);
3772 parser$5.overwrite(options, options, this.limiterOptions);
3773
3774 if (options.timeout != null) {
3775 return this._startAutoCleanup();
3776 }
3777 }
3778 }, {
3779 key: "disconnect",
3780 value: function disconnect() {
3781 var flush = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
3782 var ref;
3783
3784 if (!this.sharedConnection) {
3785 return (ref = this.connection) != null ? ref.disconnect(flush) : void 0;
3786 }
3787 }
3788 }]);
3789
3790 return Group;
3791 }();
3792 Group.prototype.defaults = {
3793 timeout: 1000 * 60 * 5,
3794 connection: null,
3795 Promise: Promise,
3796 id: "group-key"
3797 };
3798 return Group;
3799 }.call(commonjsGlobal);
3800
3801 var Group_1 = Group;
3802
3803 var Batcher, Events$5, parser$6;
3804 parser$6 = parser;
3805 Events$5 = Events_1;
3806
3807 Batcher = function () {
3808 var Batcher =
3809 /*#__PURE__*/
3810 function () {
3811 function Batcher() {
3812 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3813
3814 _classCallCheck(this, Batcher);
3815
3816 this.options = options;
3817 parser$6.load(this.options, this.defaults, this);
3818 this.Events = new Events$5(this);
3819 this._arr = [];
3820
3821 this._resetPromise();
3822
3823 this._lastFlush = Date.now();
3824 }
3825
3826 _createClass(Batcher, [{
3827 key: "_resetPromise",
3828 value: function _resetPromise() {
3829 var _this = this;
3830
3831 return this._promise = new this.Promise(function (res, rej) {
3832 return _this._resolve = res;
3833 });
3834 }
3835 }, {
3836 key: "_flush",
3837 value: function _flush() {
3838 clearTimeout(this._timeout);
3839 this._lastFlush = Date.now();
3840
3841 this._resolve();
3842
3843 this.Events.trigger("batch", this._arr);
3844 this._arr = [];
3845 return this._resetPromise();
3846 }
3847 }, {
3848 key: "add",
3849 value: function add(data) {
3850 var _this2 = this;
3851
3852 var ret;
3853
3854 this._arr.push(data);
3855
3856 ret = this._promise;
3857
3858 if (this._arr.length === this.maxSize) {
3859 this._flush();
3860 } else if (this.maxTime != null && this._arr.length === 1) {
3861 this._timeout = setTimeout(function () {
3862 return _this2._flush();
3863 }, this.maxTime);
3864 }
3865
3866 return ret;
3867 }
3868 }]);
3869
3870 return Batcher;
3871 }();
3872 Batcher.prototype.defaults = {
3873 maxTime: null,
3874 maxSize: null,
3875 Promise: Promise
3876 };
3877 return Batcher;
3878 }.call(commonjsGlobal);
3879
3880 var Batcher_1 = Batcher;
3881
3882 var require$$7 = getCjsExportFromNamespace(version$2);
3883
3884 var Bottleneck,
3885 DEFAULT_PRIORITY,
3886 Events$6,
3887 LocalDatastore$1,
3888 NUM_PRIORITIES,
3889 Queues$1,
3890 RedisDatastore$1,
3891 States$1,
3892 Sync$1,
3893 parser$7,
3894 splice$1 = [].splice;
3895 NUM_PRIORITIES = 10;
3896 DEFAULT_PRIORITY = 5;
3897 parser$7 = parser;
3898 Queues$1 = Queues_1;
3899 LocalDatastore$1 = LocalDatastore_1;
3900 RedisDatastore$1 = RedisDatastore_1;
3901 Events$6 = Events_1;
3902 States$1 = States_1;
3903 Sync$1 = Sync_1;
3904
3905 Bottleneck = function () {
3906 var Bottleneck =
3907 /*#__PURE__*/
3908 function () {
3909 function Bottleneck() {
3910 var _this = this;
3911
3912 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3913
3914 _classCallCheck(this, Bottleneck);
3915
3916 var storeInstanceOptions, storeOptions;
3917 this._drainOne = this._drainOne.bind(this);
3918 this.submit = this.submit.bind(this);
3919 this.schedule = this.schedule.bind(this);
3920 this.updateSettings = this.updateSettings.bind(this);
3921 this.incrementReservoir = this.incrementReservoir.bind(this);
3922
3923 for (var _len = arguments.length, invalid = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
3924 invalid[_key - 1] = arguments[_key];
3925 }
3926
3927 this._validateOptions(options, invalid);
3928
3929 parser$7.load(options, this.instanceDefaults, this);
3930 this._queues = new Queues$1(NUM_PRIORITIES);
3931 this._scheduled = {};
3932 this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : []));
3933 this._limiter = null;
3934 this.Events = new Events$6(this);
3935 this._submitLock = new Sync$1("submit", this.Promise);
3936 this._registerLock = new Sync$1("register", this.Promise);
3937 storeOptions = parser$7.load(options, this.storeDefaults, {});
3938
3939 this._store = function () {
3940 if (this.datastore === "redis" || this.datastore === "ioredis" || this.connection != null) {
3941 storeInstanceOptions = parser$7.load(options, this.redisStoreDefaults, {});
3942 return new RedisDatastore$1(this, storeOptions, storeInstanceOptions);
3943 } else if (this.datastore === "local") {
3944 storeInstanceOptions = parser$7.load(options, this.localStoreDefaults, {});
3945 return new LocalDatastore$1(this, storeOptions, storeInstanceOptions);
3946 } else {
3947 throw new Bottleneck.prototype.BottleneckError("Invalid datastore type: ".concat(this.datastore));
3948 }
3949 }.call(this);
3950
3951 this._queues.on("leftzero", function () {
3952 var base;
3953 return typeof (base = _this._store.heartbeat).ref === "function" ? base.ref() : void 0;
3954 });
3955
3956 this._queues.on("zero", function () {
3957 var base;
3958 return typeof (base = _this._store.heartbeat).unref === "function" ? base.unref() : void 0;
3959 });
3960 }
3961
3962 _createClass(Bottleneck, [{
3963 key: "_validateOptions",
3964 value: function _validateOptions(options, invalid) {
3965 if (!(options != null && _typeof(options) === "object" && invalid.length === 0)) {
3966 throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.");
3967 }
3968 }
3969 }, {
3970 key: "ready",
3971 value: function ready() {
3972 return this._store.ready;
3973 }
3974 }, {
3975 key: "clients",
3976 value: function clients() {
3977 return this._store.clients;
3978 }
3979 }, {
3980 key: "channel",
3981 value: function channel() {
3982 return "b_".concat(this.id);
3983 }
3984 }, {
3985 key: "channel_client",
3986 value: function channel_client() {
3987 return "b_".concat(this.id, "_").concat(this._store.clientId);
3988 }
3989 }, {
3990 key: "publish",
3991 value: function publish(message) {
3992 return this._store.__publish__(message);
3993 }
3994 }, {
3995 key: "disconnect",
3996 value: function disconnect() {
3997 var flush = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
3998 return this._store.__disconnect__(flush);
3999 }
4000 }, {
4001 key: "chain",
4002 value: function chain(_limiter) {
4003 this._limiter = _limiter;
4004 return this;
4005 }
4006 }, {
4007 key: "queued",
4008 value: function queued(priority) {
4009 return this._queues.queued(priority);
4010 }
4011 }, {
4012 key: "clusterQueued",
4013 value: function clusterQueued() {
4014 return this._store.__queued__();
4015 }
4016 }, {
4017 key: "empty",
4018 value: function empty() {
4019 return this.queued() === 0 && this._submitLock.isEmpty();
4020 }
4021 }, {
4022 key: "running",
4023 value: function running() {
4024 return this._store.__running__();
4025 }
4026 }, {
4027 key: "done",
4028 value: function done() {
4029 return this._store.__done__();
4030 }
4031 }, {
4032 key: "jobStatus",
4033 value: function jobStatus(id) {
4034 return this._states.jobStatus(id);
4035 }
4036 }, {
4037 key: "jobs",
4038 value: function jobs(status) {
4039 return this._states.statusJobs(status);
4040 }
4041 }, {
4042 key: "counts",
4043 value: function counts() {
4044 return this._states.statusCounts();
4045 }
4046 }, {
4047 key: "_sanitizePriority",
4048 value: function _sanitizePriority(priority) {
4049 var sProperty;
4050 sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority;
4051
4052 if (sProperty < 0) {
4053 return 0;
4054 } else if (sProperty > NUM_PRIORITIES - 1) {
4055 return NUM_PRIORITIES - 1;
4056 } else {
4057 return sProperty;
4058 }
4059 }
4060 }, {
4061 key: "_randomIndex",
4062 value: function _randomIndex() {
4063 return Math.random().toString(36).slice(2);
4064 }
4065 }, {
4066 key: "check",
4067 value: function check() {
4068 var weight = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
4069 return this._store.__check__(weight);
4070 }
4071 }, {
4072 key: "_run",
4073 value: function _run(next, wait, index, retryCount) {
4074 var _this2 = this;
4075
4076 var completed, done;
4077 this.Events.trigger("debug", "Scheduling ".concat(next.options.id), {
4078 args: next.args,
4079 options: next.options
4080 });
4081 done = false;
4082
4083 completed =
4084 /*#__PURE__*/
4085 function () {
4086 var _ref = _asyncToGenerator(
4087 /*#__PURE__*/
4088 regeneratorRuntime.mark(function _callee() {
4089 var e,
4090 error,
4091 eventInfo,
4092 retry,
4093 retryAfter,
4094 running,
4095 _ref2,
4096 _args = arguments;
4097
4098 return regeneratorRuntime.wrap(function _callee$(_context) {
4099 while (1) {
4100 switch (_context.prev = _context.next) {
4101 case 0:
4102 if (done) {
4103 _context.next = 30;
4104 break;
4105 }
4106
4107 _context.prev = 1;
4108 done = true;
4109 clearTimeout(_this2._scheduled[index].expiration);
4110 delete _this2._scheduled[index];
4111 eventInfo = {
4112 args: next.args,
4113 options: next.options,
4114 retryCount: retryCount
4115 };
4116
4117 if (!((error = _args.length <= 0 ? undefined : _args[0]) != null)) {
4118 _context.next = 14;
4119 break;
4120 }
4121
4122 _context.next = 9;
4123 return _this2.Events.trigger("failed", error, eventInfo);
4124
4125 case 9:
4126 retry = _context.sent;
4127
4128 if (!(retry != null)) {
4129 _context.next = 14;
4130 break;
4131 }
4132
4133 retryAfter = ~~retry;
4134
4135 _this2.Events.trigger("retry", "Retrying ".concat(next.options.id, " after ").concat(retryAfter, " ms"), eventInfo);
4136
4137 return _context.abrupt("return", _this2._run(next, retryAfter, index, retryCount + 1));
4138
4139 case 14:
4140 _this2._states.next(next.options.id); // DONE
4141
4142
4143 _this2.Events.trigger("debug", "Completed ".concat(next.options.id), eventInfo);
4144
4145 _this2.Events.trigger("done", "Completed ".concat(next.options.id), eventInfo);
4146
4147 _context.next = 19;
4148 return _this2._store.__free__(index, next.options.weight);
4149
4150 case 19:
4151 _ref2 = _context.sent;
4152 running = _ref2.running;
4153
4154 _this2.Events.trigger("debug", "Freed ".concat(next.options.id), eventInfo);
4155
4156 if (running === 0 && _this2.empty()) {
4157 _this2.Events.trigger("idle");
4158 }
4159
4160 return _context.abrupt("return", typeof next.cb === "function" ? next.cb.apply(next, _args) : void 0);
4161
4162 case 26:
4163 _context.prev = 26;
4164 _context.t0 = _context["catch"](1);
4165 e = _context.t0;
4166 return _context.abrupt("return", _this2.Events.trigger("error", e));
4167
4168 case 30:
4169 case "end":
4170 return _context.stop();
4171 }
4172 }
4173 }, _callee, this, [[1, 26]]);
4174 }));
4175
4176 return function completed() {
4177 return _ref.apply(this, arguments);
4178 };
4179 }();
4180
4181 if (retryCount === 0) {
4182 // RUNNING
4183 this._states.next(next.options.id);
4184 }
4185
4186 return this._scheduled[index] = {
4187 timeout: setTimeout(function () {
4188 _this2.Events.trigger("debug", "Executing ".concat(next.options.id), {
4189 args: next.args,
4190 options: next.options
4191 });
4192
4193 if (retryCount === 0) {
4194 // EXECUTING
4195 _this2._states.next(next.options.id);
4196 }
4197
4198 if (_this2._limiter != null) {
4199 var _this2$_limiter;
4200
4201 return (_this2$_limiter = _this2._limiter).submit.apply(_this2$_limiter, [next.options, next.task].concat(_toConsumableArray(next.args), [completed]));
4202 } else {
4203 return next.task.apply(next, _toConsumableArray(next.args).concat([completed]));
4204 }
4205 }, wait),
4206 expiration: next.options.expiration != null ? setTimeout(function () {
4207 return completed(new Bottleneck.prototype.BottleneckError("This job timed out after ".concat(next.options.expiration, " ms.")));
4208 }, wait + next.options.expiration) : void 0,
4209 job: next
4210 };
4211 }
4212 }, {
4213 key: "_drainOne",
4214 value: function _drainOne(capacity) {
4215 var _this3 = this;
4216
4217 return this._registerLock.schedule(function () {
4218 var args, index, next, options, queue;
4219
4220 if (_this3.queued() === 0) {
4221 return _this3.Promise.resolve(null);
4222 }
4223
4224 queue = _this3._queues.getFirst();
4225
4226 var _next = next = queue.first();
4227
4228 options = _next.options;
4229 args = _next.args;
4230
4231 if (capacity != null && options.weight > capacity) {
4232 return _this3.Promise.resolve(null);
4233 }
4234
4235 _this3.Events.trigger("debug", "Draining ".concat(options.id), {
4236 args: args,
4237 options: options
4238 });
4239
4240 index = _this3._randomIndex();
4241 return _this3._store.__register__(index, options.weight, options.expiration).then(function (_ref3) {
4242 var success = _ref3.success,
4243 wait = _ref3.wait,
4244 reservoir = _ref3.reservoir;
4245 var empty;
4246
4247 _this3.Events.trigger("debug", "Drained ".concat(options.id), {
4248 success: success,
4249 args: args,
4250 options: options
4251 });
4252
4253 if (success) {
4254 queue.shift();
4255 empty = _this3.empty();
4256
4257 if (empty) {
4258 _this3.Events.trigger("empty");
4259 }
4260
4261 if (reservoir === 0) {
4262 _this3.Events.trigger("depleted", empty);
4263 }
4264
4265 _this3._run(next, wait, index, 0);
4266
4267 return _this3.Promise.resolve(options.weight);
4268 } else {
4269 return _this3.Promise.resolve(null);
4270 }
4271 });
4272 });
4273 }
4274 }, {
4275 key: "_drainAll",
4276 value: function _drainAll(capacity) {
4277 var _this4 = this;
4278
4279 var total = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
4280 return this._drainOne(capacity).then(function (drained) {
4281 var newCapacity;
4282
4283 if (drained != null) {
4284 newCapacity = capacity != null ? capacity - drained : capacity;
4285 return _this4._drainAll(newCapacity, total + drained);
4286 } else {
4287 return _this4.Promise.resolve(total);
4288 }
4289 }).catch(function (e) {
4290 return _this4.Events.trigger("error", e);
4291 });
4292 }
4293 }, {
4294 key: "_drop",
4295 value: function _drop(job) {
4296 var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "This job has been dropped by Bottleneck";
4297
4298 if (this._states.remove(job.options.id)) {
4299 if (this.rejectOnDrop) {
4300 if (typeof job.cb === "function") {
4301 job.cb(new Bottleneck.prototype.BottleneckError(message));
4302 }
4303 }
4304
4305 return this.Events.trigger("dropped", job);
4306 }
4307 }
4308 }, {
4309 key: "_dropAllQueued",
4310 value: function _dropAllQueued(message) {
4311 var _this5 = this;
4312
4313 return this._queues.shiftAll(function (job) {
4314 return _this5._drop(job, message);
4315 });
4316 }
4317 }, {
4318 key: "stop",
4319 value: function stop() {
4320 var _this6 = this;
4321
4322 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4323 var done, waitForExecuting;
4324 options = parser$7.load(options, this.stopDefaults);
4325
4326 waitForExecuting = function waitForExecuting(at) {
4327 var finished;
4328
4329 finished = function finished() {
4330 var counts;
4331 counts = _this6._states.counts;
4332 return counts[0] + counts[1] + counts[2] + counts[3] === at;
4333 };
4334
4335 return new _this6.Promise(function (resolve, reject) {
4336 if (finished()) {
4337 return resolve();
4338 } else {
4339 return _this6.on("done", function () {
4340 if (finished()) {
4341 _this6.removeAllListeners("done");
4342
4343 return resolve();
4344 }
4345 });
4346 }
4347 });
4348 };
4349
4350 done = options.dropWaitingJobs ? (this._run = function (next) {
4351 return _this6._drop(next, options.dropErrorMessage);
4352 }, this._drainOne = function () {
4353 return _this6.Promise.resolve(null);
4354 }, this._registerLock.schedule(function () {
4355 return _this6._submitLock.schedule(function () {
4356 var k, ref, v;
4357 ref = _this6._scheduled;
4358
4359 for (k in ref) {
4360 v = ref[k];
4361
4362 if (_this6.jobStatus(v.job.options.id) === "RUNNING") {
4363 clearTimeout(v.timeout);
4364 clearTimeout(v.expiration);
4365
4366 _this6._drop(v.job, options.dropErrorMessage);
4367 }
4368 }
4369
4370 _this6._dropAllQueued(options.dropErrorMessage);
4371
4372 return waitForExecuting(0);
4373 });
4374 })) : this.schedule({
4375 priority: NUM_PRIORITIES - 1,
4376 weight: 0
4377 }, function () {
4378 return waitForExecuting(1);
4379 });
4380
4381 this.submit = function () {
4382 var _ref4, _ref5, _splice$call, _splice$call2;
4383
4384 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
4385 args[_key2] = arguments[_key2];
4386 }
4387
4388 var cb, ref;
4389 ref = args, (_ref4 = ref, _ref5 = _toArray(_ref4), args = _ref5.slice(0), _ref4), (_splice$call = splice$1.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call);
4390 return typeof cb === "function" ? cb(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)) : void 0;
4391 };
4392
4393 this.stop = function () {
4394 return _this6.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called"));
4395 };
4396
4397 return done;
4398 }
4399 }, {
4400 key: "submit",
4401 value: function submit() {
4402 var _this7 = this;
4403
4404 for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
4405 args[_key3] = arguments[_key3];
4406 }
4407
4408 var cb, job, options, ref, ref1, task;
4409
4410 if (typeof args[0] === "function") {
4411 var _ref6, _ref7, _splice$call3, _splice$call4;
4412
4413 ref = args, (_ref6 = ref, _ref7 = _toArray(_ref6), task = _ref7[0], args = _ref7.slice(1), _ref6), (_splice$call3 = splice$1.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3);
4414 options = parser$7.load({}, this.jobDefaults, {});
4415 } else {
4416 var _ref8, _ref9, _splice$call5, _splice$call6;
4417
4418 ref1 = args, (_ref8 = ref1, _ref9 = _toArray(_ref8), options = _ref9[0], task = _ref9[1], args = _ref9.slice(2), _ref8), (_splice$call5 = splice$1.call(args, -1), _splice$call6 = _slicedToArray(_splice$call5, 1), cb = _splice$call6[0], _splice$call5);
4419 options = parser$7.load(options, this.jobDefaults);
4420 }
4421
4422 job = {
4423 options: options,
4424 task: task,
4425 args: args,
4426 cb: cb
4427 };
4428 options.priority = this._sanitizePriority(options.priority);
4429
4430 if (options.id === this.jobDefaults.id) {
4431 options.id = "".concat(options.id, "-").concat(this._randomIndex());
4432 }
4433
4434 if (this.jobStatus(options.id) != null) {
4435 if (typeof job.cb === "function") {
4436 job.cb(new Bottleneck.prototype.BottleneckError("A job with the same id already exists (id=".concat(options.id, ")")));
4437 }
4438
4439 return false;
4440 }
4441
4442 this._states.start(options.id); // RECEIVED
4443
4444
4445 this.Events.trigger("debug", "Queueing ".concat(options.id), {
4446 args: args,
4447 options: options
4448 });
4449 return this._submitLock.schedule(
4450 /*#__PURE__*/
4451 _asyncToGenerator(
4452 /*#__PURE__*/
4453 regeneratorRuntime.mark(function _callee2() {
4454 var blocked, e, reachedHWM, shifted, strategy, _ref11;
4455
4456 return regeneratorRuntime.wrap(function _callee2$(_context2) {
4457 while (1) {
4458 switch (_context2.prev = _context2.next) {
4459 case 0:
4460 _context2.prev = 0;
4461 _context2.next = 3;
4462 return _this7._store.__submit__(_this7.queued(), options.weight);
4463
4464 case 3:
4465 _ref11 = _context2.sent;
4466 reachedHWM = _ref11.reachedHWM;
4467 blocked = _ref11.blocked;
4468 strategy = _ref11.strategy;
4469
4470 _this7.Events.trigger("debug", "Queued ".concat(options.id), {
4471 args: args,
4472 options: options,
4473 reachedHWM: reachedHWM,
4474 blocked: blocked
4475 });
4476
4477 _context2.next = 17;
4478 break;
4479
4480 case 10:
4481 _context2.prev = 10;
4482 _context2.t0 = _context2["catch"](0);
4483 e = _context2.t0;
4484
4485 _this7._states.remove(options.id);
4486
4487 _this7.Events.trigger("debug", "Could not queue ".concat(options.id), {
4488 args: args,
4489 options: options,
4490 error: e
4491 });
4492
4493 if (typeof job.cb === "function") {
4494 job.cb(e);
4495 }
4496
4497 return _context2.abrupt("return", false);
4498
4499 case 17:
4500 if (!blocked) {
4501 _context2.next = 22;
4502 break;
4503 }
4504
4505 _this7._drop(job);
4506
4507 return _context2.abrupt("return", true);
4508
4509 case 22:
4510 if (!reachedHWM) {
4511 _context2.next = 28;
4512 break;
4513 }
4514
4515 shifted = strategy === Bottleneck.prototype.strategy.LEAK ? _this7._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? _this7._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0;
4516
4517 if (shifted != null) {
4518 _this7._drop(shifted);
4519 }
4520
4521 if (!(shifted == null || strategy === Bottleneck.prototype.strategy.OVERFLOW)) {
4522 _context2.next = 28;
4523 break;
4524 }
4525
4526 if (shifted == null) {
4527 _this7._drop(job);
4528 }
4529
4530 return _context2.abrupt("return", reachedHWM);
4531
4532 case 28:
4533 _this7._states.next(job.options.id); // QUEUED
4534
4535
4536 _this7._queues.push(options.priority, job);
4537
4538 _context2.next = 32;
4539 return _this7._drainAll();
4540
4541 case 32:
4542 return _context2.abrupt("return", reachedHWM);
4543
4544 case 33:
4545 case "end":
4546 return _context2.stop();
4547 }
4548 }
4549 }, _callee2, this, [[0, 10]]);
4550 })));
4551 }
4552 }, {
4553 key: "schedule",
4554 value: function schedule() {
4555 var _this8 = this;
4556
4557 for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
4558 args[_key4] = arguments[_key4];
4559 }
4560
4561 var options, task, wrapped;
4562
4563 if (typeof args[0] === "function") {
4564 var _args3 = args;
4565
4566 var _args4 = _toArray(_args3);
4567
4568 task = _args4[0];
4569 args = _args4.slice(1);
4570 options = parser$7.load({}, this.jobDefaults, {});
4571 } else {
4572 var _args5 = args;
4573
4574 var _args6 = _toArray(_args5);
4575
4576 options = _args6[0];
4577 task = _args6[1];
4578 args = _args6.slice(2);
4579 options = parser$7.load(options, this.jobDefaults);
4580 }
4581
4582 wrapped = function wrapped() {
4583 var _ref12, _ref13, _splice$call7, _splice$call8;
4584
4585 for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
4586 args[_key5] = arguments[_key5];
4587 }
4588
4589 var cb, ref, returned;
4590 ref = args, (_ref12 = ref, _ref13 = _toArray(_ref12), args = _ref13.slice(0), _ref12), (_splice$call7 = splice$1.call(args, -1), _splice$call8 = _slicedToArray(_splice$call7, 1), cb = _splice$call8[0], _splice$call7);
4591 returned = task.apply(void 0, _toConsumableArray(args));
4592 return (!((returned != null ? returned.then : void 0) != null && typeof returned.then === "function") ? _this8.Promise.resolve(returned) : returned).then(function () {
4593 for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
4594 args[_key6] = arguments[_key6];
4595 }
4596
4597 return cb.apply(void 0, [null].concat(args));
4598 }).catch(function () {
4599 return cb.apply(void 0, arguments);
4600 });
4601 };
4602
4603 return new this.Promise(function (resolve, reject) {
4604 return _this8.submit.apply(_this8, [options, wrapped].concat(_toConsumableArray(args), [function () {
4605 for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
4606 args[_key7] = arguments[_key7];
4607 }
4608
4609 return (args[0] != null ? reject : (args.shift(), resolve)).apply(void 0, args);
4610 }])).catch(function (e) {
4611 return _this8.Events.trigger("error", e);
4612 });
4613 });
4614 }
4615 }, {
4616 key: "wrap",
4617 value: function wrap(fn) {
4618 var _this9 = this;
4619
4620 var wrapped;
4621
4622 wrapped = function wrapped() {
4623 for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
4624 args[_key8] = arguments[_key8];
4625 }
4626
4627 return _this9.schedule.apply(_this9, [fn].concat(args));
4628 };
4629
4630 wrapped.withOptions = function (options) {
4631 for (var _len9 = arguments.length, args = new Array(_len9 > 1 ? _len9 - 1 : 0), _key9 = 1; _key9 < _len9; _key9++) {
4632 args[_key9 - 1] = arguments[_key9];
4633 }
4634
4635 return _this9.schedule.apply(_this9, [options, fn].concat(args));
4636 };
4637
4638 return wrapped;
4639 }
4640 }, {
4641 key: "updateSettings",
4642 value: function () {
4643 var _updateSettings = _asyncToGenerator(
4644 /*#__PURE__*/
4645 regeneratorRuntime.mark(function _callee3() {
4646 var options,
4647 _args7 = arguments;
4648 return regeneratorRuntime.wrap(function _callee3$(_context3) {
4649 while (1) {
4650 switch (_context3.prev = _context3.next) {
4651 case 0:
4652 options = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : {};
4653 _context3.next = 3;
4654 return this._store.__updateSettings__(parser$7.overwrite(options, this.storeDefaults));
4655
4656 case 3:
4657 parser$7.overwrite(options, this.instanceDefaults, this);
4658 return _context3.abrupt("return", this);
4659
4660 case 5:
4661 case "end":
4662 return _context3.stop();
4663 }
4664 }
4665 }, _callee3, this);
4666 }));
4667
4668 return function updateSettings() {
4669 return _updateSettings.apply(this, arguments);
4670 };
4671 }()
4672 }, {
4673 key: "currentReservoir",
4674 value: function currentReservoir() {
4675 return this._store.__currentReservoir__();
4676 }
4677 }, {
4678 key: "incrementReservoir",
4679 value: function incrementReservoir() {
4680 var incr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
4681 return this._store.__incrementReservoir__(incr);
4682 }
4683 }]);
4684
4685 return Bottleneck;
4686 }();
4687 Bottleneck.default = Bottleneck;
4688 Bottleneck.Events = Events$6;
4689 Bottleneck.version = Bottleneck.prototype.version = require$$7.version;
4690 Bottleneck.strategy = Bottleneck.prototype.strategy = {
4691 LEAK: 1,
4692 OVERFLOW: 2,
4693 OVERFLOW_PRIORITY: 4,
4694 BLOCK: 3
4695 };
4696 Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1;
4697 Bottleneck.Group = Bottleneck.prototype.Group = Group_1;
4698 Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = RedisConnection_1;
4699 Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = IORedisConnection_1;
4700 Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1;
4701 Bottleneck.prototype.jobDefaults = {
4702 priority: DEFAULT_PRIORITY,
4703 weight: 1,
4704 expiration: null,
4705 id: "<no-id>"
4706 };
4707 Bottleneck.prototype.storeDefaults = {
4708 maxConcurrent: null,
4709 minTime: 0,
4710 highWater: null,
4711 strategy: Bottleneck.prototype.strategy.LEAK,
4712 penalty: null,
4713 reservoir: null,
4714 reservoirRefreshInterval: null,
4715 reservoirRefreshAmount: null
4716 };
4717 Bottleneck.prototype.localStoreDefaults = {
4718 Promise: Promise,
4719 timeout: null,
4720 heartbeatInterval: 250
4721 };
4722 Bottleneck.prototype.redisStoreDefaults = {
4723 Promise: Promise,
4724 timeout: null,
4725 heartbeatInterval: 5000,
4726 clientOptions: {},
4727 clusterNodes: null,
4728 clearDatastore: false,
4729 connection: null
4730 };
4731 Bottleneck.prototype.instanceDefaults = {
4732 datastore: "local",
4733 connection: null,
4734 id: "<no-id>",
4735 rejectOnDrop: true,
4736 trackDoneStatus: false,
4737 Promise: Promise
4738 };
4739 Bottleneck.prototype.stopDefaults = {
4740 enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.",
4741 dropWaitingJobs: true,
4742 dropErrorMessage: "This limiter has been stopped."
4743 };
4744 return Bottleneck;
4745 }.call(commonjsGlobal);
4746
4747 var Bottleneck_1 = Bottleneck;
4748
4749 var es5 = Bottleneck_1;
4750
4751 return es5;
4752
4753})));