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[num_static_argv + 1]\n\nredis.call('zadd', client_last_seen_key, 0, blacklist)\n\nreturn {}\n",
1980 "check.lua": "local weight = tonumber(ARGV[num_static_argv + 1])\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[num_static_argv + 1]\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[num_static_argv + 1])\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[num_static_argv + 1])\nlocal limiter_version = ARGV[num_static_argv + 2]\nlocal num_local_argv = num_static_argv + 2\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_local_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\n if clear == 1 then\n -- Force all connected clients to re-register\n process_tick(now, true)\n end\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]) or 0)\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]\nlocal queued = ARGV[3]\n\nlocal num_static_argv = 3\n",
1994 "register.lua": "local index = ARGV[num_static_argv + 1]\nlocal weight = tonumber(ARGV[num_static_argv + 2])\nlocal expiration = tonumber(ARGV[num_static_argv + 3])\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 "running.lua": "return process_tick(now, false)['running']\n",
1996 "submit.lua": "local queueLength = tonumber(ARGV[num_static_argv + 1])\nlocal weight = tonumber(ARGV[num_static_argv + 2])\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",
1997 "update_settings.lua": "local 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",
1998 "validate_keys.lua": "if not (redis.call('exists', settings_key) == 1) then\n return redis.error_reply('SETTINGS_KEY_NOT_FOUND')\nend\n\nif not redis.call('zscore', client_running_key, client) then\n -- Register new client\n redis.call('zadd', client_running_key, 0, client)\n redis.call('hset', client_num_queued_key, client, queued)\n redis.call('zadd', client_last_registered_key, 0, client)\nend\n\nredis.call('zadd', client_last_seen_key, now, client)\n"
1999 };
2000
2001 var lua$1 = /*#__PURE__*/Object.freeze({
2002 default: lua
2003 });
2004
2005 var require$$0 = getCjsExportFromNamespace(lua$1);
2006
2007 var Scripts = createCommonjsModule(function (module, exports) {
2008 var headers, lua, templates;
2009 lua = require$$0;
2010 headers = {
2011 refs: lua["refs.lua"],
2012 validate_keys: lua["validate_keys.lua"],
2013 refresh_expiration: lua["refresh_expiration.lua"],
2014 process_tick: lua["process_tick.lua"],
2015 conditions_check: lua["conditions_check.lua"],
2016 get_time: lua["get_time.lua"]
2017 };
2018
2019 exports.allKeys = function (id) {
2020 return [
2021 /*
2022 HASH
2023 */
2024 "b_".concat(id, "_settings"),
2025 /*
2026 HASH
2027 job index -> weight
2028 */
2029 "b_".concat(id, "_job_weights"),
2030 /*
2031 ZSET
2032 job index -> expiration
2033 */
2034 "b_".concat(id, "_job_expirations"),
2035 /*
2036 HASH
2037 job index -> client
2038 */
2039 "b_".concat(id, "_job_clients"),
2040 /*
2041 ZSET
2042 client -> sum running
2043 */
2044 "b_".concat(id, "_client_running"),
2045 /*
2046 HASH
2047 client -> num queued
2048 */
2049 "b_".concat(id, "_client_num_queued"),
2050 /*
2051 ZSET
2052 client -> last job registered
2053 */
2054 "b_".concat(id, "_client_last_registered"),
2055 /*
2056 ZSET
2057 client -> last seen
2058 */
2059 "b_".concat(id, "_client_last_seen")];
2060 };
2061
2062 templates = {
2063 init: {
2064 keys: exports.allKeys,
2065 headers: ["process_tick"],
2066 refresh_expiration: true,
2067 code: lua["init.lua"]
2068 },
2069 group_check: {
2070 keys: exports.allKeys,
2071 headers: [],
2072 refresh_expiration: false,
2073 code: lua["group_check.lua"]
2074 },
2075 blacklist_client: {
2076 keys: exports.allKeys,
2077 headers: ["validate_keys"],
2078 refresh_expiration: false,
2079 code: lua["blacklist_client.lua"]
2080 },
2081 heartbeat: {
2082 keys: exports.allKeys,
2083 headers: ["validate_keys", "process_tick"],
2084 refresh_expiration: false,
2085 code: lua["heartbeat.lua"]
2086 },
2087 update_settings: {
2088 keys: exports.allKeys,
2089 headers: ["validate_keys", "process_tick"],
2090 refresh_expiration: true,
2091 code: lua["update_settings.lua"]
2092 },
2093 running: {
2094 keys: exports.allKeys,
2095 headers: ["validate_keys", "process_tick"],
2096 refresh_expiration: false,
2097 code: lua["running.lua"]
2098 },
2099 queued: {
2100 keys: exports.allKeys,
2101 headers: ["validate_keys"],
2102 refresh_expiration: false,
2103 code: lua["queued.lua"]
2104 },
2105 done: {
2106 keys: exports.allKeys,
2107 headers: ["validate_keys", "process_tick"],
2108 refresh_expiration: false,
2109 code: lua["done.lua"]
2110 },
2111 check: {
2112 keys: exports.allKeys,
2113 headers: ["validate_keys", "process_tick", "conditions_check"],
2114 refresh_expiration: false,
2115 code: lua["check.lua"]
2116 },
2117 submit: {
2118 keys: exports.allKeys,
2119 headers: ["validate_keys", "process_tick", "conditions_check"],
2120 refresh_expiration: true,
2121 code: lua["submit.lua"]
2122 },
2123 register: {
2124 keys: exports.allKeys,
2125 headers: ["validate_keys", "process_tick", "conditions_check"],
2126 refresh_expiration: true,
2127 code: lua["register.lua"]
2128 },
2129 free: {
2130 keys: exports.allKeys,
2131 headers: ["validate_keys", "process_tick"],
2132 refresh_expiration: true,
2133 code: lua["free.lua"]
2134 },
2135 current_reservoir: {
2136 keys: exports.allKeys,
2137 headers: ["validate_keys", "process_tick"],
2138 refresh_expiration: false,
2139 code: lua["current_reservoir.lua"]
2140 },
2141 increment_reservoir: {
2142 keys: exports.allKeys,
2143 headers: ["validate_keys", "process_tick"],
2144 refresh_expiration: true,
2145 code: lua["increment_reservoir.lua"]
2146 }
2147 };
2148 exports.names = Object.keys(templates);
2149
2150 exports.keys = function (name, id) {
2151 return templates[name].keys(id);
2152 };
2153
2154 exports.payload = function (name) {
2155 var template;
2156 template = templates[name];
2157 return Array.prototype.concat(headers.refs, template.headers.map(function (h) {
2158 return headers[h];
2159 }), template.refresh_expiration ? headers.refresh_expiration : "", template.code).join("\n");
2160 };
2161 });
2162 var Scripts_1 = Scripts.allKeys;
2163 var Scripts_2 = Scripts.names;
2164 var Scripts_3 = Scripts.keys;
2165 var Scripts_4 = Scripts.payload;
2166
2167 var Events$2, RedisConnection, Scripts$1, parser$2;
2168 parser$2 = parser;
2169 Events$2 = Events_1;
2170 Scripts$1 = Scripts;
2171
2172 RedisConnection = function () {
2173 var RedisConnection =
2174 /*#__PURE__*/
2175 function () {
2176 function RedisConnection() {
2177 var _this = this;
2178
2179 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2180
2181 _classCallCheck(this, RedisConnection);
2182
2183 var Redis;
2184 Redis = eval("require")("redis"); // Obfuscated or else Webpack/Angular will try to inline the optional redis module
2185
2186 parser$2.load(options, this.defaults, this);
2187
2188 if (this.Events == null) {
2189 this.Events = new Events$2(this);
2190 }
2191
2192 this.terminated = false;
2193
2194 if (this.client == null) {
2195 this.client = Redis.createClient(this.clientOptions);
2196 }
2197
2198 this.subscriber = this.client.duplicate();
2199 this.limiters = {};
2200 this.shas = {};
2201 this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(function () {
2202 return _this._loadScripts();
2203 }).then(function () {
2204 return {
2205 client: _this.client,
2206 subscriber: _this.subscriber
2207 };
2208 });
2209 }
2210
2211 _createClass(RedisConnection, [{
2212 key: "_setup",
2213 value: function _setup(client, sub) {
2214 var _this2 = this;
2215
2216 client.setMaxListeners(0);
2217 return new this.Promise(function (resolve, reject) {
2218 client.on("error", function (e) {
2219 return _this2.Events.trigger("error", e);
2220 });
2221
2222 if (sub) {
2223 client.on("message", function (channel, message) {
2224 var ref;
2225 return (ref = _this2.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0;
2226 });
2227 }
2228
2229 if (client.ready) {
2230 return resolve();
2231 } else {
2232 return client.once("ready", resolve);
2233 }
2234 });
2235 }
2236 }, {
2237 key: "_loadScript",
2238 value: function _loadScript(name) {
2239 var _this3 = this;
2240
2241 return new this.Promise(function (resolve, reject) {
2242 var payload;
2243 payload = Scripts$1.payload(name);
2244 return _this3.client.multi([["script", "load", payload]]).exec(function (err, replies) {
2245 if (err != null) {
2246 return reject(err);
2247 }
2248
2249 _this3.shas[name] = replies[0];
2250 return resolve(replies[0]);
2251 });
2252 });
2253 }
2254 }, {
2255 key: "_loadScripts",
2256 value: function _loadScripts() {
2257 var _this4 = this;
2258
2259 return this.Promise.all(Scripts$1.names.map(function (k) {
2260 return _this4._loadScript(k);
2261 }));
2262 }
2263 }, {
2264 key: "__runCommand__",
2265 value: function () {
2266 var _runCommand__ = _asyncToGenerator(
2267 /*#__PURE__*/
2268 regeneratorRuntime.mark(function _callee(cmd) {
2269 var _this5 = this;
2270
2271 return regeneratorRuntime.wrap(function _callee$(_context) {
2272 while (1) {
2273 switch (_context.prev = _context.next) {
2274 case 0:
2275 _context.next = 2;
2276 return this.ready;
2277
2278 case 2:
2279 return _context.abrupt("return", new this.Promise(function (resolve, reject) {
2280 return _this5.client.multi([cmd]).exec_atomic(function (err, replies) {
2281 if (err != null) {
2282 return reject(err);
2283 } else {
2284 return resolve(replies[0]);
2285 }
2286 });
2287 }));
2288
2289 case 3:
2290 case "end":
2291 return _context.stop();
2292 }
2293 }
2294 }, _callee, this);
2295 }));
2296
2297 return function __runCommand__(_x) {
2298 return _runCommand__.apply(this, arguments);
2299 };
2300 }()
2301 }, {
2302 key: "__addLimiter__",
2303 value: function __addLimiter__(instance) {
2304 var _this6 = this;
2305
2306 return this.Promise.all([instance.channel(), instance.channel_client()].map(function (channel) {
2307 return new _this6.Promise(function (resolve, reject) {
2308 var _handler;
2309
2310 _handler = function handler(chan) {
2311 if (chan === channel) {
2312 _this6.subscriber.removeListener("subscribe", _handler);
2313
2314 _this6.limiters[channel] = instance;
2315 return resolve();
2316 }
2317 };
2318
2319 _this6.subscriber.on("subscribe", _handler);
2320
2321 return _this6.subscriber.subscribe(channel);
2322 });
2323 }));
2324 }
2325 }, {
2326 key: "__removeLimiter__",
2327 value: function __removeLimiter__(instance) {
2328 var _this7 = this;
2329
2330 return this.Promise.all([instance.channel(), instance.channel_client()].map(
2331 /*#__PURE__*/
2332 function () {
2333 var _ref = _asyncToGenerator(
2334 /*#__PURE__*/
2335 regeneratorRuntime.mark(function _callee2(channel) {
2336 return regeneratorRuntime.wrap(function _callee2$(_context2) {
2337 while (1) {
2338 switch (_context2.prev = _context2.next) {
2339 case 0:
2340 if (_this7.terminated) {
2341 _context2.next = 3;
2342 break;
2343 }
2344
2345 _context2.next = 3;
2346 return new _this7.Promise(function (resolve, reject) {
2347 return _this7.subscriber.unsubscribe(channel, function (err, chan) {
2348 if (err != null) {
2349 return reject(err);
2350 }
2351
2352 if (chan === channel) {
2353 return resolve();
2354 }
2355 });
2356 });
2357
2358 case 3:
2359 return _context2.abrupt("return", delete _this7.limiters[channel]);
2360
2361 case 4:
2362 case "end":
2363 return _context2.stop();
2364 }
2365 }
2366 }, _callee2, this);
2367 }));
2368
2369 return function (_x2) {
2370 return _ref.apply(this, arguments);
2371 };
2372 }()));
2373 }
2374 }, {
2375 key: "__scriptArgs__",
2376 value: function __scriptArgs__(name, id, args, cb) {
2377 var keys;
2378 keys = Scripts$1.keys(name, id);
2379 return [this.shas[name], keys.length].concat(keys, args, cb);
2380 }
2381 }, {
2382 key: "__scriptFn__",
2383 value: function __scriptFn__(name) {
2384 return this.client.evalsha.bind(this.client);
2385 }
2386 }, {
2387 key: "disconnect",
2388 value: function disconnect() {
2389 var flush = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
2390 var i, k, len, ref;
2391 ref = Object.keys(this.limiters);
2392
2393 for (i = 0, len = ref.length; i < len; i++) {
2394 k = ref[i];
2395 clearInterval(this.limiters[k]._store.heartbeat);
2396 }
2397
2398 this.limiters = {};
2399 this.terminated = true;
2400 this.client.end(flush);
2401 this.subscriber.end(flush);
2402 return this.Promise.resolve();
2403 }
2404 }]);
2405
2406 return RedisConnection;
2407 }();
2408 RedisConnection.prototype.datastore = "redis";
2409 RedisConnection.prototype.defaults = {
2410 clientOptions: {},
2411 client: null,
2412 Promise: Promise,
2413 Events: null
2414 };
2415 return RedisConnection;
2416 }.call(commonjsGlobal);
2417
2418 var RedisConnection_1 = RedisConnection;
2419
2420 var Events$3, IORedisConnection, Scripts$2, parser$3;
2421 parser$3 = parser;
2422 Events$3 = Events_1;
2423 Scripts$2 = Scripts;
2424
2425 IORedisConnection = function () {
2426 var IORedisConnection =
2427 /*#__PURE__*/
2428 function () {
2429 function IORedisConnection() {
2430 var _this = this;
2431
2432 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2433
2434 _classCallCheck(this, IORedisConnection);
2435
2436 var Redis;
2437 Redis = eval("require")("ioredis"); // Obfuscated or else Webpack/Angular will try to inline the optional ioredis module
2438
2439 parser$3.load(options, this.defaults, this);
2440
2441 if (this.Events == null) {
2442 this.Events = new Events$3(this);
2443 }
2444
2445 this.terminated = false;
2446
2447 if (this.clusterNodes != null) {
2448 this.client = new Redis.Cluster(this.clusterNodes, this.clientOptions);
2449 this.subscriber = new Redis.Cluster(this.clusterNodes, this.clientOptions);
2450 } else {
2451 if (this.client == null) {
2452 this.client = new Redis(this.clientOptions);
2453 }
2454
2455 this.subscriber = this.client.duplicate();
2456 }
2457
2458 this.limiters = {};
2459 this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(function () {
2460 _this._loadScripts();
2461
2462 return {
2463 client: _this.client,
2464 subscriber: _this.subscriber
2465 };
2466 });
2467 }
2468
2469 _createClass(IORedisConnection, [{
2470 key: "_setup",
2471 value: function _setup(client, sub) {
2472 var _this2 = this;
2473
2474 client.setMaxListeners(0);
2475 return new this.Promise(function (resolve, reject) {
2476 client.on("error", function (e) {
2477 return _this2.Events.trigger("error", e);
2478 });
2479
2480 if (sub) {
2481 client.on("message", function (channel, message) {
2482 var ref;
2483 return (ref = _this2.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0;
2484 });
2485 }
2486
2487 if (client.status === "ready") {
2488 return resolve();
2489 } else {
2490 return client.once("ready", resolve);
2491 }
2492 });
2493 }
2494 }, {
2495 key: "_loadScripts",
2496 value: function _loadScripts() {
2497 var _this3 = this;
2498
2499 return Scripts$2.names.forEach(function (name) {
2500 return _this3.client.defineCommand(name, {
2501 lua: Scripts$2.payload(name)
2502 });
2503 });
2504 }
2505 }, {
2506 key: "__runCommand__",
2507 value: function () {
2508 var _runCommand__ = _asyncToGenerator(
2509 /*#__PURE__*/
2510 regeneratorRuntime.mark(function _callee(cmd) {
2511 var _, deleted, _ref, _ref2, _ref2$;
2512
2513 return regeneratorRuntime.wrap(function _callee$(_context) {
2514 while (1) {
2515 switch (_context.prev = _context.next) {
2516 case 0:
2517 _context.next = 2;
2518 return this.ready;
2519
2520 case 2:
2521 _context.next = 4;
2522 return this.client.pipeline([cmd]).exec();
2523
2524 case 4:
2525 _ref = _context.sent;
2526 _ref2 = _slicedToArray(_ref, 1);
2527 _ref2$ = _slicedToArray(_ref2[0], 2);
2528 _ = _ref2$[0];
2529 deleted = _ref2$[1];
2530 return _context.abrupt("return", deleted);
2531
2532 case 10:
2533 case "end":
2534 return _context.stop();
2535 }
2536 }
2537 }, _callee, this);
2538 }));
2539
2540 return function __runCommand__(_x) {
2541 return _runCommand__.apply(this, arguments);
2542 };
2543 }()
2544 }, {
2545 key: "__addLimiter__",
2546 value: function __addLimiter__(instance) {
2547 var _this4 = this;
2548
2549 return this.Promise.all([instance.channel(), instance.channel_client()].map(function (channel) {
2550 return new _this4.Promise(function (resolve, reject) {
2551 return _this4.subscriber.subscribe(channel, function () {
2552 _this4.limiters[channel] = instance;
2553 return resolve();
2554 });
2555 });
2556 }));
2557 }
2558 }, {
2559 key: "__removeLimiter__",
2560 value: function __removeLimiter__(instance) {
2561 var _this5 = this;
2562
2563 return [instance.channel(), instance.channel_client()].forEach(
2564 /*#__PURE__*/
2565 function () {
2566 var _ref3 = _asyncToGenerator(
2567 /*#__PURE__*/
2568 regeneratorRuntime.mark(function _callee2(channel) {
2569 return regeneratorRuntime.wrap(function _callee2$(_context2) {
2570 while (1) {
2571 switch (_context2.prev = _context2.next) {
2572 case 0:
2573 if (_this5.terminated) {
2574 _context2.next = 3;
2575 break;
2576 }
2577
2578 _context2.next = 3;
2579 return _this5.subscriber.unsubscribe(channel);
2580
2581 case 3:
2582 return _context2.abrupt("return", delete _this5.limiters[channel]);
2583
2584 case 4:
2585 case "end":
2586 return _context2.stop();
2587 }
2588 }
2589 }, _callee2, this);
2590 }));
2591
2592 return function (_x2) {
2593 return _ref3.apply(this, arguments);
2594 };
2595 }());
2596 }
2597 }, {
2598 key: "__scriptArgs__",
2599 value: function __scriptArgs__(name, id, args, cb) {
2600 var keys;
2601 keys = Scripts$2.keys(name, id);
2602 return [keys.length].concat(keys, args, cb);
2603 }
2604 }, {
2605 key: "__scriptFn__",
2606 value: function __scriptFn__(name) {
2607 return this.client[name].bind(this.client);
2608 }
2609 }, {
2610 key: "disconnect",
2611 value: function disconnect() {
2612 var flush = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
2613 var i, k, len, ref;
2614 ref = Object.keys(this.limiters);
2615
2616 for (i = 0, len = ref.length; i < len; i++) {
2617 k = ref[i];
2618 clearInterval(this.limiters[k]._store.heartbeat);
2619 }
2620
2621 this.limiters = {};
2622 this.terminated = true;
2623
2624 if (flush) {
2625 return this.Promise.all([this.client.quit(), this.subscriber.quit()]);
2626 } else {
2627 this.client.disconnect();
2628 this.subscriber.disconnect();
2629 return this.Promise.resolve();
2630 }
2631 }
2632 }]);
2633
2634 return IORedisConnection;
2635 }();
2636 IORedisConnection.prototype.datastore = "ioredis";
2637 IORedisConnection.prototype.defaults = {
2638 clientOptions: {},
2639 clusterNodes: null,
2640 client: null,
2641 Promise: Promise,
2642 Events: null
2643 };
2644 return IORedisConnection;
2645 }.call(commonjsGlobal);
2646
2647 var IORedisConnection_1 = IORedisConnection;
2648
2649 var BottleneckError$2, IORedisConnection$1, RedisConnection$1, RedisDatastore, parser$4;
2650 parser$4 = parser;
2651 BottleneckError$2 = BottleneckError_1;
2652 RedisConnection$1 = RedisConnection_1;
2653 IORedisConnection$1 = IORedisConnection_1;
2654
2655 RedisDatastore =
2656 /*#__PURE__*/
2657 function () {
2658 function RedisDatastore(instance, storeOptions, storeInstanceOptions) {
2659 var _this = this;
2660
2661 _classCallCheck(this, RedisDatastore);
2662
2663 this.instance = instance;
2664 this.storeOptions = storeOptions;
2665 this.originalId = this.instance.id;
2666 this.clientId = this.instance._randomIndex();
2667 parser$4.load(storeInstanceOptions, storeInstanceOptions, this);
2668 this.clients = {};
2669 this.capacityPriorityCounters = {};
2670 this.sharedConnection = this.connection != null;
2671
2672 if (this.connection == null) {
2673 this.connection = this.instance.datastore === "redis" ? new RedisConnection$1({
2674 clientOptions: this.clientOptions,
2675 Promise: this.Promise,
2676 Events: this.instance.Events
2677 }) : this.instance.datastore === "ioredis" ? new IORedisConnection$1({
2678 clientOptions: this.clientOptions,
2679 clusterNodes: this.clusterNodes,
2680 Promise: this.Promise,
2681 Events: this.instance.Events
2682 }) : void 0;
2683 }
2684
2685 this.instance.connection = this.connection;
2686 this.instance.datastore = this.connection.datastore;
2687 this.ready = this.connection.ready.then(function (clients) {
2688 _this.clients = clients;
2689 return _this.runScript("init", _this.prepareInitSettings(_this.clearDatastore));
2690 }).then(function () {
2691 return _this.connection.__addLimiter__(_this.instance);
2692 }).then(function () {
2693 return _this.runScript("heartbeat", []);
2694 }).then(function () {
2695 var base;
2696
2697 if (typeof (base = _this.heartbeat = setInterval(function () {
2698 return _this.runScript("heartbeat", []).catch(function (e) {
2699 return _this.instance.Events.trigger("error", e);
2700 });
2701 }, _this.heartbeatInterval)).unref === "function") {
2702 base.unref();
2703 }
2704
2705 return _this.clients;
2706 });
2707 }
2708
2709 _createClass(RedisDatastore, [{
2710 key: "__publish__",
2711 value: function () {
2712 var _publish__ = _asyncToGenerator(
2713 /*#__PURE__*/
2714 regeneratorRuntime.mark(function _callee(message) {
2715 var client, _ref;
2716
2717 return regeneratorRuntime.wrap(function _callee$(_context) {
2718 while (1) {
2719 switch (_context.prev = _context.next) {
2720 case 0:
2721 _context.next = 2;
2722 return this.ready;
2723
2724 case 2:
2725 _ref = _context.sent;
2726 client = _ref.client;
2727 return _context.abrupt("return", client.publish(this.instance.channel(), "message:".concat(message.toString())));
2728
2729 case 5:
2730 case "end":
2731 return _context.stop();
2732 }
2733 }
2734 }, _callee, this);
2735 }));
2736
2737 return function __publish__(_x) {
2738 return _publish__.apply(this, arguments);
2739 };
2740 }()
2741 }, {
2742 key: "onMessage",
2743 value: function () {
2744 var _onMessage = _asyncToGenerator(
2745 /*#__PURE__*/
2746 regeneratorRuntime.mark(function _callee3(channel, message) {
2747 var _this2 = this;
2748
2749 var capacity, counter, data, drained, e, newCapacity, pos, priorityClient, rawCapacity, type, _ref2, _data$split, _data$split2;
2750
2751 return regeneratorRuntime.wrap(function _callee3$(_context3) {
2752 while (1) {
2753 switch (_context3.prev = _context3.next) {
2754 case 0:
2755 _context3.prev = 0;
2756 pos = message.indexOf(":");
2757 _ref2 = [message.slice(0, pos), message.slice(pos + 1)];
2758 type = _ref2[0];
2759 data = _ref2[1];
2760
2761 if (!(type === "capacity")) {
2762 _context3.next = 11;
2763 break;
2764 }
2765
2766 _context3.next = 8;
2767 return this.instance._drainAll(data.length > 0 ? ~~data : void 0);
2768
2769 case 8:
2770 return _context3.abrupt("return", _context3.sent);
2771
2772 case 11:
2773 if (!(type === "capacity-priority")) {
2774 _context3.next = 37;
2775 break;
2776 }
2777
2778 _data$split = data.split(":");
2779 _data$split2 = _slicedToArray(_data$split, 3);
2780 rawCapacity = _data$split2[0];
2781 priorityClient = _data$split2[1];
2782 counter = _data$split2[2];
2783 capacity = rawCapacity.length > 0 ? ~~rawCapacity : void 0;
2784
2785 if (!(priorityClient === this.clientId)) {
2786 _context3.next = 28;
2787 break;
2788 }
2789
2790 _context3.next = 21;
2791 return this.instance._drainAll(capacity);
2792
2793 case 21:
2794 drained = _context3.sent;
2795 newCapacity = capacity != null ? capacity - (drained || 0) : "";
2796 _context3.next = 25;
2797 return this.clients.client.publish(this.instance.channel(), "capacity-priority:".concat(newCapacity, "::").concat(counter));
2798
2799 case 25:
2800 return _context3.abrupt("return", _context3.sent);
2801
2802 case 28:
2803 if (!(priorityClient === "")) {
2804 _context3.next = 34;
2805 break;
2806 }
2807
2808 clearTimeout(this.capacityPriorityCounters[counter]);
2809 delete this.capacityPriorityCounters[counter];
2810 return _context3.abrupt("return", this.instance._drainAll(capacity));
2811
2812 case 34:
2813 return _context3.abrupt("return", this.capacityPriorityCounters[counter] = setTimeout(
2814 /*#__PURE__*/
2815 _asyncToGenerator(
2816 /*#__PURE__*/
2817 regeneratorRuntime.mark(function _callee2() {
2818 var e;
2819 return regeneratorRuntime.wrap(function _callee2$(_context2) {
2820 while (1) {
2821 switch (_context2.prev = _context2.next) {
2822 case 0:
2823 _context2.prev = 0;
2824 delete _this2.capacityPriorityCounters[counter];
2825 _context2.next = 4;
2826 return _this2.runScript("blacklist_client", [priorityClient]);
2827
2828 case 4:
2829 _context2.next = 6;
2830 return _this2.instance._drainAll(capacity);
2831
2832 case 6:
2833 return _context2.abrupt("return", _context2.sent);
2834
2835 case 9:
2836 _context2.prev = 9;
2837 _context2.t0 = _context2["catch"](0);
2838 e = _context2.t0;
2839 return _context2.abrupt("return", _this2.instance.Events.trigger("error", e));
2840
2841 case 13:
2842 case "end":
2843 return _context2.stop();
2844 }
2845 }
2846 }, _callee2, this, [[0, 9]]);
2847 })), 1000));
2848
2849 case 35:
2850 _context3.next = 45;
2851 break;
2852
2853 case 37:
2854 if (!(type === "message")) {
2855 _context3.next = 41;
2856 break;
2857 }
2858
2859 return _context3.abrupt("return", this.instance.Events.trigger("message", data));
2860
2861 case 41:
2862 if (!(type === "blocked")) {
2863 _context3.next = 45;
2864 break;
2865 }
2866
2867 _context3.next = 44;
2868 return this.instance._dropAllQueued();
2869
2870 case 44:
2871 return _context3.abrupt("return", _context3.sent);
2872
2873 case 45:
2874 _context3.next = 51;
2875 break;
2876
2877 case 47:
2878 _context3.prev = 47;
2879 _context3.t0 = _context3["catch"](0);
2880 e = _context3.t0;
2881 return _context3.abrupt("return", this.instance.Events.trigger("error", e));
2882
2883 case 51:
2884 case "end":
2885 return _context3.stop();
2886 }
2887 }
2888 }, _callee3, this, [[0, 47]]);
2889 }));
2890
2891 return function onMessage(_x2, _x3) {
2892 return _onMessage.apply(this, arguments);
2893 };
2894 }()
2895 }, {
2896 key: "__disconnect__",
2897 value: function __disconnect__(flush) {
2898 clearInterval(this.heartbeat);
2899
2900 if (this.sharedConnection) {
2901 return this.connection.__removeLimiter__(this.instance);
2902 } else {
2903 return this.connection.disconnect(flush);
2904 }
2905 }
2906 }, {
2907 key: "runScript",
2908 value: function () {
2909 var _runScript = _asyncToGenerator(
2910 /*#__PURE__*/
2911 regeneratorRuntime.mark(function _callee4(name, args) {
2912 var _this3 = this;
2913
2914 return regeneratorRuntime.wrap(function _callee4$(_context4) {
2915 while (1) {
2916 switch (_context4.prev = _context4.next) {
2917 case 0:
2918 if (name === "init" || name === "heartbeat") {
2919 _context4.next = 3;
2920 break;
2921 }
2922
2923 _context4.next = 3;
2924 return this.ready;
2925
2926 case 3:
2927 return _context4.abrupt("return", new this.Promise(function (resolve, reject) {
2928 var all_args, arr;
2929 all_args = [Date.now(), _this3.clientId, _this3.instance.queued()].concat(args);
2930
2931 _this3.instance.Events.trigger("debug", "Calling Redis script: ".concat(name, ".lua"), all_args);
2932
2933 arr = _this3.connection.__scriptArgs__(name, _this3.originalId, all_args, function (err, replies) {
2934 if (err != null) {
2935 return reject(err);
2936 }
2937
2938 return resolve(replies);
2939 });
2940 return _this3.connection.__scriptFn__(name).apply(void 0, _toConsumableArray(arr));
2941 }).catch(function (e) {
2942 if (e.message === "SETTINGS_KEY_NOT_FOUND" && name !== "heartbeat") {
2943 return _this3.runScript("init", _this3.prepareInitSettings(false)).then(function () {
2944 return _this3.runScript(name, args);
2945 });
2946 } else if (name === "heartbeat") {
2947 return _this3.Promise.resolve();
2948 } else {
2949 return _this3.Promise.reject(e);
2950 }
2951 }));
2952
2953 case 4:
2954 case "end":
2955 return _context4.stop();
2956 }
2957 }
2958 }, _callee4, this);
2959 }));
2960
2961 return function runScript(_x4, _x5) {
2962 return _runScript.apply(this, arguments);
2963 };
2964 }()
2965 }, {
2966 key: "prepareArray",
2967 value: function prepareArray(arr) {
2968 var i, len, results, x;
2969 results = [];
2970
2971 for (i = 0, len = arr.length; i < len; i++) {
2972 x = arr[i];
2973 results.push(x != null ? x.toString() : "");
2974 }
2975
2976 return results;
2977 }
2978 }, {
2979 key: "prepareObject",
2980 value: function prepareObject(obj) {
2981 var arr, k, v;
2982 arr = [];
2983
2984 for (k in obj) {
2985 v = obj[k];
2986 arr.push(k, v != null ? v.toString() : "");
2987 }
2988
2989 return arr;
2990 }
2991 }, {
2992 key: "prepareInitSettings",
2993 value: function prepareInitSettings(clear) {
2994 var args;
2995 args = this.prepareObject(Object.assign({}, this.storeOptions, {
2996 id: this.originalId,
2997 version: this.instance.version,
2998 groupTimeout: this.timeout
2999 }));
3000 args.unshift(clear ? 1 : 0, this.instance.version);
3001 return args;
3002 }
3003 }, {
3004 key: "convertBool",
3005 value: function convertBool(b) {
3006 return !!b;
3007 }
3008 }, {
3009 key: "__updateSettings__",
3010 value: function () {
3011 var _updateSettings__ = _asyncToGenerator(
3012 /*#__PURE__*/
3013 regeneratorRuntime.mark(function _callee5(options) {
3014 return regeneratorRuntime.wrap(function _callee5$(_context5) {
3015 while (1) {
3016 switch (_context5.prev = _context5.next) {
3017 case 0:
3018 _context5.next = 2;
3019 return this.runScript("update_settings", this.prepareObject(options));
3020
3021 case 2:
3022 return _context5.abrupt("return", parser$4.overwrite(options, options, this.storeOptions));
3023
3024 case 3:
3025 case "end":
3026 return _context5.stop();
3027 }
3028 }
3029 }, _callee5, this);
3030 }));
3031
3032 return function __updateSettings__(_x6) {
3033 return _updateSettings__.apply(this, arguments);
3034 };
3035 }()
3036 }, {
3037 key: "__running__",
3038 value: function __running__() {
3039 return this.runScript("running", []);
3040 }
3041 }, {
3042 key: "__queued__",
3043 value: function __queued__() {
3044 return this.runScript("queued", []);
3045 }
3046 }, {
3047 key: "__done__",
3048 value: function __done__() {
3049 return this.runScript("done", []);
3050 }
3051 }, {
3052 key: "__groupCheck__",
3053 value: function () {
3054 var _groupCheck__ = _asyncToGenerator(
3055 /*#__PURE__*/
3056 regeneratorRuntime.mark(function _callee6() {
3057 return regeneratorRuntime.wrap(function _callee6$(_context6) {
3058 while (1) {
3059 switch (_context6.prev = _context6.next) {
3060 case 0:
3061 _context6.t0 = this;
3062 _context6.next = 3;
3063 return this.runScript("group_check", []);
3064
3065 case 3:
3066 _context6.t1 = _context6.sent;
3067 return _context6.abrupt("return", _context6.t0.convertBool.call(_context6.t0, _context6.t1));
3068
3069 case 5:
3070 case "end":
3071 return _context6.stop();
3072 }
3073 }
3074 }, _callee6, this);
3075 }));
3076
3077 return function __groupCheck__() {
3078 return _groupCheck__.apply(this, arguments);
3079 };
3080 }()
3081 }, {
3082 key: "__incrementReservoir__",
3083 value: function __incrementReservoir__(incr) {
3084 return this.runScript("increment_reservoir", [incr]);
3085 }
3086 }, {
3087 key: "__currentReservoir__",
3088 value: function __currentReservoir__() {
3089 return this.runScript("current_reservoir", []);
3090 }
3091 }, {
3092 key: "__check__",
3093 value: function () {
3094 var _check__ = _asyncToGenerator(
3095 /*#__PURE__*/
3096 regeneratorRuntime.mark(function _callee7(weight) {
3097 return regeneratorRuntime.wrap(function _callee7$(_context7) {
3098 while (1) {
3099 switch (_context7.prev = _context7.next) {
3100 case 0:
3101 _context7.t0 = this;
3102 _context7.next = 3;
3103 return this.runScript("check", this.prepareArray([weight]));
3104
3105 case 3:
3106 _context7.t1 = _context7.sent;
3107 return _context7.abrupt("return", _context7.t0.convertBool.call(_context7.t0, _context7.t1));
3108
3109 case 5:
3110 case "end":
3111 return _context7.stop();
3112 }
3113 }
3114 }, _callee7, this);
3115 }));
3116
3117 return function __check__(_x7) {
3118 return _check__.apply(this, arguments);
3119 };
3120 }()
3121 }, {
3122 key: "__register__",
3123 value: function () {
3124 var _register__ = _asyncToGenerator(
3125 /*#__PURE__*/
3126 regeneratorRuntime.mark(function _callee8(index, weight, expiration) {
3127 var reservoir, success, wait, _ref4, _ref5;
3128
3129 return regeneratorRuntime.wrap(function _callee8$(_context8) {
3130 while (1) {
3131 switch (_context8.prev = _context8.next) {
3132 case 0:
3133 _context8.next = 2;
3134 return this.runScript("register", this.prepareArray([index, weight, expiration]));
3135
3136 case 2:
3137 _ref4 = _context8.sent;
3138 _ref5 = _slicedToArray(_ref4, 3);
3139 success = _ref5[0];
3140 wait = _ref5[1];
3141 reservoir = _ref5[2];
3142 return _context8.abrupt("return", {
3143 success: this.convertBool(success),
3144 wait: wait,
3145 reservoir: reservoir
3146 });
3147
3148 case 8:
3149 case "end":
3150 return _context8.stop();
3151 }
3152 }
3153 }, _callee8, this);
3154 }));
3155
3156 return function __register__(_x8, _x9, _x10) {
3157 return _register__.apply(this, arguments);
3158 };
3159 }()
3160 }, {
3161 key: "__submit__",
3162 value: function () {
3163 var _submit__ = _asyncToGenerator(
3164 /*#__PURE__*/
3165 regeneratorRuntime.mark(function _callee9(queueLength, weight) {
3166 var blocked, e, maxConcurrent, overweight, reachedHWM, strategy, _ref6, _ref7, _e$message$split, _e$message$split2;
3167
3168 return regeneratorRuntime.wrap(function _callee9$(_context9) {
3169 while (1) {
3170 switch (_context9.prev = _context9.next) {
3171 case 0:
3172 _context9.prev = 0;
3173 _context9.next = 3;
3174 return this.runScript("submit", this.prepareArray([queueLength, weight]));
3175
3176 case 3:
3177 _ref6 = _context9.sent;
3178 _ref7 = _slicedToArray(_ref6, 3);
3179 reachedHWM = _ref7[0];
3180 blocked = _ref7[1];
3181 strategy = _ref7[2];
3182 return _context9.abrupt("return", {
3183 reachedHWM: this.convertBool(reachedHWM),
3184 blocked: this.convertBool(blocked),
3185 strategy: strategy
3186 });
3187
3188 case 11:
3189 _context9.prev = 11;
3190 _context9.t0 = _context9["catch"](0);
3191 e = _context9.t0;
3192
3193 if (!(e.message.indexOf("OVERWEIGHT") === 0)) {
3194 _context9.next = 23;
3195 break;
3196 }
3197
3198 _e$message$split = e.message.split(":");
3199 _e$message$split2 = _slicedToArray(_e$message$split, 3);
3200 overweight = _e$message$split2[0];
3201 weight = _e$message$split2[1];
3202 maxConcurrent = _e$message$split2[2];
3203 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));
3204
3205 case 23:
3206 throw e;
3207
3208 case 24:
3209 case "end":
3210 return _context9.stop();
3211 }
3212 }
3213 }, _callee9, this, [[0, 11]]);
3214 }));
3215
3216 return function __submit__(_x11, _x12) {
3217 return _submit__.apply(this, arguments);
3218 };
3219 }()
3220 }, {
3221 key: "__free__",
3222 value: function () {
3223 var _free__ = _asyncToGenerator(
3224 /*#__PURE__*/
3225 regeneratorRuntime.mark(function _callee10(index, weight) {
3226 var running;
3227 return regeneratorRuntime.wrap(function _callee10$(_context10) {
3228 while (1) {
3229 switch (_context10.prev = _context10.next) {
3230 case 0:
3231 _context10.next = 2;
3232 return this.runScript("free", this.prepareArray([index]));
3233
3234 case 2:
3235 running = _context10.sent;
3236 return _context10.abrupt("return", {
3237 running: running
3238 });
3239
3240 case 4:
3241 case "end":
3242 return _context10.stop();
3243 }
3244 }
3245 }, _callee10, this);
3246 }));
3247
3248 return function __free__(_x13, _x14) {
3249 return _free__.apply(this, arguments);
3250 };
3251 }()
3252 }]);
3253
3254 return RedisDatastore;
3255 }();
3256
3257 var RedisDatastore_1 = RedisDatastore;
3258
3259 var BottleneckError$3, States;
3260 BottleneckError$3 = BottleneckError_1;
3261
3262 States =
3263 /*#__PURE__*/
3264 function () {
3265 function States(status1) {
3266 _classCallCheck(this, States);
3267
3268 this.status = status1;
3269 this.jobs = {};
3270 this.counts = this.status.map(function () {
3271 return 0;
3272 });
3273 }
3274
3275 _createClass(States, [{
3276 key: "next",
3277 value: function next(id) {
3278 var current, next;
3279 current = this.jobs[id];
3280 next = current + 1;
3281
3282 if (current != null && next < this.status.length) {
3283 this.counts[current]--;
3284 this.counts[next]++;
3285 return this.jobs[id]++;
3286 } else if (current != null) {
3287 this.counts[current]--;
3288 return delete this.jobs[id];
3289 }
3290 }
3291 }, {
3292 key: "start",
3293 value: function start(id) {
3294 var initial;
3295 initial = 0;
3296 this.jobs[id] = initial;
3297 return this.counts[initial]++;
3298 }
3299 }, {
3300 key: "remove",
3301 value: function remove(id) {
3302 var current;
3303 current = this.jobs[id];
3304
3305 if (current != null) {
3306 this.counts[current]--;
3307 delete this.jobs[id];
3308 }
3309
3310 return current != null;
3311 }
3312 }, {
3313 key: "jobStatus",
3314 value: function jobStatus(id) {
3315 var ref;
3316 return (ref = this.status[this.jobs[id]]) != null ? ref : null;
3317 }
3318 }, {
3319 key: "statusJobs",
3320 value: function statusJobs(status) {
3321 var k, pos, ref, results, v;
3322
3323 if (status != null) {
3324 pos = this.status.indexOf(status);
3325
3326 if (pos < 0) {
3327 throw new BottleneckError$3("status must be one of ".concat(this.status.join(', ')));
3328 }
3329
3330 ref = this.jobs;
3331 results = [];
3332
3333 for (k in ref) {
3334 v = ref[k];
3335
3336 if (v === pos) {
3337 results.push(k);
3338 }
3339 }
3340
3341 return results;
3342 } else {
3343 return Object.keys(this.jobs);
3344 }
3345 }
3346 }, {
3347 key: "statusCounts",
3348 value: function statusCounts() {
3349 var _this = this;
3350
3351 return this.counts.reduce(function (acc, v, i) {
3352 acc[_this.status[i]] = v;
3353 return acc;
3354 }, {});
3355 }
3356 }]);
3357
3358 return States;
3359 }();
3360
3361 var States_1 = States;
3362
3363 var DLList$2,
3364 Sync,
3365 splice = [].splice;
3366 DLList$2 = DLList_1;
3367
3368 Sync =
3369 /*#__PURE__*/
3370 function () {
3371 function Sync(name, Promise) {
3372 _classCallCheck(this, Sync);
3373
3374 this.submit = this.submit.bind(this);
3375 this.name = name;
3376 this.Promise = Promise;
3377 this._running = 0;
3378 this._queue = new DLList$2();
3379 }
3380
3381 _createClass(Sync, [{
3382 key: "isEmpty",
3383 value: function isEmpty() {
3384 return this._queue.length === 0;
3385 }
3386 }, {
3387 key: "_tryToRun",
3388 value: function _tryToRun() {
3389 var _this = this;
3390
3391 var next;
3392
3393 if (this._running < 1 && this._queue.length > 0) {
3394 var _next;
3395
3396 this._running++;
3397 next = this._queue.shift();
3398 return (_next = next).task.apply(_next, _toConsumableArray(next.args).concat([function () {
3399 var _next2;
3400
3401 _this._running--;
3402
3403 _this._tryToRun();
3404
3405 return typeof next.cb === "function" ? (_next2 = next).cb.apply(_next2, arguments) : void 0;
3406 }]));
3407 }
3408 }
3409 }, {
3410 key: "submit",
3411 value: function submit(task) {
3412 var _ref, _ref2, _splice$call, _splice$call2;
3413
3414 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
3415 args[_key - 1] = arguments[_key];
3416 }
3417
3418 var cb, ref;
3419 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);
3420
3421 this._queue.push({
3422 task: task,
3423 args: args,
3424 cb: cb
3425 });
3426
3427 return this._tryToRun();
3428 }
3429 }, {
3430 key: "schedule",
3431 value: function schedule(task) {
3432 var _this2 = this;
3433
3434 for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
3435 args[_key2 - 1] = arguments[_key2];
3436 }
3437
3438 var wrapped;
3439
3440 wrapped = function wrapped() {
3441 var _ref3, _ref4, _splice$call3, _splice$call4;
3442
3443 for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
3444 args[_key3] = arguments[_key3];
3445 }
3446
3447 var cb, ref;
3448 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);
3449 return task.apply(void 0, _toConsumableArray(args)).then(function () {
3450 for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
3451 args[_key4] = arguments[_key4];
3452 }
3453
3454 return cb.apply(void 0, [null].concat(args));
3455 }).catch(function () {
3456 return cb.apply(void 0, arguments);
3457 });
3458 };
3459
3460 return new this.Promise(function (resolve, reject) {
3461 return _this2.submit.apply(_this2, [wrapped].concat(args, [function () {
3462 for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
3463 args[_key5] = arguments[_key5];
3464 }
3465
3466 return (args[0] != null ? reject : (args.shift(), resolve)).apply(void 0, args);
3467 }]));
3468 });
3469 }
3470 }]);
3471
3472 return Sync;
3473 }();
3474
3475 var Sync_1 = Sync;
3476
3477 var version = "2.16.2";
3478 var version$1 = {
3479 version: version
3480 };
3481
3482 var version$2 = /*#__PURE__*/Object.freeze({
3483 version: version,
3484 default: version$1
3485 });
3486
3487 var Events$4, Group, IORedisConnection$2, RedisConnection$2, Scripts$3, parser$5;
3488 parser$5 = parser;
3489 Events$4 = Events_1;
3490 RedisConnection$2 = RedisConnection_1;
3491 IORedisConnection$2 = IORedisConnection_1;
3492 Scripts$3 = Scripts;
3493
3494 Group = function () {
3495 var Group =
3496 /*#__PURE__*/
3497 function () {
3498 function Group() {
3499 var limiterOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3500
3501 _classCallCheck(this, Group);
3502
3503 this.deleteKey = this.deleteKey.bind(this);
3504 this.updateSettings = this.updateSettings.bind(this);
3505 this.limiterOptions = limiterOptions;
3506 parser$5.load(this.limiterOptions, this.defaults, this);
3507 this.Events = new Events$4(this);
3508 this.instances = {};
3509 this.Bottleneck = Bottleneck_1;
3510
3511 this._startAutoCleanup();
3512
3513 this.sharedConnection = this.connection != null;
3514
3515 if (this.connection == null) {
3516 if (this.limiterOptions.datastore === "redis") {
3517 this.connection = new RedisConnection$2(Object.assign({}, this.limiterOptions, {
3518 Events: this.Events
3519 }));
3520 } else if (this.limiterOptions.datastore === "ioredis") {
3521 this.connection = new IORedisConnection$2(Object.assign({}, this.limiterOptions, {
3522 Events: this.Events
3523 }));
3524 }
3525 }
3526 }
3527
3528 _createClass(Group, [{
3529 key: "key",
3530 value: function key() {
3531 var _this = this;
3532
3533 var _key = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
3534
3535 var ref;
3536 return (ref = this.instances[_key]) != null ? ref : function () {
3537 var limiter;
3538 limiter = _this.instances[_key] = new _this.Bottleneck(Object.assign(_this.limiterOptions, {
3539 id: "".concat(_this.id, "-").concat(_key),
3540 timeout: _this.timeout,
3541 connection: _this.connection
3542 }));
3543
3544 _this.Events.trigger("created", limiter, _key);
3545
3546 return limiter;
3547 }();
3548 }
3549 }, {
3550 key: "deleteKey",
3551 value: function () {
3552 var _deleteKey = _asyncToGenerator(
3553 /*#__PURE__*/
3554 regeneratorRuntime.mark(function _callee() {
3555 var key,
3556 deleted,
3557 instance,
3558 _args = arguments;
3559 return regeneratorRuntime.wrap(function _callee$(_context) {
3560 while (1) {
3561 switch (_context.prev = _context.next) {
3562 case 0:
3563 key = _args.length > 0 && _args[0] !== undefined ? _args[0] : "";
3564 instance = this.instances[key];
3565
3566 if (!this.connection) {
3567 _context.next = 6;
3568 break;
3569 }
3570
3571 _context.next = 5;
3572 return this.connection.__runCommand__(['del'].concat(_toConsumableArray(Scripts$3.allKeys("".concat(this.id, "-").concat(key)))));
3573
3574 case 5:
3575 deleted = _context.sent;
3576
3577 case 6:
3578 if (!(instance != null)) {
3579 _context.next = 10;
3580 break;
3581 }
3582
3583 delete this.instances[key];
3584 _context.next = 10;
3585 return instance.disconnect();
3586
3587 case 10:
3588 return _context.abrupt("return", instance != null || deleted > 0);
3589
3590 case 11:
3591 case "end":
3592 return _context.stop();
3593 }
3594 }
3595 }, _callee, this);
3596 }));
3597
3598 return function deleteKey() {
3599 return _deleteKey.apply(this, arguments);
3600 };
3601 }()
3602 }, {
3603 key: "limiters",
3604 value: function limiters() {
3605 var k, ref, results, v;
3606 ref = this.instances;
3607 results = [];
3608
3609 for (k in ref) {
3610 v = ref[k];
3611 results.push({
3612 key: k,
3613 limiter: v
3614 });
3615 }
3616
3617 return results;
3618 }
3619 }, {
3620 key: "keys",
3621 value: function keys() {
3622 return Object.keys(this.instances);
3623 }
3624 }, {
3625 key: "clusterKeys",
3626 value: function () {
3627 var _clusterKeys = _asyncToGenerator(
3628 /*#__PURE__*/
3629 regeneratorRuntime.mark(function _callee2() {
3630 var cursor, end, found, i, k, keys, len, next, start, _ref, _ref2;
3631
3632 return regeneratorRuntime.wrap(function _callee2$(_context2) {
3633 while (1) {
3634 switch (_context2.prev = _context2.next) {
3635 case 0:
3636 if (!(this.connection == null)) {
3637 _context2.next = 2;
3638 break;
3639 }
3640
3641 return _context2.abrupt("return", this.Promise.resolve(this.keys()));
3642
3643 case 2:
3644 keys = [];
3645 cursor = null;
3646 start = "b_".concat(this.id, "-").length;
3647 end = "_settings".length;
3648
3649 case 6:
3650 if (!(cursor !== 0)) {
3651 _context2.next = 17;
3652 break;
3653 }
3654
3655 _context2.next = 9;
3656 return this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", "b_".concat(this.id, "-*_settings"), "count", 10000]);
3657
3658 case 9:
3659 _ref = _context2.sent;
3660 _ref2 = _slicedToArray(_ref, 2);
3661 next = _ref2[0];
3662 found = _ref2[1];
3663 cursor = ~~next;
3664
3665 for (i = 0, len = found.length; i < len; i++) {
3666 k = found[i];
3667 keys.push(k.slice(start, -end));
3668 }
3669
3670 _context2.next = 6;
3671 break;
3672
3673 case 17:
3674 return _context2.abrupt("return", keys);
3675
3676 case 18:
3677 case "end":
3678 return _context2.stop();
3679 }
3680 }
3681 }, _callee2, this);
3682 }));
3683
3684 return function clusterKeys() {
3685 return _clusterKeys.apply(this, arguments);
3686 };
3687 }()
3688 }, {
3689 key: "_startAutoCleanup",
3690 value: function _startAutoCleanup() {
3691 var _this2 = this;
3692
3693 var base;
3694 clearInterval(this.interval);
3695 return typeof (base = this.interval = setInterval(
3696 /*#__PURE__*/
3697 _asyncToGenerator(
3698 /*#__PURE__*/
3699 regeneratorRuntime.mark(function _callee3() {
3700 var e, k, ref, results, time, v;
3701 return regeneratorRuntime.wrap(function _callee3$(_context3) {
3702 while (1) {
3703 switch (_context3.prev = _context3.next) {
3704 case 0:
3705 time = Date.now();
3706 ref = _this2.instances;
3707 results = [];
3708 _context3.t0 = regeneratorRuntime.keys(ref);
3709
3710 case 4:
3711 if ((_context3.t1 = _context3.t0()).done) {
3712 _context3.next = 23;
3713 break;
3714 }
3715
3716 k = _context3.t1.value;
3717 v = ref[k];
3718 _context3.prev = 7;
3719 _context3.next = 10;
3720 return v._store.__groupCheck__(time);
3721
3722 case 10:
3723 if (!_context3.sent) {
3724 _context3.next = 14;
3725 break;
3726 }
3727
3728 results.push(_this2.deleteKey(k));
3729 _context3.next = 15;
3730 break;
3731
3732 case 14:
3733 results.push(void 0);
3734
3735 case 15:
3736 _context3.next = 21;
3737 break;
3738
3739 case 17:
3740 _context3.prev = 17;
3741 _context3.t2 = _context3["catch"](7);
3742 e = _context3.t2;
3743 results.push(v.Events.trigger("error", e));
3744
3745 case 21:
3746 _context3.next = 4;
3747 break;
3748
3749 case 23:
3750 return _context3.abrupt("return", results);
3751
3752 case 24:
3753 case "end":
3754 return _context3.stop();
3755 }
3756 }
3757 }, _callee3, this, [[7, 17]]);
3758 })), this.timeout / 2)).unref === "function" ? base.unref() : void 0;
3759 }
3760 }, {
3761 key: "updateSettings",
3762 value: function updateSettings() {
3763 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3764 parser$5.overwrite(options, this.defaults, this);
3765 parser$5.overwrite(options, options, this.limiterOptions);
3766
3767 if (options.timeout != null) {
3768 return this._startAutoCleanup();
3769 }
3770 }
3771 }, {
3772 key: "disconnect",
3773 value: function disconnect() {
3774 var flush = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
3775 var ref;
3776
3777 if (!this.sharedConnection) {
3778 return (ref = this.connection) != null ? ref.disconnect(flush) : void 0;
3779 }
3780 }
3781 }]);
3782
3783 return Group;
3784 }();
3785 Group.prototype.defaults = {
3786 timeout: 1000 * 60 * 5,
3787 connection: null,
3788 Promise: Promise,
3789 id: "group-key"
3790 };
3791 return Group;
3792 }.call(commonjsGlobal);
3793
3794 var Group_1 = Group;
3795
3796 var Batcher, Events$5, parser$6;
3797 parser$6 = parser;
3798 Events$5 = Events_1;
3799
3800 Batcher = function () {
3801 var Batcher =
3802 /*#__PURE__*/
3803 function () {
3804 function Batcher() {
3805 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3806
3807 _classCallCheck(this, Batcher);
3808
3809 this.options = options;
3810 parser$6.load(this.options, this.defaults, this);
3811 this.Events = new Events$5(this);
3812 this._arr = [];
3813
3814 this._resetPromise();
3815
3816 this._lastFlush = Date.now();
3817 }
3818
3819 _createClass(Batcher, [{
3820 key: "_resetPromise",
3821 value: function _resetPromise() {
3822 var _this = this;
3823
3824 return this._promise = new this.Promise(function (res, rej) {
3825 return _this._resolve = res;
3826 });
3827 }
3828 }, {
3829 key: "_flush",
3830 value: function _flush() {
3831 clearTimeout(this._timeout);
3832 this._lastFlush = Date.now();
3833
3834 this._resolve();
3835
3836 this.Events.trigger("batch", this._arr);
3837 this._arr = [];
3838 return this._resetPromise();
3839 }
3840 }, {
3841 key: "add",
3842 value: function add(data) {
3843 var _this2 = this;
3844
3845 var ret;
3846
3847 this._arr.push(data);
3848
3849 ret = this._promise;
3850
3851 if (this._arr.length === this.maxSize) {
3852 this._flush();
3853 } else if (this.maxTime != null && this._arr.length === 1) {
3854 this._timeout = setTimeout(function () {
3855 return _this2._flush();
3856 }, this.maxTime);
3857 }
3858
3859 return ret;
3860 }
3861 }]);
3862
3863 return Batcher;
3864 }();
3865 Batcher.prototype.defaults = {
3866 maxTime: null,
3867 maxSize: null,
3868 Promise: Promise
3869 };
3870 return Batcher;
3871 }.call(commonjsGlobal);
3872
3873 var Batcher_1 = Batcher;
3874
3875 var require$$7 = getCjsExportFromNamespace(version$2);
3876
3877 var Bottleneck,
3878 DEFAULT_PRIORITY,
3879 Events$6,
3880 LocalDatastore$1,
3881 NUM_PRIORITIES,
3882 Queues$1,
3883 RedisDatastore$1,
3884 States$1,
3885 Sync$1,
3886 parser$7,
3887 splice$1 = [].splice;
3888 NUM_PRIORITIES = 10;
3889 DEFAULT_PRIORITY = 5;
3890 parser$7 = parser;
3891 Queues$1 = Queues_1;
3892 LocalDatastore$1 = LocalDatastore_1;
3893 RedisDatastore$1 = RedisDatastore_1;
3894 Events$6 = Events_1;
3895 States$1 = States_1;
3896 Sync$1 = Sync_1;
3897
3898 Bottleneck = function () {
3899 var Bottleneck =
3900 /*#__PURE__*/
3901 function () {
3902 function Bottleneck() {
3903 var _this = this;
3904
3905 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3906
3907 _classCallCheck(this, Bottleneck);
3908
3909 var storeInstanceOptions, storeOptions;
3910 this._drainOne = this._drainOne.bind(this);
3911 this.submit = this.submit.bind(this);
3912 this.schedule = this.schedule.bind(this);
3913 this.updateSettings = this.updateSettings.bind(this);
3914 this.incrementReservoir = this.incrementReservoir.bind(this);
3915
3916 for (var _len = arguments.length, invalid = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
3917 invalid[_key - 1] = arguments[_key];
3918 }
3919
3920 this._validateOptions(options, invalid);
3921
3922 parser$7.load(options, this.instanceDefaults, this);
3923 this._queues = new Queues$1(NUM_PRIORITIES);
3924 this._scheduled = {};
3925 this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : []));
3926 this._limiter = null;
3927 this.Events = new Events$6(this);
3928 this._submitLock = new Sync$1("submit", this.Promise);
3929 this._registerLock = new Sync$1("register", this.Promise);
3930 storeOptions = parser$7.load(options, this.storeDefaults, {});
3931
3932 this._store = function () {
3933 if (this.datastore === "redis" || this.datastore === "ioredis" || this.connection != null) {
3934 storeInstanceOptions = parser$7.load(options, this.redisStoreDefaults, {});
3935 return new RedisDatastore$1(this, storeOptions, storeInstanceOptions);
3936 } else if (this.datastore === "local") {
3937 storeInstanceOptions = parser$7.load(options, this.localStoreDefaults, {});
3938 return new LocalDatastore$1(this, storeOptions, storeInstanceOptions);
3939 } else {
3940 throw new Bottleneck.prototype.BottleneckError("Invalid datastore type: ".concat(this.datastore));
3941 }
3942 }.call(this);
3943
3944 this._queues.on("leftzero", function () {
3945 var base;
3946 return typeof (base = _this._store.heartbeat).ref === "function" ? base.ref() : void 0;
3947 });
3948
3949 this._queues.on("zero", function () {
3950 var base;
3951 return typeof (base = _this._store.heartbeat).unref === "function" ? base.unref() : void 0;
3952 });
3953 }
3954
3955 _createClass(Bottleneck, [{
3956 key: "_validateOptions",
3957 value: function _validateOptions(options, invalid) {
3958 if (!(options != null && _typeof(options) === "object" && invalid.length === 0)) {
3959 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.");
3960 }
3961 }
3962 }, {
3963 key: "ready",
3964 value: function ready() {
3965 return this._store.ready;
3966 }
3967 }, {
3968 key: "clients",
3969 value: function clients() {
3970 return this._store.clients;
3971 }
3972 }, {
3973 key: "channel",
3974 value: function channel() {
3975 return "b_".concat(this.id);
3976 }
3977 }, {
3978 key: "channel_client",
3979 value: function channel_client() {
3980 return "b_".concat(this.id, "_").concat(this._store.clientId);
3981 }
3982 }, {
3983 key: "publish",
3984 value: function publish(message) {
3985 return this._store.__publish__(message);
3986 }
3987 }, {
3988 key: "disconnect",
3989 value: function disconnect() {
3990 var flush = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
3991 return this._store.__disconnect__(flush);
3992 }
3993 }, {
3994 key: "chain",
3995 value: function chain(_limiter) {
3996 this._limiter = _limiter;
3997 return this;
3998 }
3999 }, {
4000 key: "queued",
4001 value: function queued(priority) {
4002 return this._queues.queued(priority);
4003 }
4004 }, {
4005 key: "clusterQueued",
4006 value: function clusterQueued() {
4007 return this._store.__queued__();
4008 }
4009 }, {
4010 key: "empty",
4011 value: function empty() {
4012 return this.queued() === 0 && this._submitLock.isEmpty();
4013 }
4014 }, {
4015 key: "running",
4016 value: function running() {
4017 return this._store.__running__();
4018 }
4019 }, {
4020 key: "done",
4021 value: function done() {
4022 return this._store.__done__();
4023 }
4024 }, {
4025 key: "jobStatus",
4026 value: function jobStatus(id) {
4027 return this._states.jobStatus(id);
4028 }
4029 }, {
4030 key: "jobs",
4031 value: function jobs(status) {
4032 return this._states.statusJobs(status);
4033 }
4034 }, {
4035 key: "counts",
4036 value: function counts() {
4037 return this._states.statusCounts();
4038 }
4039 }, {
4040 key: "_sanitizePriority",
4041 value: function _sanitizePriority(priority) {
4042 var sProperty;
4043 sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority;
4044
4045 if (sProperty < 0) {
4046 return 0;
4047 } else if (sProperty > NUM_PRIORITIES - 1) {
4048 return NUM_PRIORITIES - 1;
4049 } else {
4050 return sProperty;
4051 }
4052 }
4053 }, {
4054 key: "_randomIndex",
4055 value: function _randomIndex() {
4056 return Math.random().toString(36).slice(2);
4057 }
4058 }, {
4059 key: "check",
4060 value: function check() {
4061 var weight = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
4062 return this._store.__check__(weight);
4063 }
4064 }, {
4065 key: "_run",
4066 value: function _run(next, wait, index, retryCount) {
4067 var _this2 = this;
4068
4069 var completed, done;
4070 this.Events.trigger("debug", "Scheduling ".concat(next.options.id), {
4071 args: next.args,
4072 options: next.options
4073 });
4074 done = false;
4075
4076 completed =
4077 /*#__PURE__*/
4078 function () {
4079 var _ref = _asyncToGenerator(
4080 /*#__PURE__*/
4081 regeneratorRuntime.mark(function _callee() {
4082 var e,
4083 error,
4084 eventInfo,
4085 retry,
4086 retryAfter,
4087 running,
4088 _ref2,
4089 _args = arguments;
4090
4091 return regeneratorRuntime.wrap(function _callee$(_context) {
4092 while (1) {
4093 switch (_context.prev = _context.next) {
4094 case 0:
4095 if (done) {
4096 _context.next = 30;
4097 break;
4098 }
4099
4100 _context.prev = 1;
4101 done = true;
4102 clearTimeout(_this2._scheduled[index].expiration);
4103 delete _this2._scheduled[index];
4104 eventInfo = {
4105 args: next.args,
4106 options: next.options,
4107 retryCount: retryCount
4108 };
4109
4110 if (!((error = _args.length <= 0 ? undefined : _args[0]) != null)) {
4111 _context.next = 14;
4112 break;
4113 }
4114
4115 _context.next = 9;
4116 return _this2.Events.trigger("failed", error, eventInfo);
4117
4118 case 9:
4119 retry = _context.sent;
4120
4121 if (!(retry != null)) {
4122 _context.next = 14;
4123 break;
4124 }
4125
4126 retryAfter = ~~retry;
4127
4128 _this2.Events.trigger("retry", "Retrying ".concat(next.options.id, " after ").concat(retryAfter, " ms"), eventInfo);
4129
4130 return _context.abrupt("return", _this2._run(next, retryAfter, index, retryCount + 1));
4131
4132 case 14:
4133 _this2._states.next(next.options.id); // DONE
4134
4135
4136 _this2.Events.trigger("debug", "Completed ".concat(next.options.id), eventInfo);
4137
4138 _this2.Events.trigger("done", "Completed ".concat(next.options.id), eventInfo);
4139
4140 _context.next = 19;
4141 return _this2._store.__free__(index, next.options.weight);
4142
4143 case 19:
4144 _ref2 = _context.sent;
4145 running = _ref2.running;
4146
4147 _this2.Events.trigger("debug", "Freed ".concat(next.options.id), eventInfo);
4148
4149 if (running === 0 && _this2.empty()) {
4150 _this2.Events.trigger("idle");
4151 }
4152
4153 return _context.abrupt("return", typeof next.cb === "function" ? next.cb.apply(next, _args) : void 0);
4154
4155 case 26:
4156 _context.prev = 26;
4157 _context.t0 = _context["catch"](1);
4158 e = _context.t0;
4159 return _context.abrupt("return", _this2.Events.trigger("error", e));
4160
4161 case 30:
4162 case "end":
4163 return _context.stop();
4164 }
4165 }
4166 }, _callee, this, [[1, 26]]);
4167 }));
4168
4169 return function completed() {
4170 return _ref.apply(this, arguments);
4171 };
4172 }();
4173
4174 if (retryCount === 0) {
4175 // RUNNING
4176 this._states.next(next.options.id);
4177 }
4178
4179 return this._scheduled[index] = {
4180 timeout: setTimeout(function () {
4181 _this2.Events.trigger("debug", "Executing ".concat(next.options.id), {
4182 args: next.args,
4183 options: next.options
4184 });
4185
4186 if (retryCount === 0) {
4187 // EXECUTING
4188 _this2._states.next(next.options.id);
4189 }
4190
4191 if (_this2._limiter != null) {
4192 var _this2$_limiter;
4193
4194 return (_this2$_limiter = _this2._limiter).submit.apply(_this2$_limiter, [next.options, next.task].concat(_toConsumableArray(next.args), [completed]));
4195 } else {
4196 return next.task.apply(next, _toConsumableArray(next.args).concat([completed]));
4197 }
4198 }, wait),
4199 expiration: next.options.expiration != null ? setTimeout(function () {
4200 return completed(new Bottleneck.prototype.BottleneckError("This job timed out after ".concat(next.options.expiration, " ms.")));
4201 }, wait + next.options.expiration) : void 0,
4202 job: next
4203 };
4204 }
4205 }, {
4206 key: "_drainOne",
4207 value: function _drainOne(capacity) {
4208 var _this3 = this;
4209
4210 return this._registerLock.schedule(function () {
4211 var args, index, next, options, queue;
4212
4213 if (_this3.queued() === 0) {
4214 return _this3.Promise.resolve(null);
4215 }
4216
4217 queue = _this3._queues.getFirst();
4218
4219 var _next = next = queue.first();
4220
4221 options = _next.options;
4222 args = _next.args;
4223
4224 if (capacity != null && options.weight > capacity) {
4225 return _this3.Promise.resolve(null);
4226 }
4227
4228 _this3.Events.trigger("debug", "Draining ".concat(options.id), {
4229 args: args,
4230 options: options
4231 });
4232
4233 index = _this3._randomIndex();
4234 return _this3._store.__register__(index, options.weight, options.expiration).then(function (_ref3) {
4235 var success = _ref3.success,
4236 wait = _ref3.wait,
4237 reservoir = _ref3.reservoir;
4238 var empty;
4239
4240 _this3.Events.trigger("debug", "Drained ".concat(options.id), {
4241 success: success,
4242 args: args,
4243 options: options
4244 });
4245
4246 if (success) {
4247 queue.shift();
4248 empty = _this3.empty();
4249
4250 if (empty) {
4251 _this3.Events.trigger("empty");
4252 }
4253
4254 if (reservoir === 0) {
4255 _this3.Events.trigger("depleted", empty);
4256 }
4257
4258 _this3._run(next, wait, index, 0);
4259
4260 return _this3.Promise.resolve(options.weight);
4261 } else {
4262 return _this3.Promise.resolve(null);
4263 }
4264 });
4265 });
4266 }
4267 }, {
4268 key: "_drainAll",
4269 value: function _drainAll(capacity) {
4270 var _this4 = this;
4271
4272 var total = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
4273 return this._drainOne(capacity).then(function (drained) {
4274 var newCapacity;
4275
4276 if (drained != null) {
4277 newCapacity = capacity != null ? capacity - drained : capacity;
4278 return _this4._drainAll(newCapacity, total + drained);
4279 } else {
4280 return _this4.Promise.resolve(total);
4281 }
4282 }).catch(function (e) {
4283 return _this4.Events.trigger("error", e);
4284 });
4285 }
4286 }, {
4287 key: "_drop",
4288 value: function _drop(job) {
4289 var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "This job has been dropped by Bottleneck";
4290
4291 if (this._states.remove(job.options.id)) {
4292 if (this.rejectOnDrop) {
4293 if (typeof job.cb === "function") {
4294 job.cb(new Bottleneck.prototype.BottleneckError(message));
4295 }
4296 }
4297
4298 return this.Events.trigger("dropped", job);
4299 }
4300 }
4301 }, {
4302 key: "_dropAllQueued",
4303 value: function _dropAllQueued(message) {
4304 var _this5 = this;
4305
4306 return this._queues.shiftAll(function (job) {
4307 return _this5._drop(job, message);
4308 });
4309 }
4310 }, {
4311 key: "stop",
4312 value: function stop() {
4313 var _this6 = this;
4314
4315 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4316 var done, waitForExecuting;
4317 options = parser$7.load(options, this.stopDefaults);
4318
4319 waitForExecuting = function waitForExecuting(at) {
4320 var finished;
4321
4322 finished = function finished() {
4323 var counts;
4324 counts = _this6._states.counts;
4325 return counts[0] + counts[1] + counts[2] + counts[3] === at;
4326 };
4327
4328 return new _this6.Promise(function (resolve, reject) {
4329 if (finished()) {
4330 return resolve();
4331 } else {
4332 return _this6.on("done", function () {
4333 if (finished()) {
4334 _this6.removeAllListeners("done");
4335
4336 return resolve();
4337 }
4338 });
4339 }
4340 });
4341 };
4342
4343 done = options.dropWaitingJobs ? (this._run = function (next) {
4344 return _this6._drop(next, options.dropErrorMessage);
4345 }, this._drainOne = function () {
4346 return _this6.Promise.resolve(null);
4347 }, this._registerLock.schedule(function () {
4348 return _this6._submitLock.schedule(function () {
4349 var k, ref, v;
4350 ref = _this6._scheduled;
4351
4352 for (k in ref) {
4353 v = ref[k];
4354
4355 if (_this6.jobStatus(v.job.options.id) === "RUNNING") {
4356 clearTimeout(v.timeout);
4357 clearTimeout(v.expiration);
4358
4359 _this6._drop(v.job, options.dropErrorMessage);
4360 }
4361 }
4362
4363 _this6._dropAllQueued(options.dropErrorMessage);
4364
4365 return waitForExecuting(0);
4366 });
4367 })) : this.schedule({
4368 priority: NUM_PRIORITIES - 1,
4369 weight: 0
4370 }, function () {
4371 return waitForExecuting(1);
4372 });
4373
4374 this.submit = function () {
4375 var _ref4, _ref5, _splice$call, _splice$call2;
4376
4377 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
4378 args[_key2] = arguments[_key2];
4379 }
4380
4381 var cb, ref;
4382 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);
4383 return typeof cb === "function" ? cb(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)) : void 0;
4384 };
4385
4386 this.stop = function () {
4387 return _this6.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called"));
4388 };
4389
4390 return done;
4391 }
4392 }, {
4393 key: "submit",
4394 value: function submit() {
4395 var _this7 = this;
4396
4397 for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
4398 args[_key3] = arguments[_key3];
4399 }
4400
4401 var cb, job, options, ref, ref1, task;
4402
4403 if (typeof args[0] === "function") {
4404 var _ref6, _ref7, _splice$call3, _splice$call4;
4405
4406 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);
4407 options = parser$7.load({}, this.jobDefaults, {});
4408 } else {
4409 var _ref8, _ref9, _splice$call5, _splice$call6;
4410
4411 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);
4412 options = parser$7.load(options, this.jobDefaults);
4413 }
4414
4415 job = {
4416 options: options,
4417 task: task,
4418 args: args,
4419 cb: cb
4420 };
4421 options.priority = this._sanitizePriority(options.priority);
4422
4423 if (options.id === this.jobDefaults.id) {
4424 options.id = "".concat(options.id, "-").concat(this._randomIndex());
4425 }
4426
4427 if (this.jobStatus(options.id) != null) {
4428 if (typeof job.cb === "function") {
4429 job.cb(new Bottleneck.prototype.BottleneckError("A job with the same id already exists (id=".concat(options.id, ")")));
4430 }
4431
4432 return false;
4433 }
4434
4435 this._states.start(options.id); // RECEIVED
4436
4437
4438 this.Events.trigger("debug", "Queueing ".concat(options.id), {
4439 args: args,
4440 options: options
4441 });
4442 return this._submitLock.schedule(
4443 /*#__PURE__*/
4444 _asyncToGenerator(
4445 /*#__PURE__*/
4446 regeneratorRuntime.mark(function _callee2() {
4447 var blocked, e, reachedHWM, shifted, strategy, _ref11;
4448
4449 return regeneratorRuntime.wrap(function _callee2$(_context2) {
4450 while (1) {
4451 switch (_context2.prev = _context2.next) {
4452 case 0:
4453 _context2.prev = 0;
4454 _context2.next = 3;
4455 return _this7._store.__submit__(_this7.queued(), options.weight);
4456
4457 case 3:
4458 _ref11 = _context2.sent;
4459 reachedHWM = _ref11.reachedHWM;
4460 blocked = _ref11.blocked;
4461 strategy = _ref11.strategy;
4462
4463 _this7.Events.trigger("debug", "Queued ".concat(options.id), {
4464 args: args,
4465 options: options,
4466 reachedHWM: reachedHWM,
4467 blocked: blocked
4468 });
4469
4470 _context2.next = 17;
4471 break;
4472
4473 case 10:
4474 _context2.prev = 10;
4475 _context2.t0 = _context2["catch"](0);
4476 e = _context2.t0;
4477
4478 _this7._states.remove(options.id);
4479
4480 _this7.Events.trigger("debug", "Could not queue ".concat(options.id), {
4481 args: args,
4482 options: options,
4483 error: e
4484 });
4485
4486 if (typeof job.cb === "function") {
4487 job.cb(e);
4488 }
4489
4490 return _context2.abrupt("return", false);
4491
4492 case 17:
4493 if (!blocked) {
4494 _context2.next = 22;
4495 break;
4496 }
4497
4498 _this7._drop(job);
4499
4500 return _context2.abrupt("return", true);
4501
4502 case 22:
4503 if (!reachedHWM) {
4504 _context2.next = 28;
4505 break;
4506 }
4507
4508 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;
4509
4510 if (shifted != null) {
4511 _this7._drop(shifted);
4512 }
4513
4514 if (!(shifted == null || strategy === Bottleneck.prototype.strategy.OVERFLOW)) {
4515 _context2.next = 28;
4516 break;
4517 }
4518
4519 if (shifted == null) {
4520 _this7._drop(job);
4521 }
4522
4523 return _context2.abrupt("return", reachedHWM);
4524
4525 case 28:
4526 _this7._states.next(job.options.id); // QUEUED
4527
4528
4529 _this7._queues.push(options.priority, job);
4530
4531 _context2.next = 32;
4532 return _this7._drainAll();
4533
4534 case 32:
4535 return _context2.abrupt("return", reachedHWM);
4536
4537 case 33:
4538 case "end":
4539 return _context2.stop();
4540 }
4541 }
4542 }, _callee2, this, [[0, 10]]);
4543 })));
4544 }
4545 }, {
4546 key: "schedule",
4547 value: function schedule() {
4548 var _this8 = this;
4549
4550 for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
4551 args[_key4] = arguments[_key4];
4552 }
4553
4554 var options, task, wrapped;
4555
4556 if (typeof args[0] === "function") {
4557 var _args3 = args;
4558
4559 var _args4 = _toArray(_args3);
4560
4561 task = _args4[0];
4562 args = _args4.slice(1);
4563 options = parser$7.load({}, this.jobDefaults, {});
4564 } else {
4565 var _args5 = args;
4566
4567 var _args6 = _toArray(_args5);
4568
4569 options = _args6[0];
4570 task = _args6[1];
4571 args = _args6.slice(2);
4572 options = parser$7.load(options, this.jobDefaults);
4573 }
4574
4575 wrapped = function wrapped() {
4576 var _ref12, _ref13, _splice$call7, _splice$call8;
4577
4578 for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
4579 args[_key5] = arguments[_key5];
4580 }
4581
4582 var cb, ref, returned;
4583 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);
4584 returned = task.apply(void 0, _toConsumableArray(args));
4585 return (!((returned != null ? returned.then : void 0) != null && typeof returned.then === "function") ? _this8.Promise.resolve(returned) : returned).then(function () {
4586 for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
4587 args[_key6] = arguments[_key6];
4588 }
4589
4590 return cb.apply(void 0, [null].concat(args));
4591 }).catch(function () {
4592 return cb.apply(void 0, arguments);
4593 });
4594 };
4595
4596 return new this.Promise(function (resolve, reject) {
4597 return _this8.submit.apply(_this8, [options, wrapped].concat(_toConsumableArray(args), [function () {
4598 for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
4599 args[_key7] = arguments[_key7];
4600 }
4601
4602 return (args[0] != null ? reject : (args.shift(), resolve)).apply(void 0, args);
4603 }])).catch(function (e) {
4604 return _this8.Events.trigger("error", e);
4605 });
4606 });
4607 }
4608 }, {
4609 key: "wrap",
4610 value: function wrap(fn) {
4611 var schedule, wrapped;
4612 schedule = this.schedule;
4613
4614 wrapped = function wrapped() {
4615 for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
4616 args[_key8] = arguments[_key8];
4617 }
4618
4619 return schedule.apply(void 0, [fn.bind(this)].concat(args));
4620 };
4621
4622 wrapped.withOptions = function (options) {
4623 for (var _len9 = arguments.length, args = new Array(_len9 > 1 ? _len9 - 1 : 0), _key9 = 1; _key9 < _len9; _key9++) {
4624 args[_key9 - 1] = arguments[_key9];
4625 }
4626
4627 return schedule.apply(void 0, [options, fn].concat(args));
4628 };
4629
4630 return wrapped;
4631 }
4632 }, {
4633 key: "updateSettings",
4634 value: function () {
4635 var _updateSettings = _asyncToGenerator(
4636 /*#__PURE__*/
4637 regeneratorRuntime.mark(function _callee3() {
4638 var options,
4639 _args7 = arguments;
4640 return regeneratorRuntime.wrap(function _callee3$(_context3) {
4641 while (1) {
4642 switch (_context3.prev = _context3.next) {
4643 case 0:
4644 options = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : {};
4645 _context3.next = 3;
4646 return this._store.__updateSettings__(parser$7.overwrite(options, this.storeDefaults));
4647
4648 case 3:
4649 parser$7.overwrite(options, this.instanceDefaults, this);
4650 return _context3.abrupt("return", this);
4651
4652 case 5:
4653 case "end":
4654 return _context3.stop();
4655 }
4656 }
4657 }, _callee3, this);
4658 }));
4659
4660 return function updateSettings() {
4661 return _updateSettings.apply(this, arguments);
4662 };
4663 }()
4664 }, {
4665 key: "currentReservoir",
4666 value: function currentReservoir() {
4667 return this._store.__currentReservoir__();
4668 }
4669 }, {
4670 key: "incrementReservoir",
4671 value: function incrementReservoir() {
4672 var incr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
4673 return this._store.__incrementReservoir__(incr);
4674 }
4675 }]);
4676
4677 return Bottleneck;
4678 }();
4679 Bottleneck.default = Bottleneck;
4680 Bottleneck.Events = Events$6;
4681 Bottleneck.version = Bottleneck.prototype.version = require$$7.version;
4682 Bottleneck.strategy = Bottleneck.prototype.strategy = {
4683 LEAK: 1,
4684 OVERFLOW: 2,
4685 OVERFLOW_PRIORITY: 4,
4686 BLOCK: 3
4687 };
4688 Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1;
4689 Bottleneck.Group = Bottleneck.prototype.Group = Group_1;
4690 Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = RedisConnection_1;
4691 Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = IORedisConnection_1;
4692 Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1;
4693 Bottleneck.prototype.jobDefaults = {
4694 priority: DEFAULT_PRIORITY,
4695 weight: 1,
4696 expiration: null,
4697 id: "<no-id>"
4698 };
4699 Bottleneck.prototype.storeDefaults = {
4700 maxConcurrent: null,
4701 minTime: 0,
4702 highWater: null,
4703 strategy: Bottleneck.prototype.strategy.LEAK,
4704 penalty: null,
4705 reservoir: null,
4706 reservoirRefreshInterval: null,
4707 reservoirRefreshAmount: null
4708 };
4709 Bottleneck.prototype.localStoreDefaults = {
4710 Promise: Promise,
4711 timeout: null,
4712 heartbeatInterval: 250
4713 };
4714 Bottleneck.prototype.redisStoreDefaults = {
4715 Promise: Promise,
4716 timeout: null,
4717 heartbeatInterval: 5000,
4718 clientOptions: {},
4719 clusterNodes: null,
4720 clearDatastore: false,
4721 connection: null
4722 };
4723 Bottleneck.prototype.instanceDefaults = {
4724 datastore: "local",
4725 connection: null,
4726 id: "<no-id>",
4727 rejectOnDrop: true,
4728 trackDoneStatus: false,
4729 Promise: Promise
4730 };
4731 Bottleneck.prototype.stopDefaults = {
4732 enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.",
4733 dropWaitingJobs: true,
4734 dropErrorMessage: "This limiter has been stopped."
4735 };
4736 return Bottleneck;
4737 }.call(commonjsGlobal);
4738
4739 var Bottleneck_1 = Bottleneck;
4740
4741 var es5 = Bottleneck_1;
4742
4743 return es5;
4744
4745})));