Bug:Fix file validation issue
[vnfsdk/refrepo.git] / vnfmarket / src / main / webapp / vnfmarket / node_modules / form-data / node_modules / async / dist / async.js
1 (function (global, factory) {
2     typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3     typeof define === 'function' && define.amd ? define(['exports'], factory) :
4     (factory((global.async = global.async || {})));
5 }(this, (function (exports) { 'use strict';
6
7 /**
8  * A faster alternative to `Function#apply`, this function invokes `func`
9  * with the `this` binding of `thisArg` and the arguments of `args`.
10  *
11  * @private
12  * @param {Function} func The function to invoke.
13  * @param {*} thisArg The `this` binding of `func`.
14  * @param {Array} args The arguments to invoke `func` with.
15  * @returns {*} Returns the result of `func`.
16  */
17 function apply(func, thisArg, args) {
18   switch (args.length) {
19     case 0: return func.call(thisArg);
20     case 1: return func.call(thisArg, args[0]);
21     case 2: return func.call(thisArg, args[0], args[1]);
22     case 3: return func.call(thisArg, args[0], args[1], args[2]);
23   }
24   return func.apply(thisArg, args);
25 }
26
27 /* Built-in method references for those with the same name as other `lodash` methods. */
28 var nativeMax = Math.max;
29
30 /**
31  * A specialized version of `baseRest` which transforms the rest array.
32  *
33  * @private
34  * @param {Function} func The function to apply a rest parameter to.
35  * @param {number} [start=func.length-1] The start position of the rest parameter.
36  * @param {Function} transform The rest array transform.
37  * @returns {Function} Returns the new function.
38  */
39 function overRest$1(func, start, transform) {
40   start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
41   return function() {
42     var args = arguments,
43         index = -1,
44         length = nativeMax(args.length - start, 0),
45         array = Array(length);
46
47     while (++index < length) {
48       array[index] = args[start + index];
49     }
50     index = -1;
51     var otherArgs = Array(start + 1);
52     while (++index < start) {
53       otherArgs[index] = args[index];
54     }
55     otherArgs[start] = transform(array);
56     return apply(func, this, otherArgs);
57   };
58 }
59
60 /**
61  * This method returns the first argument it receives.
62  *
63  * @static
64  * @since 0.1.0
65  * @memberOf _
66  * @category Util
67  * @param {*} value Any value.
68  * @returns {*} Returns `value`.
69  * @example
70  *
71  * var object = { 'a': 1 };
72  *
73  * console.log(_.identity(object) === object);
74  * // => true
75  */
76 function identity(value) {
77   return value;
78 }
79
80 // Lodash rest function without function.toString()
81 // remappings
82 function rest(func, start) {
83     return overRest$1(func, start, identity);
84 }
85
86 var initialParams = function (fn) {
87     return rest(function (args /*..., callback*/) {
88         var callback = args.pop();
89         fn.call(this, args, callback);
90     });
91 };
92
93 function applyEach$1(eachfn) {
94     return rest(function (fns, args) {
95         var go = initialParams(function (args, callback) {
96             var that = this;
97             return eachfn(fns, function (fn, cb) {
98                 fn.apply(that, args.concat(cb));
99             }, callback);
100         });
101         if (args.length) {
102             return go.apply(this, args);
103         } else {
104             return go;
105         }
106     });
107 }
108
109 /** Detect free variable `global` from Node.js. */
110 var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
111
112 /** Detect free variable `self`. */
113 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
114
115 /** Used as a reference to the global object. */
116 var root = freeGlobal || freeSelf || Function('return this')();
117
118 /** Built-in value references. */
119 var Symbol$1 = root.Symbol;
120
121 /** Used for built-in method references. */
122 var objectProto = Object.prototype;
123
124 /** Used to check objects for own properties. */
125 var hasOwnProperty = objectProto.hasOwnProperty;
126
127 /**
128  * Used to resolve the
129  * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
130  * of values.
131  */
132 var nativeObjectToString = objectProto.toString;
133
134 /** Built-in value references. */
135 var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined;
136
137 /**
138  * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
139  *
140  * @private
141  * @param {*} value The value to query.
142  * @returns {string} Returns the raw `toStringTag`.
143  */
144 function getRawTag(value) {
145   var isOwn = hasOwnProperty.call(value, symToStringTag$1),
146       tag = value[symToStringTag$1];
147
148   try {
149     value[symToStringTag$1] = undefined;
150     var unmasked = true;
151   } catch (e) {}
152
153   var result = nativeObjectToString.call(value);
154   if (unmasked) {
155     if (isOwn) {
156       value[symToStringTag$1] = tag;
157     } else {
158       delete value[symToStringTag$1];
159     }
160   }
161   return result;
162 }
163
164 /** Used for built-in method references. */
165 var objectProto$1 = Object.prototype;
166
167 /**
168  * Used to resolve the
169  * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
170  * of values.
171  */
172 var nativeObjectToString$1 = objectProto$1.toString;
173
174 /**
175  * Converts `value` to a string using `Object.prototype.toString`.
176  *
177  * @private
178  * @param {*} value The value to convert.
179  * @returns {string} Returns the converted string.
180  */
181 function objectToString(value) {
182   return nativeObjectToString$1.call(value);
183 }
184
185 /** `Object#toString` result references. */
186 var nullTag = '[object Null]';
187 var undefinedTag = '[object Undefined]';
188
189 /** Built-in value references. */
190 var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;
191
192 /**
193  * The base implementation of `getTag` without fallbacks for buggy environments.
194  *
195  * @private
196  * @param {*} value The value to query.
197  * @returns {string} Returns the `toStringTag`.
198  */
199 function baseGetTag(value) {
200   if (value == null) {
201     return value === undefined ? undefinedTag : nullTag;
202   }
203   return (symToStringTag && symToStringTag in Object(value))
204     ? getRawTag(value)
205     : objectToString(value);
206 }
207
208 /**
209  * Checks if `value` is the
210  * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
211  * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
212  *
213  * @static
214  * @memberOf _
215  * @since 0.1.0
216  * @category Lang
217  * @param {*} value The value to check.
218  * @returns {boolean} Returns `true` if `value` is an object, else `false`.
219  * @example
220  *
221  * _.isObject({});
222  * // => true
223  *
224  * _.isObject([1, 2, 3]);
225  * // => true
226  *
227  * _.isObject(_.noop);
228  * // => true
229  *
230  * _.isObject(null);
231  * // => false
232  */
233 function isObject(value) {
234   var type = typeof value;
235   return value != null && (type == 'object' || type == 'function');
236 }
237
238 /** `Object#toString` result references. */
239 var asyncTag = '[object AsyncFunction]';
240 var funcTag = '[object Function]';
241 var genTag = '[object GeneratorFunction]';
242 var proxyTag = '[object Proxy]';
243
244 /**
245  * Checks if `value` is classified as a `Function` object.
246  *
247  * @static
248  * @memberOf _
249  * @since 0.1.0
250  * @category Lang
251  * @param {*} value The value to check.
252  * @returns {boolean} Returns `true` if `value` is a function, else `false`.
253  * @example
254  *
255  * _.isFunction(_);
256  * // => true
257  *
258  * _.isFunction(/abc/);
259  * // => false
260  */
261 function isFunction(value) {
262   if (!isObject(value)) {
263     return false;
264   }
265   // The use of `Object#toString` avoids issues with the `typeof` operator
266   // in Safari 9 which returns 'object' for typed arrays and other constructors.
267   var tag = baseGetTag(value);
268   return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
269 }
270
271 /** Used as references for various `Number` constants. */
272 var MAX_SAFE_INTEGER = 9007199254740991;
273
274 /**
275  * Checks if `value` is a valid array-like length.
276  *
277  * **Note:** This method is loosely based on
278  * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
279  *
280  * @static
281  * @memberOf _
282  * @since 4.0.0
283  * @category Lang
284  * @param {*} value The value to check.
285  * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
286  * @example
287  *
288  * _.isLength(3);
289  * // => true
290  *
291  * _.isLength(Number.MIN_VALUE);
292  * // => false
293  *
294  * _.isLength(Infinity);
295  * // => false
296  *
297  * _.isLength('3');
298  * // => false
299  */
300 function isLength(value) {
301   return typeof value == 'number' &&
302     value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
303 }
304
305 /**
306  * Checks if `value` is array-like. A value is considered array-like if it's
307  * not a function and has a `value.length` that's an integer greater than or
308  * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
309  *
310  * @static
311  * @memberOf _
312  * @since 4.0.0
313  * @category Lang
314  * @param {*} value The value to check.
315  * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
316  * @example
317  *
318  * _.isArrayLike([1, 2, 3]);
319  * // => true
320  *
321  * _.isArrayLike(document.body.children);
322  * // => true
323  *
324  * _.isArrayLike('abc');
325  * // => true
326  *
327  * _.isArrayLike(_.noop);
328  * // => false
329  */
330 function isArrayLike(value) {
331   return value != null && isLength(value.length) && !isFunction(value);
332 }
333
334 // A temporary value used to identify if the loop should be broken.
335 // See #1064, #1293
336 var breakLoop = {};
337
338 /**
339  * This method returns `undefined`.
340  *
341  * @static
342  * @memberOf _
343  * @since 2.3.0
344  * @category Util
345  * @example
346  *
347  * _.times(2, _.noop);
348  * // => [undefined, undefined]
349  */
350 function noop() {
351   // No operation performed.
352 }
353
354 function once(fn) {
355     return function () {
356         if (fn === null) return;
357         var callFn = fn;
358         fn = null;
359         callFn.apply(this, arguments);
360     };
361 }
362
363 var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator;
364
365 var getIterator = function (coll) {
366     return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol]();
367 };
368
369 /**
370  * The base implementation of `_.times` without support for iteratee shorthands
371  * or max array length checks.
372  *
373  * @private
374  * @param {number} n The number of times to invoke `iteratee`.
375  * @param {Function} iteratee The function invoked per iteration.
376  * @returns {Array} Returns the array of results.
377  */
378 function baseTimes(n, iteratee) {
379   var index = -1,
380       result = Array(n);
381
382   while (++index < n) {
383     result[index] = iteratee(index);
384   }
385   return result;
386 }
387
388 /**
389  * Checks if `value` is object-like. A value is object-like if it's not `null`
390  * and has a `typeof` result of "object".
391  *
392  * @static
393  * @memberOf _
394  * @since 4.0.0
395  * @category Lang
396  * @param {*} value The value to check.
397  * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
398  * @example
399  *
400  * _.isObjectLike({});
401  * // => true
402  *
403  * _.isObjectLike([1, 2, 3]);
404  * // => true
405  *
406  * _.isObjectLike(_.noop);
407  * // => false
408  *
409  * _.isObjectLike(null);
410  * // => false
411  */
412 function isObjectLike(value) {
413   return value != null && typeof value == 'object';
414 }
415
416 /** `Object#toString` result references. */
417 var argsTag = '[object Arguments]';
418
419 /**
420  * The base implementation of `_.isArguments`.
421  *
422  * @private
423  * @param {*} value The value to check.
424  * @returns {boolean} Returns `true` if `value` is an `arguments` object,
425  */
426 function baseIsArguments(value) {
427   return isObjectLike(value) && baseGetTag(value) == argsTag;
428 }
429
430 /** Used for built-in method references. */
431 var objectProto$3 = Object.prototype;
432
433 /** Used to check objects for own properties. */
434 var hasOwnProperty$2 = objectProto$3.hasOwnProperty;
435
436 /** Built-in value references. */
437 var propertyIsEnumerable = objectProto$3.propertyIsEnumerable;
438
439 /**
440  * Checks if `value` is likely an `arguments` object.
441  *
442  * @static
443  * @memberOf _
444  * @since 0.1.0
445  * @category Lang
446  * @param {*} value The value to check.
447  * @returns {boolean} Returns `true` if `value` is an `arguments` object,
448  *  else `false`.
449  * @example
450  *
451  * _.isArguments(function() { return arguments; }());
452  * // => true
453  *
454  * _.isArguments([1, 2, 3]);
455  * // => false
456  */
457 var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
458   return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') &&
459     !propertyIsEnumerable.call(value, 'callee');
460 };
461
462 /**
463  * Checks if `value` is classified as an `Array` object.
464  *
465  * @static
466  * @memberOf _
467  * @since 0.1.0
468  * @category Lang
469  * @param {*} value The value to check.
470  * @returns {boolean} Returns `true` if `value` is an array, else `false`.
471  * @example
472  *
473  * _.isArray([1, 2, 3]);
474  * // => true
475  *
476  * _.isArray(document.body.children);
477  * // => false
478  *
479  * _.isArray('abc');
480  * // => false
481  *
482  * _.isArray(_.noop);
483  * // => false
484  */
485 var isArray = Array.isArray;
486
487 /**
488  * This method returns `false`.
489  *
490  * @static
491  * @memberOf _
492  * @since 4.13.0
493  * @category Util
494  * @returns {boolean} Returns `false`.
495  * @example
496  *
497  * _.times(2, _.stubFalse);
498  * // => [false, false]
499  */
500 function stubFalse() {
501   return false;
502 }
503
504 /** Detect free variable `exports`. */
505 var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
506
507 /** Detect free variable `module`. */
508 var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
509
510 /** Detect the popular CommonJS extension `module.exports`. */
511 var moduleExports = freeModule && freeModule.exports === freeExports;
512
513 /** Built-in value references. */
514 var Buffer = moduleExports ? root.Buffer : undefined;
515
516 /* Built-in method references for those with the same name as other `lodash` methods. */
517 var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
518
519 /**
520  * Checks if `value` is a buffer.
521  *
522  * @static
523  * @memberOf _
524  * @since 4.3.0
525  * @category Lang
526  * @param {*} value The value to check.
527  * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
528  * @example
529  *
530  * _.isBuffer(new Buffer(2));
531  * // => true
532  *
533  * _.isBuffer(new Uint8Array(2));
534  * // => false
535  */
536 var isBuffer = nativeIsBuffer || stubFalse;
537
538 /** Used as references for various `Number` constants. */
539 var MAX_SAFE_INTEGER$1 = 9007199254740991;
540
541 /** Used to detect unsigned integer values. */
542 var reIsUint = /^(?:0|[1-9]\d*)$/;
543
544 /**
545  * Checks if `value` is a valid array-like index.
546  *
547  * @private
548  * @param {*} value The value to check.
549  * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
550  * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
551  */
552 function isIndex(value, length) {
553   length = length == null ? MAX_SAFE_INTEGER$1 : length;
554   return !!length &&
555     (typeof value == 'number' || reIsUint.test(value)) &&
556     (value > -1 && value % 1 == 0 && value < length);
557 }
558
559 /** `Object#toString` result references. */
560 var argsTag$1 = '[object Arguments]';
561 var arrayTag = '[object Array]';
562 var boolTag = '[object Boolean]';
563 var dateTag = '[object Date]';
564 var errorTag = '[object Error]';
565 var funcTag$1 = '[object Function]';
566 var mapTag = '[object Map]';
567 var numberTag = '[object Number]';
568 var objectTag = '[object Object]';
569 var regexpTag = '[object RegExp]';
570 var setTag = '[object Set]';
571 var stringTag = '[object String]';
572 var weakMapTag = '[object WeakMap]';
573
574 var arrayBufferTag = '[object ArrayBuffer]';
575 var dataViewTag = '[object DataView]';
576 var float32Tag = '[object Float32Array]';
577 var float64Tag = '[object Float64Array]';
578 var int8Tag = '[object Int8Array]';
579 var int16Tag = '[object Int16Array]';
580 var int32Tag = '[object Int32Array]';
581 var uint8Tag = '[object Uint8Array]';
582 var uint8ClampedTag = '[object Uint8ClampedArray]';
583 var uint16Tag = '[object Uint16Array]';
584 var uint32Tag = '[object Uint32Array]';
585
586 /** Used to identify `toStringTag` values of typed arrays. */
587 var typedArrayTags = {};
588 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
589 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
590 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
591 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
592 typedArrayTags[uint32Tag] = true;
593 typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =
594 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
595 typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
596 typedArrayTags[errorTag] = typedArrayTags[funcTag$1] =
597 typedArrayTags[mapTag] = typedArrayTags[numberTag] =
598 typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
599 typedArrayTags[setTag] = typedArrayTags[stringTag] =
600 typedArrayTags[weakMapTag] = false;
601
602 /**
603  * The base implementation of `_.isTypedArray` without Node.js optimizations.
604  *
605  * @private
606  * @param {*} value The value to check.
607  * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
608  */
609 function baseIsTypedArray(value) {
610   return isObjectLike(value) &&
611     isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
612 }
613
614 /**
615  * The base implementation of `_.unary` without support for storing metadata.
616  *
617  * @private
618  * @param {Function} func The function to cap arguments for.
619  * @returns {Function} Returns the new capped function.
620  */
621 function baseUnary(func) {
622   return function(value) {
623     return func(value);
624   };
625 }
626
627 /** Detect free variable `exports`. */
628 var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports;
629
630 /** Detect free variable `module`. */
631 var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module;
632
633 /** Detect the popular CommonJS extension `module.exports`. */
634 var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;
635
636 /** Detect free variable `process` from Node.js. */
637 var freeProcess = moduleExports$1 && freeGlobal.process;
638
639 /** Used to access faster Node.js helpers. */
640 var nodeUtil = (function() {
641   try {
642     return freeProcess && freeProcess.binding && freeProcess.binding('util');
643   } catch (e) {}
644 }());
645
646 /* Node.js helper references. */
647 var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
648
649 /**
650  * Checks if `value` is classified as a typed array.
651  *
652  * @static
653  * @memberOf _
654  * @since 3.0.0
655  * @category Lang
656  * @param {*} value The value to check.
657  * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
658  * @example
659  *
660  * _.isTypedArray(new Uint8Array);
661  * // => true
662  *
663  * _.isTypedArray([]);
664  * // => false
665  */
666 var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
667
668 /** Used for built-in method references. */
669 var objectProto$2 = Object.prototype;
670
671 /** Used to check objects for own properties. */
672 var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
673
674 /**
675  * Creates an array of the enumerable property names of the array-like `value`.
676  *
677  * @private
678  * @param {*} value The value to query.
679  * @param {boolean} inherited Specify returning inherited property names.
680  * @returns {Array} Returns the array of property names.
681  */
682 function arrayLikeKeys(value, inherited) {
683   var isArr = isArray(value),
684       isArg = !isArr && isArguments(value),
685       isBuff = !isArr && !isArg && isBuffer(value),
686       isType = !isArr && !isArg && !isBuff && isTypedArray(value),
687       skipIndexes = isArr || isArg || isBuff || isType,
688       result = skipIndexes ? baseTimes(value.length, String) : [],
689       length = result.length;
690
691   for (var key in value) {
692     if ((inherited || hasOwnProperty$1.call(value, key)) &&
693         !(skipIndexes && (
694            // Safari 9 has enumerable `arguments.length` in strict mode.
695            key == 'length' ||
696            // Node.js 0.10 has enumerable non-index properties on buffers.
697            (isBuff && (key == 'offset' || key == 'parent')) ||
698            // PhantomJS 2 has enumerable non-index properties on typed arrays.
699            (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
700            // Skip index properties.
701            isIndex(key, length)
702         ))) {
703       result.push(key);
704     }
705   }
706   return result;
707 }
708
709 /** Used for built-in method references. */
710 var objectProto$5 = Object.prototype;
711
712 /**
713  * Checks if `value` is likely a prototype object.
714  *
715  * @private
716  * @param {*} value The value to check.
717  * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
718  */
719 function isPrototype(value) {
720   var Ctor = value && value.constructor,
721       proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5;
722
723   return value === proto;
724 }
725
726 /**
727  * Creates a unary function that invokes `func` with its argument transformed.
728  *
729  * @private
730  * @param {Function} func The function to wrap.
731  * @param {Function} transform The argument transform.
732  * @returns {Function} Returns the new function.
733  */
734 function overArg(func, transform) {
735   return function(arg) {
736     return func(transform(arg));
737   };
738 }
739
740 /* Built-in method references for those with the same name as other `lodash` methods. */
741 var nativeKeys = overArg(Object.keys, Object);
742
743 /** Used for built-in method references. */
744 var objectProto$4 = Object.prototype;
745
746 /** Used to check objects for own properties. */
747 var hasOwnProperty$3 = objectProto$4.hasOwnProperty;
748
749 /**
750  * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
751  *
752  * @private
753  * @param {Object} object The object to query.
754  * @returns {Array} Returns the array of property names.
755  */
756 function baseKeys(object) {
757   if (!isPrototype(object)) {
758     return nativeKeys(object);
759   }
760   var result = [];
761   for (var key in Object(object)) {
762     if (hasOwnProperty$3.call(object, key) && key != 'constructor') {
763       result.push(key);
764     }
765   }
766   return result;
767 }
768
769 /**
770  * Creates an array of the own enumerable property names of `object`.
771  *
772  * **Note:** Non-object values are coerced to objects. See the
773  * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
774  * for more details.
775  *
776  * @static
777  * @since 0.1.0
778  * @memberOf _
779  * @category Object
780  * @param {Object} object The object to query.
781  * @returns {Array} Returns the array of property names.
782  * @example
783  *
784  * function Foo() {
785  *   this.a = 1;
786  *   this.b = 2;
787  * }
788  *
789  * Foo.prototype.c = 3;
790  *
791  * _.keys(new Foo);
792  * // => ['a', 'b'] (iteration order is not guaranteed)
793  *
794  * _.keys('hi');
795  * // => ['0', '1']
796  */
797 function keys(object) {
798   return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
799 }
800
801 function createArrayIterator(coll) {
802     var i = -1;
803     var len = coll.length;
804     return function next() {
805         return ++i < len ? { value: coll[i], key: i } : null;
806     };
807 }
808
809 function createES2015Iterator(iterator) {
810     var i = -1;
811     return function next() {
812         var item = iterator.next();
813         if (item.done) return null;
814         i++;
815         return { value: item.value, key: i };
816     };
817 }
818
819 function createObjectIterator(obj) {
820     var okeys = keys(obj);
821     var i = -1;
822     var len = okeys.length;
823     return function next() {
824         var key = okeys[++i];
825         return i < len ? { value: obj[key], key: key } : null;
826     };
827 }
828
829 function iterator(coll) {
830     if (isArrayLike(coll)) {
831         return createArrayIterator(coll);
832     }
833
834     var iterator = getIterator(coll);
835     return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);
836 }
837
838 function onlyOnce(fn) {
839     return function () {
840         if (fn === null) throw new Error("Callback was already called.");
841         var callFn = fn;
842         fn = null;
843         callFn.apply(this, arguments);
844     };
845 }
846
847 function _eachOfLimit(limit) {
848     return function (obj, iteratee, callback) {
849         callback = once(callback || noop);
850         if (limit <= 0 || !obj) {
851             return callback(null);
852         }
853         var nextElem = iterator(obj);
854         var done = false;
855         var running = 0;
856
857         function iterateeCallback(err, value) {
858             running -= 1;
859             if (err) {
860                 done = true;
861                 callback(err);
862             } else if (value === breakLoop || done && running <= 0) {
863                 done = true;
864                 return callback(null);
865             } else {
866                 replenish();
867             }
868         }
869
870         function replenish() {
871             while (running < limit && !done) {
872                 var elem = nextElem();
873                 if (elem === null) {
874                     done = true;
875                     if (running <= 0) {
876                         callback(null);
877                     }
878                     return;
879                 }
880                 running += 1;
881                 iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));
882             }
883         }
884
885         replenish();
886     };
887 }
888
889 /**
890  * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a
891  * time.
892  *
893  * @name eachOfLimit
894  * @static
895  * @memberOf module:Collections
896  * @method
897  * @see [async.eachOf]{@link module:Collections.eachOf}
898  * @alias forEachOfLimit
899  * @category Collection
900  * @param {Array|Iterable|Object} coll - A collection to iterate over.
901  * @param {number} limit - The maximum number of async operations at a time.
902  * @param {Function} iteratee - A function to apply to each
903  * item in `coll`. The `key` is the item's key, or index in the case of an
904  * array. The iteratee is passed a `callback(err)` which must be called once it
905  * has completed. If no error has occurred, the callback should be run without
906  * arguments or with an explicit `null` argument. Invoked with
907  * (item, key, callback).
908  * @param {Function} [callback] - A callback which is called when all
909  * `iteratee` functions have finished, or an error occurs. Invoked with (err).
910  */
911 function eachOfLimit(coll, limit, iteratee, callback) {
912   _eachOfLimit(limit)(coll, iteratee, callback);
913 }
914
915 function doLimit(fn, limit) {
916     return function (iterable, iteratee, callback) {
917         return fn(iterable, limit, iteratee, callback);
918     };
919 }
920
921 // eachOf implementation optimized for array-likes
922 function eachOfArrayLike(coll, iteratee, callback) {
923     callback = once(callback || noop);
924     var index = 0,
925         completed = 0,
926         length = coll.length;
927     if (length === 0) {
928         callback(null);
929     }
930
931     function iteratorCallback(err, value) {
932         if (err) {
933             callback(err);
934         } else if (++completed === length || value === breakLoop) {
935             callback(null);
936         }
937     }
938
939     for (; index < length; index++) {
940         iteratee(coll[index], index, onlyOnce(iteratorCallback));
941     }
942 }
943
944 // a generic version of eachOf which can handle array, object, and iterator cases.
945 var eachOfGeneric = doLimit(eachOfLimit, Infinity);
946
947 /**
948  * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument
949  * to the iteratee.
950  *
951  * @name eachOf
952  * @static
953  * @memberOf module:Collections
954  * @method
955  * @alias forEachOf
956  * @category Collection
957  * @see [async.each]{@link module:Collections.each}
958  * @param {Array|Iterable|Object} coll - A collection to iterate over.
959  * @param {Function} iteratee - A function to apply to each
960  * item in `coll`. The `key` is the item's key, or index in the case of an
961  * array. The iteratee is passed a `callback(err)` which must be called once it
962  * has completed. If no error has occurred, the callback should be run without
963  * arguments or with an explicit `null` argument. Invoked with
964  * (item, key, callback).
965  * @param {Function} [callback] - A callback which is called when all
966  * `iteratee` functions have finished, or an error occurs. Invoked with (err).
967  * @example
968  *
969  * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
970  * var configs = {};
971  *
972  * async.forEachOf(obj, function (value, key, callback) {
973  *     fs.readFile(__dirname + value, "utf8", function (err, data) {
974  *         if (err) return callback(err);
975  *         try {
976  *             configs[key] = JSON.parse(data);
977  *         } catch (e) {
978  *             return callback(e);
979  *         }
980  *         callback();
981  *     });
982  * }, function (err) {
983  *     if (err) console.error(err.message);
984  *     // configs is now a map of JSON data
985  *     doSomethingWith(configs);
986  * });
987  */
988 var eachOf = function (coll, iteratee, callback) {
989     var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;
990     eachOfImplementation(coll, iteratee, callback);
991 };
992
993 function doParallel(fn) {
994     return function (obj, iteratee, callback) {
995         return fn(eachOf, obj, iteratee, callback);
996     };
997 }
998
999 function _asyncMap(eachfn, arr, iteratee, callback) {
1000     callback = callback || noop;
1001     arr = arr || [];
1002     var results = [];
1003     var counter = 0;
1004
1005     eachfn(arr, function (value, _, callback) {
1006         var index = counter++;
1007         iteratee(value, function (err, v) {
1008             results[index] = v;
1009             callback(err);
1010         });
1011     }, function (err) {
1012         callback(err, results);
1013     });
1014 }
1015
1016 /**
1017  * Produces a new collection of values by mapping each value in `coll` through
1018  * the `iteratee` function. The `iteratee` is called with an item from `coll`
1019  * and a callback for when it has finished processing. Each of these callback
1020  * takes 2 arguments: an `error`, and the transformed item from `coll`. If
1021  * `iteratee` passes an error to its callback, the main `callback` (for the
1022  * `map` function) is immediately called with the error.
1023  *
1024  * Note, that since this function applies the `iteratee` to each item in
1025  * parallel, there is no guarantee that the `iteratee` functions will complete
1026  * in order. However, the results array will be in the same order as the
1027  * original `coll`.
1028  *
1029  * If `map` is passed an Object, the results will be an Array.  The results
1030  * will roughly be in the order of the original Objects' keys (but this can
1031  * vary across JavaScript engines)
1032  *
1033  * @name map
1034  * @static
1035  * @memberOf module:Collections
1036  * @method
1037  * @category Collection
1038  * @param {Array|Iterable|Object} coll - A collection to iterate over.
1039  * @param {Function} iteratee - A function to apply to each item in `coll`.
1040  * The iteratee is passed a `callback(err, transformed)` which must be called
1041  * once it has completed with an error (which can be `null`) and a
1042  * transformed item. Invoked with (item, callback).
1043  * @param {Function} [callback] - A callback which is called when all `iteratee`
1044  * functions have finished, or an error occurs. Results is an Array of the
1045  * transformed items from the `coll`. Invoked with (err, results).
1046  * @example
1047  *
1048  * async.map(['file1','file2','file3'], fs.stat, function(err, results) {
1049  *     // results is now an array of stats for each file
1050  * });
1051  */
1052 var map = doParallel(_asyncMap);
1053
1054 /**
1055  * Applies the provided arguments to each function in the array, calling
1056  * `callback` after all functions have completed. If you only provide the first
1057  * argument, `fns`, then it will return a function which lets you pass in the
1058  * arguments as if it were a single function call. If more arguments are
1059  * provided, `callback` is required while `args` is still optional.
1060  *
1061  * @name applyEach
1062  * @static
1063  * @memberOf module:ControlFlow
1064  * @method
1065  * @category Control Flow
1066  * @param {Array|Iterable|Object} fns - A collection of asynchronous functions
1067  * to all call with the same arguments
1068  * @param {...*} [args] - any number of separate arguments to pass to the
1069  * function.
1070  * @param {Function} [callback] - the final argument should be the callback,
1071  * called when all functions have completed processing.
1072  * @returns {Function} - If only the first argument, `fns`, is provided, it will
1073  * return a function which lets you pass in the arguments as if it were a single
1074  * function call. The signature is `(..args, callback)`. If invoked with any
1075  * arguments, `callback` is required.
1076  * @example
1077  *
1078  * async.applyEach([enableSearch, updateSchema], 'bucket', callback);
1079  *
1080  * // partial application example:
1081  * async.each(
1082  *     buckets,
1083  *     async.applyEach([enableSearch, updateSchema]),
1084  *     callback
1085  * );
1086  */
1087 var applyEach = applyEach$1(map);
1088
1089 function doParallelLimit(fn) {
1090     return function (obj, limit, iteratee, callback) {
1091         return fn(_eachOfLimit(limit), obj, iteratee, callback);
1092     };
1093 }
1094
1095 /**
1096  * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.
1097  *
1098  * @name mapLimit
1099  * @static
1100  * @memberOf module:Collections
1101  * @method
1102  * @see [async.map]{@link module:Collections.map}
1103  * @category Collection
1104  * @param {Array|Iterable|Object} coll - A collection to iterate over.
1105  * @param {number} limit - The maximum number of async operations at a time.
1106  * @param {Function} iteratee - A function to apply to each item in `coll`.
1107  * The iteratee is passed a `callback(err, transformed)` which must be called
1108  * once it has completed with an error (which can be `null`) and a transformed
1109  * item. Invoked with (item, callback).
1110  * @param {Function} [callback] - A callback which is called when all `iteratee`
1111  * functions have finished, or an error occurs. Results is an array of the
1112  * transformed items from the `coll`. Invoked with (err, results).
1113  */
1114 var mapLimit = doParallelLimit(_asyncMap);
1115
1116 /**
1117  * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.
1118  *
1119  * @name mapSeries
1120  * @static
1121  * @memberOf module:Collections
1122  * @method
1123  * @see [async.map]{@link module:Collections.map}
1124  * @category Collection
1125  * @param {Array|Iterable|Object} coll - A collection to iterate over.
1126  * @param {Function} iteratee - A function to apply to each item in `coll`.
1127  * The iteratee is passed a `callback(err, transformed)` which must be called
1128  * once it has completed with an error (which can be `null`) and a
1129  * transformed item. Invoked with (item, callback).
1130  * @param {Function} [callback] - A callback which is called when all `iteratee`
1131  * functions have finished, or an error occurs. Results is an array of the
1132  * transformed items from the `coll`. Invoked with (err, results).
1133  */
1134 var mapSeries = doLimit(mapLimit, 1);
1135
1136 /**
1137  * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.
1138  *
1139  * @name applyEachSeries
1140  * @static
1141  * @memberOf module:ControlFlow
1142  * @method
1143  * @see [async.applyEach]{@link module:ControlFlow.applyEach}
1144  * @category Control Flow
1145  * @param {Array|Iterable|Object} fns - A collection of asynchronous functions to all
1146  * call with the same arguments
1147  * @param {...*} [args] - any number of separate arguments to pass to the
1148  * function.
1149  * @param {Function} [callback] - the final argument should be the callback,
1150  * called when all functions have completed processing.
1151  * @returns {Function} - If only the first argument is provided, it will return
1152  * a function which lets you pass in the arguments as if it were a single
1153  * function call.
1154  */
1155 var applyEachSeries = applyEach$1(mapSeries);
1156
1157 /**
1158  * Creates a continuation function with some arguments already applied.
1159  *
1160  * Useful as a shorthand when combined with other control flow functions. Any
1161  * arguments passed to the returned function are added to the arguments
1162  * originally passed to apply.
1163  *
1164  * @name apply
1165  * @static
1166  * @memberOf module:Utils
1167  * @method
1168  * @category Util
1169  * @param {Function} function - The function you want to eventually apply all
1170  * arguments to. Invokes with (arguments...).
1171  * @param {...*} arguments... - Any number of arguments to automatically apply
1172  * when the continuation is called.
1173  * @example
1174  *
1175  * // using apply
1176  * async.parallel([
1177  *     async.apply(fs.writeFile, 'testfile1', 'test1'),
1178  *     async.apply(fs.writeFile, 'testfile2', 'test2')
1179  * ]);
1180  *
1181  *
1182  * // the same process without using apply
1183  * async.parallel([
1184  *     function(callback) {
1185  *         fs.writeFile('testfile1', 'test1', callback);
1186  *     },
1187  *     function(callback) {
1188  *         fs.writeFile('testfile2', 'test2', callback);
1189  *     }
1190  * ]);
1191  *
1192  * // It's possible to pass any number of additional arguments when calling the
1193  * // continuation:
1194  *
1195  * node> var fn = async.apply(sys.puts, 'one');
1196  * node> fn('two', 'three');
1197  * one
1198  * two
1199  * three
1200  */
1201 var apply$2 = rest(function (fn, args) {
1202     return rest(function (callArgs) {
1203         return fn.apply(null, args.concat(callArgs));
1204     });
1205 });
1206
1207 /**
1208  * Take a sync function and make it async, passing its return value to a
1209  * callback. This is useful for plugging sync functions into a waterfall,
1210  * series, or other async functions. Any arguments passed to the generated
1211  * function will be passed to the wrapped function (except for the final
1212  * callback argument). Errors thrown will be passed to the callback.
1213  *
1214  * If the function passed to `asyncify` returns a Promise, that promises's
1215  * resolved/rejected state will be used to call the callback, rather than simply
1216  * the synchronous return value.
1217  *
1218  * This also means you can asyncify ES2016 `async` functions.
1219  *
1220  * @name asyncify
1221  * @static
1222  * @memberOf module:Utils
1223  * @method
1224  * @alias wrapSync
1225  * @category Util
1226  * @param {Function} func - The synchronous function to convert to an
1227  * asynchronous function.
1228  * @returns {Function} An asynchronous wrapper of the `func`. To be invoked with
1229  * (callback).
1230  * @example
1231  *
1232  * // passing a regular synchronous function
1233  * async.waterfall([
1234  *     async.apply(fs.readFile, filename, "utf8"),
1235  *     async.asyncify(JSON.parse),
1236  *     function (data, next) {
1237  *         // data is the result of parsing the text.
1238  *         // If there was a parsing error, it would have been caught.
1239  *     }
1240  * ], callback);
1241  *
1242  * // passing a function returning a promise
1243  * async.waterfall([
1244  *     async.apply(fs.readFile, filename, "utf8"),
1245  *     async.asyncify(function (contents) {
1246  *         return db.model.create(contents);
1247  *     }),
1248  *     function (model, next) {
1249  *         // `model` is the instantiated model object.
1250  *         // If there was an error, this function would be skipped.
1251  *     }
1252  * ], callback);
1253  *
1254  * // es6 example
1255  * var q = async.queue(async.asyncify(async function(file) {
1256  *     var intermediateStep = await processFile(file);
1257  *     return await somePromise(intermediateStep)
1258  * }));
1259  *
1260  * q.push(files);
1261  */
1262 function asyncify(func) {
1263     return initialParams(function (args, callback) {
1264         var result;
1265         try {
1266             result = func.apply(this, args);
1267         } catch (e) {
1268             return callback(e);
1269         }
1270         // if result is Promise object
1271         if (isObject(result) && typeof result.then === 'function') {
1272             result.then(function (value) {
1273                 callback(null, value);
1274             }, function (err) {
1275                 callback(err.message ? err : new Error(err));
1276             });
1277         } else {
1278             callback(null, result);
1279         }
1280     });
1281 }
1282
1283 /**
1284  * A specialized version of `_.forEach` for arrays without support for
1285  * iteratee shorthands.
1286  *
1287  * @private
1288  * @param {Array} [array] The array to iterate over.
1289  * @param {Function} iteratee The function invoked per iteration.
1290  * @returns {Array} Returns `array`.
1291  */
1292 function arrayEach(array, iteratee) {
1293   var index = -1,
1294       length = array == null ? 0 : array.length;
1295
1296   while (++index < length) {
1297     if (iteratee(array[index], index, array) === false) {
1298       break;
1299     }
1300   }
1301   return array;
1302 }
1303
1304 /**
1305  * Creates a base function for methods like `_.forIn` and `_.forOwn`.
1306  *
1307  * @private
1308  * @param {boolean} [fromRight] Specify iterating from right to left.
1309  * @returns {Function} Returns the new base function.
1310  */
1311 function createBaseFor(fromRight) {
1312   return function(object, iteratee, keysFunc) {
1313     var index = -1,
1314         iterable = Object(object),
1315         props = keysFunc(object),
1316         length = props.length;
1317
1318     while (length--) {
1319       var key = props[fromRight ? length : ++index];
1320       if (iteratee(iterable[key], key, iterable) === false) {
1321         break;
1322       }
1323     }
1324     return object;
1325   };
1326 }
1327
1328 /**
1329  * The base implementation of `baseForOwn` which iterates over `object`
1330  * properties returned by `keysFunc` and invokes `iteratee` for each property.
1331  * Iteratee functions may exit iteration early by explicitly returning `false`.
1332  *
1333  * @private
1334  * @param {Object} object The object to iterate over.
1335  * @param {Function} iteratee The function invoked per iteration.
1336  * @param {Function} keysFunc The function to get the keys of `object`.
1337  * @returns {Object} Returns `object`.
1338  */
1339 var baseFor = createBaseFor();
1340
1341 /**
1342  * The base implementation of `_.forOwn` without support for iteratee shorthands.
1343  *
1344  * @private
1345  * @param {Object} object The object to iterate over.
1346  * @param {Function} iteratee The function invoked per iteration.
1347  * @returns {Object} Returns `object`.
1348  */
1349 function baseForOwn(object, iteratee) {
1350   return object && baseFor(object, iteratee, keys);
1351 }
1352
1353 /**
1354  * The base implementation of `_.findIndex` and `_.findLastIndex` without
1355  * support for iteratee shorthands.
1356  *
1357  * @private
1358  * @param {Array} array The array to inspect.
1359  * @param {Function} predicate The function invoked per iteration.
1360  * @param {number} fromIndex The index to search from.
1361  * @param {boolean} [fromRight] Specify iterating from right to left.
1362  * @returns {number} Returns the index of the matched value, else `-1`.
1363  */
1364 function baseFindIndex(array, predicate, fromIndex, fromRight) {
1365   var length = array.length,
1366       index = fromIndex + (fromRight ? 1 : -1);
1367
1368   while ((fromRight ? index-- : ++index < length)) {
1369     if (predicate(array[index], index, array)) {
1370       return index;
1371     }
1372   }
1373   return -1;
1374 }
1375
1376 /**
1377  * The base implementation of `_.isNaN` without support for number objects.
1378  *
1379  * @private
1380  * @param {*} value The value to check.
1381  * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
1382  */
1383 function baseIsNaN(value) {
1384   return value !== value;
1385 }
1386
1387 /**
1388  * A specialized version of `_.indexOf` which performs strict equality
1389  * comparisons of values, i.e. `===`.
1390  *
1391  * @private
1392  * @param {Array} array The array to inspect.
1393  * @param {*} value The value to search for.
1394  * @param {number} fromIndex The index to search from.
1395  * @returns {number} Returns the index of the matched value, else `-1`.
1396  */
1397 function strictIndexOf(array, value, fromIndex) {
1398   var index = fromIndex - 1,
1399       length = array.length;
1400
1401   while (++index < length) {
1402     if (array[index] === value) {
1403       return index;
1404     }
1405   }
1406   return -1;
1407 }
1408
1409 /**
1410  * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
1411  *
1412  * @private
1413  * @param {Array} array The array to inspect.
1414  * @param {*} value The value to search for.
1415  * @param {number} fromIndex The index to search from.
1416  * @returns {number} Returns the index of the matched value, else `-1`.
1417  */
1418 function baseIndexOf(array, value, fromIndex) {
1419   return value === value
1420     ? strictIndexOf(array, value, fromIndex)
1421     : baseFindIndex(array, baseIsNaN, fromIndex);
1422 }
1423
1424 /**
1425  * Determines the best order for running the functions in `tasks`, based on
1426  * their requirements. Each function can optionally depend on other functions
1427  * being completed first, and each function is run as soon as its requirements
1428  * are satisfied.
1429  *
1430  * If any of the functions pass an error to their callback, the `auto` sequence
1431  * will stop. Further tasks will not execute (so any other functions depending
1432  * on it will not run), and the main `callback` is immediately called with the
1433  * error.
1434  *
1435  * Functions also receive an object containing the results of functions which
1436  * have completed so far as the first argument, if they have dependencies. If a
1437  * task function has no dependencies, it will only be passed a callback.
1438  *
1439  * @name auto
1440  * @static
1441  * @memberOf module:ControlFlow
1442  * @method
1443  * @category Control Flow
1444  * @param {Object} tasks - An object. Each of its properties is either a
1445  * function or an array of requirements, with the function itself the last item
1446  * in the array. The object's key of a property serves as the name of the task
1447  * defined by that property, i.e. can be used when specifying requirements for
1448  * other tasks. The function receives one or two arguments:
1449  * * a `results` object, containing the results of the previously executed
1450  *   functions, only passed if the task has any dependencies,
1451  * * a `callback(err, result)` function, which must be called when finished,
1452  *   passing an `error` (which can be `null`) and the result of the function's
1453  *   execution.
1454  * @param {number} [concurrency=Infinity] - An optional `integer` for
1455  * determining the maximum number of tasks that can be run in parallel. By
1456  * default, as many as possible.
1457  * @param {Function} [callback] - An optional callback which is called when all
1458  * the tasks have been completed. It receives the `err` argument if any `tasks`
1459  * pass an error to their callback. Results are always returned; however, if an
1460  * error occurs, no further `tasks` will be performed, and the results object
1461  * will only contain partial results. Invoked with (err, results).
1462  * @returns undefined
1463  * @example
1464  *
1465  * async.auto({
1466  *     // this function will just be passed a callback
1467  *     readData: async.apply(fs.readFile, 'data.txt', 'utf-8'),
1468  *     showData: ['readData', function(results, cb) {
1469  *         // results.readData is the file's contents
1470  *         // ...
1471  *     }]
1472  * }, callback);
1473  *
1474  * async.auto({
1475  *     get_data: function(callback) {
1476  *         console.log('in get_data');
1477  *         // async code to get some data
1478  *         callback(null, 'data', 'converted to array');
1479  *     },
1480  *     make_folder: function(callback) {
1481  *         console.log('in make_folder');
1482  *         // async code to create a directory to store a file in
1483  *         // this is run at the same time as getting the data
1484  *         callback(null, 'folder');
1485  *     },
1486  *     write_file: ['get_data', 'make_folder', function(results, callback) {
1487  *         console.log('in write_file', JSON.stringify(results));
1488  *         // once there is some data and the directory exists,
1489  *         // write the data to a file in the directory
1490  *         callback(null, 'filename');
1491  *     }],
1492  *     email_link: ['write_file', function(results, callback) {
1493  *         console.log('in email_link', JSON.stringify(results));
1494  *         // once the file is written let's email a link to it...
1495  *         // results.write_file contains the filename returned by write_file.
1496  *         callback(null, {'file':results.write_file, 'email':'user@example.com'});
1497  *     }]
1498  * }, function(err, results) {
1499  *     console.log('err = ', err);
1500  *     console.log('results = ', results);
1501  * });
1502  */
1503 var auto = function (tasks, concurrency, callback) {
1504     if (typeof concurrency === 'function') {
1505         // concurrency is optional, shift the args.
1506         callback = concurrency;
1507         concurrency = null;
1508     }
1509     callback = once(callback || noop);
1510     var keys$$1 = keys(tasks);
1511     var numTasks = keys$$1.length;
1512     if (!numTasks) {
1513         return callback(null);
1514     }
1515     if (!concurrency) {
1516         concurrency = numTasks;
1517     }
1518
1519     var results = {};
1520     var runningTasks = 0;
1521     var hasError = false;
1522
1523     var listeners = Object.create(null);
1524
1525     var readyTasks = [];
1526
1527     // for cycle detection:
1528     var readyToCheck = []; // tasks that have been identified as reachable
1529     // without the possibility of returning to an ancestor task
1530     var uncheckedDependencies = {};
1531
1532     baseForOwn(tasks, function (task, key) {
1533         if (!isArray(task)) {
1534             // no dependencies
1535             enqueueTask(key, [task]);
1536             readyToCheck.push(key);
1537             return;
1538         }
1539
1540         var dependencies = task.slice(0, task.length - 1);
1541         var remainingDependencies = dependencies.length;
1542         if (remainingDependencies === 0) {
1543             enqueueTask(key, task);
1544             readyToCheck.push(key);
1545             return;
1546         }
1547         uncheckedDependencies[key] = remainingDependencies;
1548
1549         arrayEach(dependencies, function (dependencyName) {
1550             if (!tasks[dependencyName]) {
1551                 throw new Error('async.auto task `' + key + '` has a non-existent dependency `' + dependencyName + '` in ' + dependencies.join(', '));
1552             }
1553             addListener(dependencyName, function () {
1554                 remainingDependencies--;
1555                 if (remainingDependencies === 0) {
1556                     enqueueTask(key, task);
1557                 }
1558             });
1559         });
1560     });
1561
1562     checkForDeadlocks();
1563     processQueue();
1564
1565     function enqueueTask(key, task) {
1566         readyTasks.push(function () {
1567             runTask(key, task);
1568         });
1569     }
1570
1571     function processQueue() {
1572         if (readyTasks.length === 0 && runningTasks === 0) {
1573             return callback(null, results);
1574         }
1575         while (readyTasks.length && runningTasks < concurrency) {
1576             var run = readyTasks.shift();
1577             run();
1578         }
1579     }
1580
1581     function addListener(taskName, fn) {
1582         var taskListeners = listeners[taskName];
1583         if (!taskListeners) {
1584             taskListeners = listeners[taskName] = [];
1585         }
1586
1587         taskListeners.push(fn);
1588     }
1589
1590     function taskComplete(taskName) {
1591         var taskListeners = listeners[taskName] || [];
1592         arrayEach(taskListeners, function (fn) {
1593             fn();
1594         });
1595         processQueue();
1596     }
1597
1598     function runTask(key, task) {
1599         if (hasError) return;
1600
1601         var taskCallback = onlyOnce(rest(function (err, args) {
1602             runningTasks--;
1603             if (args.length <= 1) {
1604                 args = args[0];
1605             }
1606             if (err) {
1607                 var safeResults = {};
1608                 baseForOwn(results, function (val, rkey) {
1609                     safeResults[rkey] = val;
1610                 });
1611                 safeResults[key] = args;
1612                 hasError = true;
1613                 listeners = Object.create(null);
1614
1615                 callback(err, safeResults);
1616             } else {
1617                 results[key] = args;
1618                 taskComplete(key);
1619             }
1620         }));
1621
1622         runningTasks++;
1623         var taskFn = task[task.length - 1];
1624         if (task.length > 1) {
1625             taskFn(results, taskCallback);
1626         } else {
1627             taskFn(taskCallback);
1628         }
1629     }
1630
1631     function checkForDeadlocks() {
1632         // Kahn's algorithm
1633         // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm
1634         // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html
1635         var currentTask;
1636         var counter = 0;
1637         while (readyToCheck.length) {
1638             currentTask = readyToCheck.pop();
1639             counter++;
1640             arrayEach(getDependents(currentTask), function (dependent) {
1641                 if (--uncheckedDependencies[dependent] === 0) {
1642                     readyToCheck.push(dependent);
1643                 }
1644             });
1645         }
1646
1647         if (counter !== numTasks) {
1648             throw new Error('async.auto cannot execute tasks due to a recursive dependency');
1649         }
1650     }
1651
1652     function getDependents(taskName) {
1653         var result = [];
1654         baseForOwn(tasks, function (task, key) {
1655             if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) {
1656                 result.push(key);
1657             }
1658         });
1659         return result;
1660     }
1661 };
1662
1663 /**
1664  * A specialized version of `_.map` for arrays without support for iteratee
1665  * shorthands.
1666  *
1667  * @private
1668  * @param {Array} [array] The array to iterate over.
1669  * @param {Function} iteratee The function invoked per iteration.
1670  * @returns {Array} Returns the new mapped array.
1671  */
1672 function arrayMap(array, iteratee) {
1673   var index = -1,
1674       length = array == null ? 0 : array.length,
1675       result = Array(length);
1676
1677   while (++index < length) {
1678     result[index] = iteratee(array[index], index, array);
1679   }
1680   return result;
1681 }
1682
1683 /** `Object#toString` result references. */
1684 var symbolTag = '[object Symbol]';
1685
1686 /**
1687  * Checks if `value` is classified as a `Symbol` primitive or object.
1688  *
1689  * @static
1690  * @memberOf _
1691  * @since 4.0.0
1692  * @category Lang
1693  * @param {*} value The value to check.
1694  * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
1695  * @example
1696  *
1697  * _.isSymbol(Symbol.iterator);
1698  * // => true
1699  *
1700  * _.isSymbol('abc');
1701  * // => false
1702  */
1703 function isSymbol(value) {
1704   return typeof value == 'symbol' ||
1705     (isObjectLike(value) && baseGetTag(value) == symbolTag);
1706 }
1707
1708 /** Used as references for various `Number` constants. */
1709 var INFINITY = 1 / 0;
1710
1711 /** Used to convert symbols to primitives and strings. */
1712 var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined;
1713 var symbolToString = symbolProto ? symbolProto.toString : undefined;
1714
1715 /**
1716  * The base implementation of `_.toString` which doesn't convert nullish
1717  * values to empty strings.
1718  *
1719  * @private
1720  * @param {*} value The value to process.
1721  * @returns {string} Returns the string.
1722  */
1723 function baseToString(value) {
1724   // Exit early for strings to avoid a performance hit in some environments.
1725   if (typeof value == 'string') {
1726     return value;
1727   }
1728   if (isArray(value)) {
1729     // Recursively convert values (susceptible to call stack limits).
1730     return arrayMap(value, baseToString) + '';
1731   }
1732   if (isSymbol(value)) {
1733     return symbolToString ? symbolToString.call(value) : '';
1734   }
1735   var result = (value + '');
1736   return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
1737 }
1738
1739 /**
1740  * The base implementation of `_.slice` without an iteratee call guard.
1741  *
1742  * @private
1743  * @param {Array} array The array to slice.
1744  * @param {number} [start=0] The start position.
1745  * @param {number} [end=array.length] The end position.
1746  * @returns {Array} Returns the slice of `array`.
1747  */
1748 function baseSlice(array, start, end) {
1749   var index = -1,
1750       length = array.length;
1751
1752   if (start < 0) {
1753     start = -start > length ? 0 : (length + start);
1754   }
1755   end = end > length ? length : end;
1756   if (end < 0) {
1757     end += length;
1758   }
1759   length = start > end ? 0 : ((end - start) >>> 0);
1760   start >>>= 0;
1761
1762   var result = Array(length);
1763   while (++index < length) {
1764     result[index] = array[index + start];
1765   }
1766   return result;
1767 }
1768
1769 /**
1770  * Casts `array` to a slice if it's needed.
1771  *
1772  * @private
1773  * @param {Array} array The array to inspect.
1774  * @param {number} start The start position.
1775  * @param {number} [end=array.length] The end position.
1776  * @returns {Array} Returns the cast slice.
1777  */
1778 function castSlice(array, start, end) {
1779   var length = array.length;
1780   end = end === undefined ? length : end;
1781   return (!start && end >= length) ? array : baseSlice(array, start, end);
1782 }
1783
1784 /**
1785  * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
1786  * that is not found in the character symbols.
1787  *
1788  * @private
1789  * @param {Array} strSymbols The string symbols to inspect.
1790  * @param {Array} chrSymbols The character symbols to find.
1791  * @returns {number} Returns the index of the last unmatched string symbol.
1792  */
1793 function charsEndIndex(strSymbols, chrSymbols) {
1794   var index = strSymbols.length;
1795
1796   while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
1797   return index;
1798 }
1799
1800 /**
1801  * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
1802  * that is not found in the character symbols.
1803  *
1804  * @private
1805  * @param {Array} strSymbols The string symbols to inspect.
1806  * @param {Array} chrSymbols The character symbols to find.
1807  * @returns {number} Returns the index of the first unmatched string symbol.
1808  */
1809 function charsStartIndex(strSymbols, chrSymbols) {
1810   var index = -1,
1811       length = strSymbols.length;
1812
1813   while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
1814   return index;
1815 }
1816
1817 /**
1818  * Converts an ASCII `string` to an array.
1819  *
1820  * @private
1821  * @param {string} string The string to convert.
1822  * @returns {Array} Returns the converted array.
1823  */
1824 function asciiToArray(string) {
1825   return string.split('');
1826 }
1827
1828 /** Used to compose unicode character classes. */
1829 var rsAstralRange = '\\ud800-\\udfff';
1830 var rsComboMarksRange = '\\u0300-\\u036f';
1831 var reComboHalfMarksRange = '\\ufe20-\\ufe2f';
1832 var rsComboSymbolsRange = '\\u20d0-\\u20ff';
1833 var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange;
1834 var rsVarRange = '\\ufe0e\\ufe0f';
1835
1836 /** Used to compose unicode capture groups. */
1837 var rsZWJ = '\\u200d';
1838
1839 /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
1840 var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange  + rsComboRange + rsVarRange + ']');
1841
1842 /**
1843  * Checks if `string` contains Unicode symbols.
1844  *
1845  * @private
1846  * @param {string} string The string to inspect.
1847  * @returns {boolean} Returns `true` if a symbol is found, else `false`.
1848  */
1849 function hasUnicode(string) {
1850   return reHasUnicode.test(string);
1851 }
1852
1853 /** Used to compose unicode character classes. */
1854 var rsAstralRange$1 = '\\ud800-\\udfff';
1855 var rsComboMarksRange$1 = '\\u0300-\\u036f';
1856 var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f';
1857 var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff';
1858 var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1;
1859 var rsVarRange$1 = '\\ufe0e\\ufe0f';
1860
1861 /** Used to compose unicode capture groups. */
1862 var rsAstral = '[' + rsAstralRange$1 + ']';
1863 var rsCombo = '[' + rsComboRange$1 + ']';
1864 var rsFitz = '\\ud83c[\\udffb-\\udfff]';
1865 var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')';
1866 var rsNonAstral = '[^' + rsAstralRange$1 + ']';
1867 var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}';
1868 var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]';
1869 var rsZWJ$1 = '\\u200d';
1870
1871 /** Used to compose unicode regexes. */
1872 var reOptMod = rsModifier + '?';
1873 var rsOptVar = '[' + rsVarRange$1 + ']?';
1874 var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*';
1875 var rsSeq = rsOptVar + reOptMod + rsOptJoin;
1876 var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
1877
1878 /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
1879 var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
1880
1881 /**
1882  * Converts a Unicode `string` to an array.
1883  *
1884  * @private
1885  * @param {string} string The string to convert.
1886  * @returns {Array} Returns the converted array.
1887  */
1888 function unicodeToArray(string) {
1889   return string.match(reUnicode) || [];
1890 }
1891
1892 /**
1893  * Converts `string` to an array.
1894  *
1895  * @private
1896  * @param {string} string The string to convert.
1897  * @returns {Array} Returns the converted array.
1898  */
1899 function stringToArray(string) {
1900   return hasUnicode(string)
1901     ? unicodeToArray(string)
1902     : asciiToArray(string);
1903 }
1904
1905 /**
1906  * Converts `value` to a string. An empty string is returned for `null`
1907  * and `undefined` values. The sign of `-0` is preserved.
1908  *
1909  * @static
1910  * @memberOf _
1911  * @since 4.0.0
1912  * @category Lang
1913  * @param {*} value The value to convert.
1914  * @returns {string} Returns the converted string.
1915  * @example
1916  *
1917  * _.toString(null);
1918  * // => ''
1919  *
1920  * _.toString(-0);
1921  * // => '-0'
1922  *
1923  * _.toString([1, 2, 3]);
1924  * // => '1,2,3'
1925  */
1926 function toString(value) {
1927   return value == null ? '' : baseToString(value);
1928 }
1929
1930 /** Used to match leading and trailing whitespace. */
1931 var reTrim = /^\s+|\s+$/g;
1932
1933 /**
1934  * Removes leading and trailing whitespace or specified characters from `string`.
1935  *
1936  * @static
1937  * @memberOf _
1938  * @since 3.0.0
1939  * @category String
1940  * @param {string} [string=''] The string to trim.
1941  * @param {string} [chars=whitespace] The characters to trim.
1942  * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
1943  * @returns {string} Returns the trimmed string.
1944  * @example
1945  *
1946  * _.trim('  abc  ');
1947  * // => 'abc'
1948  *
1949  * _.trim('-_-abc-_-', '_-');
1950  * // => 'abc'
1951  *
1952  * _.map(['  foo  ', '  bar  '], _.trim);
1953  * // => ['foo', 'bar']
1954  */
1955 function trim(string, chars, guard) {
1956   string = toString(string);
1957   if (string && (guard || chars === undefined)) {
1958     return string.replace(reTrim, '');
1959   }
1960   if (!string || !(chars = baseToString(chars))) {
1961     return string;
1962   }
1963   var strSymbols = stringToArray(string),
1964       chrSymbols = stringToArray(chars),
1965       start = charsStartIndex(strSymbols, chrSymbols),
1966       end = charsEndIndex(strSymbols, chrSymbols) + 1;
1967
1968   return castSlice(strSymbols, start, end).join('');
1969 }
1970
1971 var FN_ARGS = /^(function)?\s*[^\(]*\(\s*([^\)]*)\)/m;
1972 var FN_ARG_SPLIT = /,/;
1973 var FN_ARG = /(=.+)?(\s*)$/;
1974 var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
1975
1976 function parseParams(func) {
1977     func = func.toString().replace(STRIP_COMMENTS, '');
1978     func = func.match(FN_ARGS)[2].replace(' ', '');
1979     func = func ? func.split(FN_ARG_SPLIT) : [];
1980     func = func.map(function (arg) {
1981         return trim(arg.replace(FN_ARG, ''));
1982     });
1983     return func;
1984 }
1985
1986 /**
1987  * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent
1988  * tasks are specified as parameters to the function, after the usual callback
1989  * parameter, with the parameter names matching the names of the tasks it
1990  * depends on. This can provide even more readable task graphs which can be
1991  * easier to maintain.
1992  *
1993  * If a final callback is specified, the task results are similarly injected,
1994  * specified as named parameters after the initial error parameter.
1995  *
1996  * The autoInject function is purely syntactic sugar and its semantics are
1997  * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}.
1998  *
1999  * @name autoInject
2000  * @static
2001  * @memberOf module:ControlFlow
2002  * @method
2003  * @see [async.auto]{@link module:ControlFlow.auto}
2004  * @category Control Flow
2005  * @param {Object} tasks - An object, each of whose properties is a function of
2006  * the form 'func([dependencies...], callback). The object's key of a property
2007  * serves as the name of the task defined by that property, i.e. can be used
2008  * when specifying requirements for other tasks.
2009  * * The `callback` parameter is a `callback(err, result)` which must be called
2010  *   when finished, passing an `error` (which can be `null`) and the result of
2011  *   the function's execution. The remaining parameters name other tasks on
2012  *   which the task is dependent, and the results from those tasks are the
2013  *   arguments of those parameters.
2014  * @param {Function} [callback] - An optional callback which is called when all
2015  * the tasks have been completed. It receives the `err` argument if any `tasks`
2016  * pass an error to their callback, and a `results` object with any completed
2017  * task results, similar to `auto`.
2018  * @example
2019  *
2020  * //  The example from `auto` can be rewritten as follows:
2021  * async.autoInject({
2022  *     get_data: function(callback) {
2023  *         // async code to get some data
2024  *         callback(null, 'data', 'converted to array');
2025  *     },
2026  *     make_folder: function(callback) {
2027  *         // async code to create a directory to store a file in
2028  *         // this is run at the same time as getting the data
2029  *         callback(null, 'folder');
2030  *     },
2031  *     write_file: function(get_data, make_folder, callback) {
2032  *         // once there is some data and the directory exists,
2033  *         // write the data to a file in the directory
2034  *         callback(null, 'filename');
2035  *     },
2036  *     email_link: function(write_file, callback) {
2037  *         // once the file is written let's email a link to it...
2038  *         // write_file contains the filename returned by write_file.
2039  *         callback(null, {'file':write_file, 'email':'user@example.com'});
2040  *     }
2041  * }, function(err, results) {
2042  *     console.log('err = ', err);
2043  *     console.log('email_link = ', results.email_link);
2044  * });
2045  *
2046  * // If you are using a JS minifier that mangles parameter names, `autoInject`
2047  * // will not work with plain functions, since the parameter names will be
2048  * // collapsed to a single letter identifier.  To work around this, you can
2049  * // explicitly specify the names of the parameters your task function needs
2050  * // in an array, similar to Angular.js dependency injection.
2051  *
2052  * // This still has an advantage over plain `auto`, since the results a task
2053  * // depends on are still spread into arguments.
2054  * async.autoInject({
2055  *     //...
2056  *     write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {
2057  *         callback(null, 'filename');
2058  *     }],
2059  *     email_link: ['write_file', function(write_file, callback) {
2060  *         callback(null, {'file':write_file, 'email':'user@example.com'});
2061  *     }]
2062  *     //...
2063  * }, function(err, results) {
2064  *     console.log('err = ', err);
2065  *     console.log('email_link = ', results.email_link);
2066  * });
2067  */
2068 function autoInject(tasks, callback) {
2069     var newTasks = {};
2070
2071     baseForOwn(tasks, function (taskFn, key) {
2072         var params;
2073
2074         if (isArray(taskFn)) {
2075             params = taskFn.slice(0, -1);
2076             taskFn = taskFn[taskFn.length - 1];
2077
2078             newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);
2079         } else if (taskFn.length === 1) {
2080             // no dependencies, use the function as-is
2081             newTasks[key] = taskFn;
2082         } else {
2083             params = parseParams(taskFn);
2084             if (taskFn.length === 0 && params.length === 0) {
2085                 throw new Error("autoInject task functions require explicit parameters.");
2086             }
2087
2088             params.pop();
2089
2090             newTasks[key] = params.concat(newTask);
2091         }
2092
2093         function newTask(results, taskCb) {
2094             var newArgs = arrayMap(params, function (name) {
2095                 return results[name];
2096             });
2097             newArgs.push(taskCb);
2098             taskFn.apply(null, newArgs);
2099         }
2100     });
2101
2102     auto(newTasks, callback);
2103 }
2104
2105 var hasSetImmediate = typeof setImmediate === 'function' && setImmediate;
2106 var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';
2107
2108 function fallback(fn) {
2109     setTimeout(fn, 0);
2110 }
2111
2112 function wrap(defer) {
2113     return rest(function (fn, args) {
2114         defer(function () {
2115             fn.apply(null, args);
2116         });
2117     });
2118 }
2119
2120 var _defer;
2121
2122 if (hasSetImmediate) {
2123     _defer = setImmediate;
2124 } else if (hasNextTick) {
2125     _defer = process.nextTick;
2126 } else {
2127     _defer = fallback;
2128 }
2129
2130 var setImmediate$1 = wrap(_defer);
2131
2132 // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation
2133 // used for queues. This implementation assumes that the node provided by the user can be modified
2134 // to adjust the next and last properties. We implement only the minimal functionality
2135 // for queue support.
2136 function DLL() {
2137     this.head = this.tail = null;
2138     this.length = 0;
2139 }
2140
2141 function setInitial(dll, node) {
2142     dll.length = 1;
2143     dll.head = dll.tail = node;
2144 }
2145
2146 DLL.prototype.removeLink = function (node) {
2147     if (node.prev) node.prev.next = node.next;else this.head = node.next;
2148     if (node.next) node.next.prev = node.prev;else this.tail = node.prev;
2149
2150     node.prev = node.next = null;
2151     this.length -= 1;
2152     return node;
2153 };
2154
2155 DLL.prototype.empty = DLL;
2156
2157 DLL.prototype.insertAfter = function (node, newNode) {
2158     newNode.prev = node;
2159     newNode.next = node.next;
2160     if (node.next) node.next.prev = newNode;else this.tail = newNode;
2161     node.next = newNode;
2162     this.length += 1;
2163 };
2164
2165 DLL.prototype.insertBefore = function (node, newNode) {
2166     newNode.prev = node.prev;
2167     newNode.next = node;
2168     if (node.prev) node.prev.next = newNode;else this.head = newNode;
2169     node.prev = newNode;
2170     this.length += 1;
2171 };
2172
2173 DLL.prototype.unshift = function (node) {
2174     if (this.head) this.insertBefore(this.head, node);else setInitial(this, node);
2175 };
2176
2177 DLL.prototype.push = function (node) {
2178     if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node);
2179 };
2180
2181 DLL.prototype.shift = function () {
2182     return this.head && this.removeLink(this.head);
2183 };
2184
2185 DLL.prototype.pop = function () {
2186     return this.tail && this.removeLink(this.tail);
2187 };
2188
2189 function queue(worker, concurrency, payload) {
2190     if (concurrency == null) {
2191         concurrency = 1;
2192     } else if (concurrency === 0) {
2193         throw new Error('Concurrency must not be zero');
2194     }
2195
2196     function _insert(data, insertAtFront, callback) {
2197         if (callback != null && typeof callback !== 'function') {
2198             throw new Error('task callback must be a function');
2199         }
2200         q.started = true;
2201         if (!isArray(data)) {
2202             data = [data];
2203         }
2204         if (data.length === 0 && q.idle()) {
2205             // call drain immediately if there are no tasks
2206             return setImmediate$1(function () {
2207                 q.drain();
2208             });
2209         }
2210
2211         for (var i = 0, l = data.length; i < l; i++) {
2212             var item = {
2213                 data: data[i],
2214                 callback: callback || noop
2215             };
2216
2217             if (insertAtFront) {
2218                 q._tasks.unshift(item);
2219             } else {
2220                 q._tasks.push(item);
2221             }
2222         }
2223         setImmediate$1(q.process);
2224     }
2225
2226     function _next(tasks) {
2227         return rest(function (args) {
2228             workers -= 1;
2229
2230             for (var i = 0, l = tasks.length; i < l; i++) {
2231                 var task = tasks[i];
2232                 var index = baseIndexOf(workersList, task, 0);
2233                 if (index >= 0) {
2234                     workersList.splice(index);
2235                 }
2236
2237                 task.callback.apply(task, args);
2238
2239                 if (args[0] != null) {
2240                     q.error(args[0], task.data);
2241                 }
2242             }
2243
2244             if (workers <= q.concurrency - q.buffer) {
2245                 q.unsaturated();
2246             }
2247
2248             if (q.idle()) {
2249                 q.drain();
2250             }
2251             q.process();
2252         });
2253     }
2254
2255     var workers = 0;
2256     var workersList = [];
2257     var isProcessing = false;
2258     var q = {
2259         _tasks: new DLL(),
2260         concurrency: concurrency,
2261         payload: payload,
2262         saturated: noop,
2263         unsaturated: noop,
2264         buffer: concurrency / 4,
2265         empty: noop,
2266         drain: noop,
2267         error: noop,
2268         started: false,
2269         paused: false,
2270         push: function (data, callback) {
2271             _insert(data, false, callback);
2272         },
2273         kill: function () {
2274             q.drain = noop;
2275             q._tasks.empty();
2276         },
2277         unshift: function (data, callback) {
2278             _insert(data, true, callback);
2279         },
2280         process: function () {
2281             // Avoid trying to start too many processing operations. This can occur
2282             // when callbacks resolve synchronously (#1267).
2283             if (isProcessing) {
2284                 return;
2285             }
2286             isProcessing = true;
2287             while (!q.paused && workers < q.concurrency && q._tasks.length) {
2288                 var tasks = [],
2289                     data = [];
2290                 var l = q._tasks.length;
2291                 if (q.payload) l = Math.min(l, q.payload);
2292                 for (var i = 0; i < l; i++) {
2293                     var node = q._tasks.shift();
2294                     tasks.push(node);
2295                     data.push(node.data);
2296                 }
2297
2298                 if (q._tasks.length === 0) {
2299                     q.empty();
2300                 }
2301                 workers += 1;
2302                 workersList.push(tasks[0]);
2303
2304                 if (workers === q.concurrency) {
2305                     q.saturated();
2306                 }
2307
2308                 var cb = onlyOnce(_next(tasks));
2309                 worker(data, cb);
2310             }
2311             isProcessing = false;
2312         },
2313         length: function () {
2314             return q._tasks.length;
2315         },
2316         running: function () {
2317             return workers;
2318         },
2319         workersList: function () {
2320             return workersList;
2321         },
2322         idle: function () {
2323             return q._tasks.length + workers === 0;
2324         },
2325         pause: function () {
2326             q.paused = true;
2327         },
2328         resume: function () {
2329             if (q.paused === false) {
2330                 return;
2331             }
2332             q.paused = false;
2333             setImmediate$1(q.process);
2334         }
2335     };
2336     return q;
2337 }
2338
2339 /**
2340  * A cargo of tasks for the worker function to complete. Cargo inherits all of
2341  * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}.
2342  * @typedef {Object} CargoObject
2343  * @memberOf module:ControlFlow
2344  * @property {Function} length - A function returning the number of items
2345  * waiting to be processed. Invoke like `cargo.length()`.
2346  * @property {number} payload - An `integer` for determining how many tasks
2347  * should be process per round. This property can be changed after a `cargo` is
2348  * created to alter the payload on-the-fly.
2349  * @property {Function} push - Adds `task` to the `queue`. The callback is
2350  * called once the `worker` has finished processing the task. Instead of a
2351  * single task, an array of `tasks` can be submitted. The respective callback is
2352  * used for every task in the list. Invoke like `cargo.push(task, [callback])`.
2353  * @property {Function} saturated - A callback that is called when the
2354  * `queue.length()` hits the concurrency and further tasks will be queued.
2355  * @property {Function} empty - A callback that is called when the last item
2356  * from the `queue` is given to a `worker`.
2357  * @property {Function} drain - A callback that is called when the last item
2358  * from the `queue` has returned from the `worker`.
2359  * @property {Function} idle - a function returning false if there are items
2360  * waiting or being processed, or true if not. Invoke like `cargo.idle()`.
2361  * @property {Function} pause - a function that pauses the processing of tasks
2362  * until `resume()` is called. Invoke like `cargo.pause()`.
2363  * @property {Function} resume - a function that resumes the processing of
2364  * queued tasks when the queue is paused. Invoke like `cargo.resume()`.
2365  * @property {Function} kill - a function that removes the `drain` callback and
2366  * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`.
2367  */
2368
2369 /**
2370  * Creates a `cargo` object with the specified payload. Tasks added to the
2371  * cargo will be processed altogether (up to the `payload` limit). If the
2372  * `worker` is in progress, the task is queued until it becomes available. Once
2373  * the `worker` has completed some tasks, each callback of those tasks is
2374  * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)
2375  * for how `cargo` and `queue` work.
2376  *
2377  * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers
2378  * at a time, cargo passes an array of tasks to a single worker, repeating
2379  * when the worker is finished.
2380  *
2381  * @name cargo
2382  * @static
2383  * @memberOf module:ControlFlow
2384  * @method
2385  * @see [async.queue]{@link module:ControlFlow.queue}
2386  * @category Control Flow
2387  * @param {Function} worker - An asynchronous function for processing an array
2388  * of queued tasks, which must call its `callback(err)` argument when finished,
2389  * with an optional `err` argument. Invoked with `(tasks, callback)`.
2390  * @param {number} [payload=Infinity] - An optional `integer` for determining
2391  * how many tasks should be processed per round; if omitted, the default is
2392  * unlimited.
2393  * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can
2394  * attached as certain properties to listen for specific events during the
2395  * lifecycle of the cargo and inner queue.
2396  * @example
2397  *
2398  * // create a cargo object with payload 2
2399  * var cargo = async.cargo(function(tasks, callback) {
2400  *     for (var i=0; i<tasks.length; i++) {
2401  *         console.log('hello ' + tasks[i].name);
2402  *     }
2403  *     callback();
2404  * }, 2);
2405  *
2406  * // add some items
2407  * cargo.push({name: 'foo'}, function(err) {
2408  *     console.log('finished processing foo');
2409  * });
2410  * cargo.push({name: 'bar'}, function(err) {
2411  *     console.log('finished processing bar');
2412  * });
2413  * cargo.push({name: 'baz'}, function(err) {
2414  *     console.log('finished processing baz');
2415  * });
2416  */
2417 function cargo(worker, payload) {
2418   return queue(worker, 1, payload);
2419 }
2420
2421 /**
2422  * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.
2423  *
2424  * @name eachOfSeries
2425  * @static
2426  * @memberOf module:Collections
2427  * @method
2428  * @see [async.eachOf]{@link module:Collections.eachOf}
2429  * @alias forEachOfSeries
2430  * @category Collection
2431  * @param {Array|Iterable|Object} coll - A collection to iterate over.
2432  * @param {Function} iteratee - A function to apply to each item in `coll`. The
2433  * `key` is the item's key, or index in the case of an array. The iteratee is
2434  * passed a `callback(err)` which must be called once it has completed. If no
2435  * error has occurred, the callback should be run without arguments or with an
2436  * explicit `null` argument. Invoked with (item, key, callback).
2437  * @param {Function} [callback] - A callback which is called when all `iteratee`
2438  * functions have finished, or an error occurs. Invoked with (err).
2439  */
2440 var eachOfSeries = doLimit(eachOfLimit, 1);
2441
2442 /**
2443  * Reduces `coll` into a single value using an async `iteratee` to return each
2444  * successive step. `memo` is the initial state of the reduction. This function
2445  * only operates in series.
2446  *
2447  * For performance reasons, it may make sense to split a call to this function
2448  * into a parallel map, and then use the normal `Array.prototype.reduce` on the
2449  * results. This function is for situations where each step in the reduction
2450  * needs to be async; if you can get the data before reducing it, then it's
2451  * probably a good idea to do so.
2452  *
2453  * @name reduce
2454  * @static
2455  * @memberOf module:Collections
2456  * @method
2457  * @alias inject
2458  * @alias foldl
2459  * @category Collection
2460  * @param {Array|Iterable|Object} coll - A collection to iterate over.
2461  * @param {*} memo - The initial state of the reduction.
2462  * @param {Function} iteratee - A function applied to each item in the
2463  * array to produce the next step in the reduction. The `iteratee` is passed a
2464  * `callback(err, reduction)` which accepts an optional error as its first
2465  * argument, and the state of the reduction as the second. If an error is
2466  * passed to the callback, the reduction is stopped and the main `callback` is
2467  * immediately called with the error. Invoked with (memo, item, callback).
2468  * @param {Function} [callback] - A callback which is called after all the
2469  * `iteratee` functions have finished. Result is the reduced value. Invoked with
2470  * (err, result).
2471  * @example
2472  *
2473  * async.reduce([1,2,3], 0, function(memo, item, callback) {
2474  *     // pointless async:
2475  *     process.nextTick(function() {
2476  *         callback(null, memo + item)
2477  *     });
2478  * }, function(err, result) {
2479  *     // result is now equal to the last value of memo, which is 6
2480  * });
2481  */
2482 function reduce(coll, memo, iteratee, callback) {
2483     callback = once(callback || noop);
2484     eachOfSeries(coll, function (x, i, callback) {
2485         iteratee(memo, x, function (err, v) {
2486             memo = v;
2487             callback(err);
2488         });
2489     }, function (err) {
2490         callback(err, memo);
2491     });
2492 }
2493
2494 /**
2495  * Version of the compose function that is more natural to read. Each function
2496  * consumes the return value of the previous function. It is the equivalent of
2497  * [compose]{@link module:ControlFlow.compose} with the arguments reversed.
2498  *
2499  * Each function is executed with the `this` binding of the composed function.
2500  *
2501  * @name seq
2502  * @static
2503  * @memberOf module:ControlFlow
2504  * @method
2505  * @see [async.compose]{@link module:ControlFlow.compose}
2506  * @category Control Flow
2507  * @param {...Function} functions - the asynchronous functions to compose
2508  * @returns {Function} a function that composes the `functions` in order
2509  * @example
2510  *
2511  * // Requires lodash (or underscore), express3 and dresende's orm2.
2512  * // Part of an app, that fetches cats of the logged user.
2513  * // This example uses `seq` function to avoid overnesting and error
2514  * // handling clutter.
2515  * app.get('/cats', function(request, response) {
2516  *     var User = request.models.User;
2517  *     async.seq(
2518  *         _.bind(User.get, User),  // 'User.get' has signature (id, callback(err, data))
2519  *         function(user, fn) {
2520  *             user.getCats(fn);      // 'getCats' has signature (callback(err, data))
2521  *         }
2522  *     )(req.session.user_id, function (err, cats) {
2523  *         if (err) {
2524  *             console.error(err);
2525  *             response.json({ status: 'error', message: err.message });
2526  *         } else {
2527  *             response.json({ status: 'ok', message: 'Cats found', data: cats });
2528  *         }
2529  *     });
2530  * });
2531  */
2532 var seq$1 = rest(function seq(functions) {
2533     return rest(function (args) {
2534         var that = this;
2535
2536         var cb = args[args.length - 1];
2537         if (typeof cb == 'function') {
2538             args.pop();
2539         } else {
2540             cb = noop;
2541         }
2542
2543         reduce(functions, args, function (newargs, fn, cb) {
2544             fn.apply(that, newargs.concat(rest(function (err, nextargs) {
2545                 cb(err, nextargs);
2546             })));
2547         }, function (err, results) {
2548             cb.apply(that, [err].concat(results));
2549         });
2550     });
2551 });
2552
2553 /**
2554  * Creates a function which is a composition of the passed asynchronous
2555  * functions. Each function consumes the return value of the function that
2556  * follows. Composing functions `f()`, `g()`, and `h()` would produce the result
2557  * of `f(g(h()))`, only this version uses callbacks to obtain the return values.
2558  *
2559  * Each function is executed with the `this` binding of the composed function.
2560  *
2561  * @name compose
2562  * @static
2563  * @memberOf module:ControlFlow
2564  * @method
2565  * @category Control Flow
2566  * @param {...Function} functions - the asynchronous functions to compose
2567  * @returns {Function} an asynchronous function that is the composed
2568  * asynchronous `functions`
2569  * @example
2570  *
2571  * function add1(n, callback) {
2572  *     setTimeout(function () {
2573  *         callback(null, n + 1);
2574  *     }, 10);
2575  * }
2576  *
2577  * function mul3(n, callback) {
2578  *     setTimeout(function () {
2579  *         callback(null, n * 3);
2580  *     }, 10);
2581  * }
2582  *
2583  * var add1mul3 = async.compose(mul3, add1);
2584  * add1mul3(4, function (err, result) {
2585  *     // result now equals 15
2586  * });
2587  */
2588 var compose = rest(function (args) {
2589   return seq$1.apply(null, args.reverse());
2590 });
2591
2592 function concat$1(eachfn, arr, fn, callback) {
2593     var result = [];
2594     eachfn(arr, function (x, index, cb) {
2595         fn(x, function (err, y) {
2596             result = result.concat(y || []);
2597             cb(err);
2598         });
2599     }, function (err) {
2600         callback(err, result);
2601     });
2602 }
2603
2604 /**
2605  * Applies `iteratee` to each item in `coll`, concatenating the results. Returns
2606  * the concatenated list. The `iteratee`s are called in parallel, and the
2607  * results are concatenated as they return. There is no guarantee that the
2608  * results array will be returned in the original order of `coll` passed to the
2609  * `iteratee` function.
2610  *
2611  * @name concat
2612  * @static
2613  * @memberOf module:Collections
2614  * @method
2615  * @category Collection
2616  * @param {Array|Iterable|Object} coll - A collection to iterate over.
2617  * @param {Function} iteratee - A function to apply to each item in `coll`.
2618  * The iteratee is passed a `callback(err, results)` which must be called once
2619  * it has completed with an error (which can be `null`) and an array of results.
2620  * Invoked with (item, callback).
2621  * @param {Function} [callback(err)] - A callback which is called after all the
2622  * `iteratee` functions have finished, or an error occurs. Results is an array
2623  * containing the concatenated results of the `iteratee` function. Invoked with
2624  * (err, results).
2625  * @example
2626  *
2627  * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) {
2628  *     // files is now a list of filenames that exist in the 3 directories
2629  * });
2630  */
2631 var concat = doParallel(concat$1);
2632
2633 function doSeries(fn) {
2634     return function (obj, iteratee, callback) {
2635         return fn(eachOfSeries, obj, iteratee, callback);
2636     };
2637 }
2638
2639 /**
2640  * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.
2641  *
2642  * @name concatSeries
2643  * @static
2644  * @memberOf module:Collections
2645  * @method
2646  * @see [async.concat]{@link module:Collections.concat}
2647  * @category Collection
2648  * @param {Array|Iterable|Object} coll - A collection to iterate over.
2649  * @param {Function} iteratee - A function to apply to each item in `coll`.
2650  * The iteratee is passed a `callback(err, results)` which must be called once
2651  * it has completed with an error (which can be `null`) and an array of results.
2652  * Invoked with (item, callback).
2653  * @param {Function} [callback(err)] - A callback which is called after all the
2654  * `iteratee` functions have finished, or an error occurs. Results is an array
2655  * containing the concatenated results of the `iteratee` function. Invoked with
2656  * (err, results).
2657  */
2658 var concatSeries = doSeries(concat$1);
2659
2660 /**
2661  * Returns a function that when called, calls-back with the values provided.
2662  * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to
2663  * [`auto`]{@link module:ControlFlow.auto}.
2664  *
2665  * @name constant
2666  * @static
2667  * @memberOf module:Utils
2668  * @method
2669  * @category Util
2670  * @param {...*} arguments... - Any number of arguments to automatically invoke
2671  * callback with.
2672  * @returns {Function} Returns a function that when invoked, automatically
2673  * invokes the callback with the previous given arguments.
2674  * @example
2675  *
2676  * async.waterfall([
2677  *     async.constant(42),
2678  *     function (value, next) {
2679  *         // value === 42
2680  *     },
2681  *     //...
2682  * ], callback);
2683  *
2684  * async.waterfall([
2685  *     async.constant(filename, "utf8"),
2686  *     fs.readFile,
2687  *     function (fileData, next) {
2688  *         //...
2689  *     }
2690  *     //...
2691  * ], callback);
2692  *
2693  * async.auto({
2694  *     hostname: async.constant("https://server.net/"),
2695  *     port: findFreePort,
2696  *     launchServer: ["hostname", "port", function (options, cb) {
2697  *         startServer(options, cb);
2698  *     }],
2699  *     //...
2700  * }, callback);
2701  */
2702 var constant = rest(function (values) {
2703     var args = [null].concat(values);
2704     return initialParams(function (ignoredArgs, callback) {
2705         return callback.apply(this, args);
2706     });
2707 });
2708
2709 function _createTester(check, getResult) {
2710     return function (eachfn, arr, iteratee, cb) {
2711         cb = cb || noop;
2712         var testPassed = false;
2713         var testResult;
2714         eachfn(arr, function (value, _, callback) {
2715             iteratee(value, function (err, result) {
2716                 if (err) {
2717                     callback(err);
2718                 } else if (check(result) && !testResult) {
2719                     testPassed = true;
2720                     testResult = getResult(true, value);
2721                     callback(null, breakLoop);
2722                 } else {
2723                     callback();
2724                 }
2725             });
2726         }, function (err) {
2727             if (err) {
2728                 cb(err);
2729             } else {
2730                 cb(null, testPassed ? testResult : getResult(false));
2731             }
2732         });
2733     };
2734 }
2735
2736 function _findGetResult(v, x) {
2737     return x;
2738 }
2739
2740 /**
2741  * Returns the first value in `coll` that passes an async truth test. The
2742  * `iteratee` is applied in parallel, meaning the first iteratee to return
2743  * `true` will fire the detect `callback` with that result. That means the
2744  * result might not be the first item in the original `coll` (in terms of order)
2745  * that passes the test.
2746
2747  * If order within the original `coll` is important, then look at
2748  * [`detectSeries`]{@link module:Collections.detectSeries}.
2749  *
2750  * @name detect
2751  * @static
2752  * @memberOf module:Collections
2753  * @method
2754  * @alias find
2755  * @category Collections
2756  * @param {Array|Iterable|Object} coll - A collection to iterate over.
2757  * @param {Function} iteratee - A truth test to apply to each item in `coll`.
2758  * The iteratee is passed a `callback(err, truthValue)` which must be called
2759  * with a boolean argument once it has completed. Invoked with (item, callback).
2760  * @param {Function} [callback] - A callback which is called as soon as any
2761  * iteratee returns `true`, or after all the `iteratee` functions have finished.
2762  * Result will be the first item in the array that passes the truth test
2763  * (iteratee) or the value `undefined` if none passed. Invoked with
2764  * (err, result).
2765  * @example
2766  *
2767  * async.detect(['file1','file2','file3'], function(filePath, callback) {
2768  *     fs.access(filePath, function(err) {
2769  *         callback(null, !err)
2770  *     });
2771  * }, function(err, result) {
2772  *     // result now equals the first file in the list that exists
2773  * });
2774  */
2775 var detect = doParallel(_createTester(identity, _findGetResult));
2776
2777 /**
2778  * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a
2779  * time.
2780  *
2781  * @name detectLimit
2782  * @static
2783  * @memberOf module:Collections
2784  * @method
2785  * @see [async.detect]{@link module:Collections.detect}
2786  * @alias findLimit
2787  * @category Collections
2788  * @param {Array|Iterable|Object} coll - A collection to iterate over.
2789  * @param {number} limit - The maximum number of async operations at a time.
2790  * @param {Function} iteratee - A truth test to apply to each item in `coll`.
2791  * The iteratee is passed a `callback(err, truthValue)` which must be called
2792  * with a boolean argument once it has completed. Invoked with (item, callback).
2793  * @param {Function} [callback] - A callback which is called as soon as any
2794  * iteratee returns `true`, or after all the `iteratee` functions have finished.
2795  * Result will be the first item in the array that passes the truth test
2796  * (iteratee) or the value `undefined` if none passed. Invoked with
2797  * (err, result).
2798  */
2799 var detectLimit = doParallelLimit(_createTester(identity, _findGetResult));
2800
2801 /**
2802  * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.
2803  *
2804  * @name detectSeries
2805  * @static
2806  * @memberOf module:Collections
2807  * @method
2808  * @see [async.detect]{@link module:Collections.detect}
2809  * @alias findSeries
2810  * @category Collections
2811  * @param {Array|Iterable|Object} coll - A collection to iterate over.
2812  * @param {Function} iteratee - A truth test to apply to each item in `coll`.
2813  * The iteratee is passed a `callback(err, truthValue)` which must be called
2814  * with a boolean argument once it has completed. Invoked with (item, callback).
2815  * @param {Function} [callback] - A callback which is called as soon as any
2816  * iteratee returns `true`, or after all the `iteratee` functions have finished.
2817  * Result will be the first item in the array that passes the truth test
2818  * (iteratee) or the value `undefined` if none passed. Invoked with
2819  * (err, result).
2820  */
2821 var detectSeries = doLimit(detectLimit, 1);
2822
2823 function consoleFunc(name) {
2824     return rest(function (fn, args) {
2825         fn.apply(null, args.concat(rest(function (err, args) {
2826             if (typeof console === 'object') {
2827                 if (err) {
2828                     if (console.error) {
2829                         console.error(err);
2830                     }
2831                 } else if (console[name]) {
2832                     arrayEach(args, function (x) {
2833                         console[name](x);
2834                     });
2835                 }
2836             }
2837         })));
2838     });
2839 }
2840
2841 /**
2842  * Logs the result of an `async` function to the `console` using `console.dir`
2843  * to display the properties of the resulting object. Only works in Node.js or
2844  * in browsers that support `console.dir` and `console.error` (such as FF and
2845  * Chrome). If multiple arguments are returned from the async function,
2846  * `console.dir` is called on each argument in order.
2847  *
2848  * @name dir
2849  * @static
2850  * @memberOf module:Utils
2851  * @method
2852  * @category Util
2853  * @param {Function} function - The function you want to eventually apply all
2854  * arguments to.
2855  * @param {...*} arguments... - Any number of arguments to apply to the function.
2856  * @example
2857  *
2858  * // in a module
2859  * var hello = function(name, callback) {
2860  *     setTimeout(function() {
2861  *         callback(null, {hello: name});
2862  *     }, 1000);
2863  * };
2864  *
2865  * // in the node repl
2866  * node> async.dir(hello, 'world');
2867  * {hello: 'world'}
2868  */
2869 var dir = consoleFunc('dir');
2870
2871 /**
2872  * The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in
2873  * the order of operations, the arguments `test` and `fn` are switched.
2874  *
2875  * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function.
2876  * @name doDuring
2877  * @static
2878  * @memberOf module:ControlFlow
2879  * @method
2880  * @see [async.during]{@link module:ControlFlow.during}
2881  * @category Control Flow
2882  * @param {Function} fn - A function which is called each time `test` passes.
2883  * The function is passed a `callback(err)`, which must be called once it has
2884  * completed with an optional `err` argument. Invoked with (callback).
2885  * @param {Function} test - asynchronous truth test to perform before each
2886  * execution of `fn`. Invoked with (...args, callback), where `...args` are the
2887  * non-error args from the previous callback of `fn`.
2888  * @param {Function} [callback] - A callback which is called after the test
2889  * function has failed and repeated execution of `fn` has stopped. `callback`
2890  * will be passed an error if one occured, otherwise `null`.
2891  */
2892 function doDuring(fn, test, callback) {
2893     callback = onlyOnce(callback || noop);
2894
2895     var next = rest(function (err, args) {
2896         if (err) return callback(err);
2897         args.push(check);
2898         test.apply(this, args);
2899     });
2900
2901     function check(err, truth) {
2902         if (err) return callback(err);
2903         if (!truth) return callback(null);
2904         fn(next);
2905     }
2906
2907     check(null, true);
2908 }
2909
2910 /**
2911  * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in
2912  * the order of operations, the arguments `test` and `iteratee` are switched.
2913  *
2914  * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
2915  *
2916  * @name doWhilst
2917  * @static
2918  * @memberOf module:ControlFlow
2919  * @method
2920  * @see [async.whilst]{@link module:ControlFlow.whilst}
2921  * @category Control Flow
2922  * @param {Function} iteratee - A function which is called each time `test`
2923  * passes. The function is passed a `callback(err)`, which must be called once
2924  * it has completed with an optional `err` argument. Invoked with (callback).
2925  * @param {Function} test - synchronous truth test to perform after each
2926  * execution of `iteratee`. Invoked with the non-error callback results of 
2927  * `iteratee`.
2928  * @param {Function} [callback] - A callback which is called after the test
2929  * function has failed and repeated execution of `iteratee` has stopped.
2930  * `callback` will be passed an error and any arguments passed to the final
2931  * `iteratee`'s callback. Invoked with (err, [results]);
2932  */
2933 function doWhilst(iteratee, test, callback) {
2934     callback = onlyOnce(callback || noop);
2935     var next = rest(function (err, args) {
2936         if (err) return callback(err);
2937         if (test.apply(this, args)) return iteratee(next);
2938         callback.apply(null, [null].concat(args));
2939     });
2940     iteratee(next);
2941 }
2942
2943 /**
2944  * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the
2945  * argument ordering differs from `until`.
2946  *
2947  * @name doUntil
2948  * @static
2949  * @memberOf module:ControlFlow
2950  * @method
2951  * @see [async.doWhilst]{@link module:ControlFlow.doWhilst}
2952  * @category Control Flow
2953  * @param {Function} fn - A function which is called each time `test` fails.
2954  * The function is passed a `callback(err)`, which must be called once it has
2955  * completed with an optional `err` argument. Invoked with (callback).
2956  * @param {Function} test - synchronous truth test to perform after each
2957  * execution of `fn`. Invoked with the non-error callback results of `fn`.
2958  * @param {Function} [callback] - A callback which is called after the test
2959  * function has passed and repeated execution of `fn` has stopped. `callback`
2960  * will be passed an error and any arguments passed to the final `fn`'s
2961  * callback. Invoked with (err, [results]);
2962  */
2963 function doUntil(fn, test, callback) {
2964     doWhilst(fn, function () {
2965         return !test.apply(this, arguments);
2966     }, callback);
2967 }
2968
2969 /**
2970  * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that
2971  * is passed a callback in the form of `function (err, truth)`. If error is
2972  * passed to `test` or `fn`, the main callback is immediately called with the
2973  * value of the error.
2974  *
2975  * @name during
2976  * @static
2977  * @memberOf module:ControlFlow
2978  * @method
2979  * @see [async.whilst]{@link module:ControlFlow.whilst}
2980  * @category Control Flow
2981  * @param {Function} test - asynchronous truth test to perform before each
2982  * execution of `fn`. Invoked with (callback).
2983  * @param {Function} fn - A function which is called each time `test` passes.
2984  * The function is passed a `callback(err)`, which must be called once it has
2985  * completed with an optional `err` argument. Invoked with (callback).
2986  * @param {Function} [callback] - A callback which is called after the test
2987  * function has failed and repeated execution of `fn` has stopped. `callback`
2988  * will be passed an error, if one occured, otherwise `null`.
2989  * @example
2990  *
2991  * var count = 0;
2992  *
2993  * async.during(
2994  *     function (callback) {
2995  *         return callback(null, count < 5);
2996  *     },
2997  *     function (callback) {
2998  *         count++;
2999  *         setTimeout(callback, 1000);
3000  *     },
3001  *     function (err) {
3002  *         // 5 seconds have passed
3003  *     }
3004  * );
3005  */
3006 function during(test, fn, callback) {
3007     callback = onlyOnce(callback || noop);
3008
3009     function next(err) {
3010         if (err) return callback(err);
3011         test(check);
3012     }
3013
3014     function check(err, truth) {
3015         if (err) return callback(err);
3016         if (!truth) return callback(null);
3017         fn(next);
3018     }
3019
3020     test(check);
3021 }
3022
3023 function _withoutIndex(iteratee) {
3024     return function (value, index, callback) {
3025         return iteratee(value, callback);
3026     };
3027 }
3028
3029 /**
3030  * Applies the function `iteratee` to each item in `coll`, in parallel.
3031  * The `iteratee` is called with an item from the list, and a callback for when
3032  * it has finished. If the `iteratee` passes an error to its `callback`, the
3033  * main `callback` (for the `each` function) is immediately called with the
3034  * error.
3035  *
3036  * Note, that since this function applies `iteratee` to each item in parallel,
3037  * there is no guarantee that the iteratee functions will complete in order.
3038  *
3039  * @name each
3040  * @static
3041  * @memberOf module:Collections
3042  * @method
3043  * @alias forEach
3044  * @category Collection
3045  * @param {Array|Iterable|Object} coll - A collection to iterate over.
3046  * @param {Function} iteratee - A function to apply to each item
3047  * in `coll`. The iteratee is passed a `callback(err)` which must be called once
3048  * it has completed. If no error has occurred, the `callback` should be run
3049  * without arguments or with an explicit `null` argument. The array index is not
3050  * passed to the iteratee. Invoked with (item, callback). If you need the index,
3051  * use `eachOf`.
3052  * @param {Function} [callback] - A callback which is called when all
3053  * `iteratee` functions have finished, or an error occurs. Invoked with (err).
3054  * @example
3055  *
3056  * // assuming openFiles is an array of file names and saveFile is a function
3057  * // to save the modified contents of that file:
3058  *
3059  * async.each(openFiles, saveFile, function(err){
3060  *   // if any of the saves produced an error, err would equal that error
3061  * });
3062  *
3063  * // assuming openFiles is an array of file names
3064  * async.each(openFiles, function(file, callback) {
3065  *
3066  *     // Perform operation on file here.
3067  *     console.log('Processing file ' + file);
3068  *
3069  *     if( file.length > 32 ) {
3070  *       console.log('This file name is too long');
3071  *       callback('File name too long');
3072  *     } else {
3073  *       // Do work to process file here
3074  *       console.log('File processed');
3075  *       callback();
3076  *     }
3077  * }, function(err) {
3078  *     // if any of the file processing produced an error, err would equal that error
3079  *     if( err ) {
3080  *       // One of the iterations produced an error.
3081  *       // All processing will now stop.
3082  *       console.log('A file failed to process');
3083  *     } else {
3084  *       console.log('All files have been processed successfully');
3085  *     }
3086  * });
3087  */
3088 function eachLimit(coll, iteratee, callback) {
3089   eachOf(coll, _withoutIndex(iteratee), callback);
3090 }
3091
3092 /**
3093  * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.
3094  *
3095  * @name eachLimit
3096  * @static
3097  * @memberOf module:Collections
3098  * @method
3099  * @see [async.each]{@link module:Collections.each}
3100  * @alias forEachLimit
3101  * @category Collection
3102  * @param {Array|Iterable|Object} coll - A collection to iterate over.
3103  * @param {number} limit - The maximum number of async operations at a time.
3104  * @param {Function} iteratee - A function to apply to each item in `coll`. The
3105  * iteratee is passed a `callback(err)` which must be called once it has
3106  * completed. If no error has occurred, the `callback` should be run without
3107  * arguments or with an explicit `null` argument. The array index is not passed
3108  * to the iteratee. Invoked with (item, callback). If you need the index, use
3109  * `eachOfLimit`.
3110  * @param {Function} [callback] - A callback which is called when all
3111  * `iteratee` functions have finished, or an error occurs. Invoked with (err).
3112  */
3113 function eachLimit$1(coll, limit, iteratee, callback) {
3114   _eachOfLimit(limit)(coll, _withoutIndex(iteratee), callback);
3115 }
3116
3117 /**
3118  * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.
3119  *
3120  * @name eachSeries
3121  * @static
3122  * @memberOf module:Collections
3123  * @method
3124  * @see [async.each]{@link module:Collections.each}
3125  * @alias forEachSeries
3126  * @category Collection
3127  * @param {Array|Iterable|Object} coll - A collection to iterate over.
3128  * @param {Function} iteratee - A function to apply to each
3129  * item in `coll`. The iteratee is passed a `callback(err)` which must be called
3130  * once it has completed. If no error has occurred, the `callback` should be run
3131  * without arguments or with an explicit `null` argument. The array index is
3132  * not passed to the iteratee. Invoked with (item, callback). If you need the
3133  * index, use `eachOfSeries`.
3134  * @param {Function} [callback] - A callback which is called when all
3135  * `iteratee` functions have finished, or an error occurs. Invoked with (err).
3136  */
3137 var eachSeries = doLimit(eachLimit$1, 1);
3138
3139 /**
3140  * Wrap an async function and ensure it calls its callback on a later tick of
3141  * the event loop.  If the function already calls its callback on a next tick,
3142  * no extra deferral is added. This is useful for preventing stack overflows
3143  * (`RangeError: Maximum call stack size exceeded`) and generally keeping
3144  * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)
3145  * contained.
3146  *
3147  * @name ensureAsync
3148  * @static
3149  * @memberOf module:Utils
3150  * @method
3151  * @category Util
3152  * @param {Function} fn - an async function, one that expects a node-style
3153  * callback as its last argument.
3154  * @returns {Function} Returns a wrapped function with the exact same call
3155  * signature as the function passed in.
3156  * @example
3157  *
3158  * function sometimesAsync(arg, callback) {
3159  *     if (cache[arg]) {
3160  *         return callback(null, cache[arg]); // this would be synchronous!!
3161  *     } else {
3162  *         doSomeIO(arg, callback); // this IO would be asynchronous
3163  *     }
3164  * }
3165  *
3166  * // this has a risk of stack overflows if many results are cached in a row
3167  * async.mapSeries(args, sometimesAsync, done);
3168  *
3169  * // this will defer sometimesAsync's callback if necessary,
3170  * // preventing stack overflows
3171  * async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
3172  */
3173 function ensureAsync(fn) {
3174     return initialParams(function (args, callback) {
3175         var sync = true;
3176         args.push(function () {
3177             var innerArgs = arguments;
3178             if (sync) {
3179                 setImmediate$1(function () {
3180                     callback.apply(null, innerArgs);
3181                 });
3182             } else {
3183                 callback.apply(null, innerArgs);
3184             }
3185         });
3186         fn.apply(this, args);
3187         sync = false;
3188     });
3189 }
3190
3191 function notId(v) {
3192     return !v;
3193 }
3194
3195 /**
3196  * Returns `true` if every element in `coll` satisfies an async test. If any
3197  * iteratee call returns `false`, the main `callback` is immediately called.
3198  *
3199  * @name every
3200  * @static
3201  * @memberOf module:Collections
3202  * @method
3203  * @alias all
3204  * @category Collection
3205  * @param {Array|Iterable|Object} coll - A collection to iterate over.
3206  * @param {Function} iteratee - A truth test to apply to each item in the
3207  * collection in parallel. The iteratee is passed a `callback(err, truthValue)`
3208  * which must be called with a  boolean argument once it has completed. Invoked
3209  * with (item, callback).
3210  * @param {Function} [callback] - A callback which is called after all the
3211  * `iteratee` functions have finished. Result will be either `true` or `false`
3212  * depending on the values of the async tests. Invoked with (err, result).
3213  * @example
3214  *
3215  * async.every(['file1','file2','file3'], function(filePath, callback) {
3216  *     fs.access(filePath, function(err) {
3217  *         callback(null, !err)
3218  *     });
3219  * }, function(err, result) {
3220  *     // if result is true then every file exists
3221  * });
3222  */
3223 var every = doParallel(_createTester(notId, notId));
3224
3225 /**
3226  * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.
3227  *
3228  * @name everyLimit
3229  * @static
3230  * @memberOf module:Collections
3231  * @method
3232  * @see [async.every]{@link module:Collections.every}
3233  * @alias allLimit
3234  * @category Collection
3235  * @param {Array|Iterable|Object} coll - A collection to iterate over.
3236  * @param {number} limit - The maximum number of async operations at a time.
3237  * @param {Function} iteratee - A truth test to apply to each item in the
3238  * collection in parallel. The iteratee is passed a `callback(err, truthValue)`
3239  * which must be called with a  boolean argument once it has completed. Invoked
3240  * with (item, callback).
3241  * @param {Function} [callback] - A callback which is called after all the
3242  * `iteratee` functions have finished. Result will be either `true` or `false`
3243  * depending on the values of the async tests. Invoked with (err, result).
3244  */
3245 var everyLimit = doParallelLimit(_createTester(notId, notId));
3246
3247 /**
3248  * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.
3249  *
3250  * @name everySeries
3251  * @static
3252  * @memberOf module:Collections
3253  * @method
3254  * @see [async.every]{@link module:Collections.every}
3255  * @alias allSeries
3256  * @category Collection
3257  * @param {Array|Iterable|Object} coll - A collection to iterate over.
3258  * @param {Function} iteratee - A truth test to apply to each item in the
3259  * collection in parallel. The iteratee is passed a `callback(err, truthValue)`
3260  * which must be called with a  boolean argument once it has completed. Invoked
3261  * with (item, callback).
3262  * @param {Function} [callback] - A callback which is called after all the
3263  * `iteratee` functions have finished. Result will be either `true` or `false`
3264  * depending on the values of the async tests. Invoked with (err, result).
3265  */
3266 var everySeries = doLimit(everyLimit, 1);
3267
3268 /**
3269  * The base implementation of `_.property` without support for deep paths.
3270  *
3271  * @private
3272  * @param {string} key The key of the property to get.
3273  * @returns {Function} Returns the new accessor function.
3274  */
3275 function baseProperty(key) {
3276   return function(object) {
3277     return object == null ? undefined : object[key];
3278   };
3279 }
3280
3281 function filterArray(eachfn, arr, iteratee, callback) {
3282     var truthValues = new Array(arr.length);
3283     eachfn(arr, function (x, index, callback) {
3284         iteratee(x, function (err, v) {
3285             truthValues[index] = !!v;
3286             callback(err);
3287         });
3288     }, function (err) {
3289         if (err) return callback(err);
3290         var results = [];
3291         for (var i = 0; i < arr.length; i++) {
3292             if (truthValues[i]) results.push(arr[i]);
3293         }
3294         callback(null, results);
3295     });
3296 }
3297
3298 function filterGeneric(eachfn, coll, iteratee, callback) {
3299     var results = [];
3300     eachfn(coll, function (x, index, callback) {
3301         iteratee(x, function (err, v) {
3302             if (err) {
3303                 callback(err);
3304             } else {
3305                 if (v) {
3306                     results.push({ index: index, value: x });
3307                 }
3308                 callback();
3309             }
3310         });
3311     }, function (err) {
3312         if (err) {
3313             callback(err);
3314         } else {
3315             callback(null, arrayMap(results.sort(function (a, b) {
3316                 return a.index - b.index;
3317             }), baseProperty('value')));
3318         }
3319     });
3320 }
3321
3322 function _filter(eachfn, coll, iteratee, callback) {
3323     var filter = isArrayLike(coll) ? filterArray : filterGeneric;
3324     filter(eachfn, coll, iteratee, callback || noop);
3325 }
3326
3327 /**
3328  * Returns a new array of all the values in `coll` which pass an async truth
3329  * test. This operation is performed in parallel, but the results array will be
3330  * in the same order as the original.
3331  *
3332  * @name filter
3333  * @static
3334  * @memberOf module:Collections
3335  * @method
3336  * @alias select
3337  * @category Collection
3338  * @param {Array|Iterable|Object} coll - A collection to iterate over.
3339  * @param {Function} iteratee - A truth test to apply to each item in `coll`.
3340  * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
3341  * with a boolean argument once it has completed. Invoked with (item, callback).
3342  * @param {Function} [callback] - A callback which is called after all the
3343  * `iteratee` functions have finished. Invoked with (err, results).
3344  * @example
3345  *
3346  * async.filter(['file1','file2','file3'], function(filePath, callback) {
3347  *     fs.access(filePath, function(err) {
3348  *         callback(null, !err)
3349  *     });
3350  * }, function(err, results) {
3351  *     // results now equals an array of the existing files
3352  * });
3353  */
3354 var filter = doParallel(_filter);
3355
3356 /**
3357  * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a
3358  * time.
3359  *
3360  * @name filterLimit
3361  * @static
3362  * @memberOf module:Collections
3363  * @method
3364  * @see [async.filter]{@link module:Collections.filter}
3365  * @alias selectLimit
3366  * @category Collection
3367  * @param {Array|Iterable|Object} coll - A collection to iterate over.
3368  * @param {number} limit - The maximum number of async operations at a time.
3369  * @param {Function} iteratee - A truth test to apply to each item in `coll`.
3370  * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
3371  * with a boolean argument once it has completed. Invoked with (item, callback).
3372  * @param {Function} [callback] - A callback which is called after all the
3373  * `iteratee` functions have finished. Invoked with (err, results).
3374  */
3375 var filterLimit = doParallelLimit(_filter);
3376
3377 /**
3378  * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.
3379  *
3380  * @name filterSeries
3381  * @static
3382  * @memberOf module:Collections
3383  * @method
3384  * @see [async.filter]{@link module:Collections.filter}
3385  * @alias selectSeries
3386  * @category Collection
3387  * @param {Array|Iterable|Object} coll - A collection to iterate over.
3388  * @param {Function} iteratee - A truth test to apply to each item in `coll`.
3389  * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
3390  * with a boolean argument once it has completed. Invoked with (item, callback).
3391  * @param {Function} [callback] - A callback which is called after all the
3392  * `iteratee` functions have finished. Invoked with (err, results)
3393  */
3394 var filterSeries = doLimit(filterLimit, 1);
3395
3396 /**
3397  * Calls the asynchronous function `fn` with a callback parameter that allows it
3398  * to call itself again, in series, indefinitely.
3399
3400  * If an error is passed to the
3401  * callback then `errback` is called with the error, and execution stops,
3402  * otherwise it will never be called.
3403  *
3404  * @name forever
3405  * @static
3406  * @memberOf module:ControlFlow
3407  * @method
3408  * @category Control Flow
3409  * @param {Function} fn - a function to call repeatedly. Invoked with (next).
3410  * @param {Function} [errback] - when `fn` passes an error to it's callback,
3411  * this function will be called, and execution stops. Invoked with (err).
3412  * @example
3413  *
3414  * async.forever(
3415  *     function(next) {
3416  *         // next is suitable for passing to things that need a callback(err [, whatever]);
3417  *         // it will result in this function being called again.
3418  *     },
3419  *     function(err) {
3420  *         // if next is called with a value in its first parameter, it will appear
3421  *         // in here as 'err', and execution will stop.
3422  *     }
3423  * );
3424  */
3425 function forever(fn, errback) {
3426     var done = onlyOnce(errback || noop);
3427     var task = ensureAsync(fn);
3428
3429     function next(err) {
3430         if (err) return done(err);
3431         task(next);
3432     }
3433     next();
3434 }
3435
3436 /**
3437  * Logs the result of an `async` function to the `console`. Only works in
3438  * Node.js or in browsers that support `console.log` and `console.error` (such
3439  * as FF and Chrome). If multiple arguments are returned from the async
3440  * function, `console.log` is called on each argument in order.
3441  *
3442  * @name log
3443  * @static
3444  * @memberOf module:Utils
3445  * @method
3446  * @category Util
3447  * @param {Function} function - The function you want to eventually apply all
3448  * arguments to.
3449  * @param {...*} arguments... - Any number of arguments to apply to the function.
3450  * @example
3451  *
3452  * // in a module
3453  * var hello = function(name, callback) {
3454  *     setTimeout(function() {
3455  *         callback(null, 'hello ' + name);
3456  *     }, 1000);
3457  * };
3458  *
3459  * // in the node repl
3460  * node> async.log(hello, 'world');
3461  * 'hello world'
3462  */
3463 var log = consoleFunc('log');
3464
3465 /**
3466  * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a
3467  * time.
3468  *
3469  * @name mapValuesLimit
3470  * @static
3471  * @memberOf module:Collections
3472  * @method
3473  * @see [async.mapValues]{@link module:Collections.mapValues}
3474  * @category Collection
3475  * @param {Object} obj - A collection to iterate over.
3476  * @param {number} limit - The maximum number of async operations at a time.
3477  * @param {Function} iteratee - A function to apply to each value in `obj`.
3478  * The iteratee is passed a `callback(err, transformed)` which must be called
3479  * once it has completed with an error (which can be `null`) and a
3480  * transformed value. Invoked with (value, key, callback).
3481  * @param {Function} [callback] - A callback which is called when all `iteratee`
3482  * functions have finished, or an error occurs. `result` is a new object consisting
3483  * of each key from `obj`, with each transformed value on the right-hand side.
3484  * Invoked with (err, result).
3485  */
3486 function mapValuesLimit(obj, limit, iteratee, callback) {
3487     callback = once(callback || noop);
3488     var newObj = {};
3489     eachOfLimit(obj, limit, function (val, key, next) {
3490         iteratee(val, key, function (err, result) {
3491             if (err) return next(err);
3492             newObj[key] = result;
3493             next();
3494         });
3495     }, function (err) {
3496         callback(err, newObj);
3497     });
3498 }
3499
3500 /**
3501  * A relative of [`map`]{@link module:Collections.map}, designed for use with objects.
3502  *
3503  * Produces a new Object by mapping each value of `obj` through the `iteratee`
3504  * function. The `iteratee` is called each `value` and `key` from `obj` and a
3505  * callback for when it has finished processing. Each of these callbacks takes
3506  * two arguments: an `error`, and the transformed item from `obj`. If `iteratee`
3507  * passes an error to its callback, the main `callback` (for the `mapValues`
3508  * function) is immediately called with the error.
3509  *
3510  * Note, the order of the keys in the result is not guaranteed.  The keys will
3511  * be roughly in the order they complete, (but this is very engine-specific)
3512  *
3513  * @name mapValues
3514  * @static
3515  * @memberOf module:Collections
3516  * @method
3517  * @category Collection
3518  * @param {Object} obj - A collection to iterate over.
3519  * @param {Function} iteratee - A function to apply to each value and key in
3520  * `coll`. The iteratee is passed a `callback(err, transformed)` which must be
3521  * called once it has completed with an error (which can be `null`) and a
3522  * transformed value. Invoked with (value, key, callback).
3523  * @param {Function} [callback] - A callback which is called when all `iteratee`
3524  * functions have finished, or an error occurs. `result` is a new object consisting
3525  * of each key from `obj`, with each transformed value on the right-hand side.
3526  * Invoked with (err, result).
3527  * @example
3528  *
3529  * async.mapValues({
3530  *     f1: 'file1',
3531  *     f2: 'file2',
3532  *     f3: 'file3'
3533  * }, function (file, key, callback) {
3534  *   fs.stat(file, callback);
3535  * }, function(err, result) {
3536  *     // result is now a map of stats for each file, e.g.
3537  *     // {
3538  *     //     f1: [stats for file1],
3539  *     //     f2: [stats for file2],
3540  *     //     f3: [stats for file3]
3541  *     // }
3542  * });
3543  */
3544
3545 var mapValues = doLimit(mapValuesLimit, Infinity);
3546
3547 /**
3548  * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time.
3549  *
3550  * @name mapValuesSeries
3551  * @static
3552  * @memberOf module:Collections
3553  * @method
3554  * @see [async.mapValues]{@link module:Collections.mapValues}
3555  * @category Collection
3556  * @param {Object} obj - A collection to iterate over.
3557  * @param {Function} iteratee - A function to apply to each value in `obj`.
3558  * The iteratee is passed a `callback(err, transformed)` which must be called
3559  * once it has completed with an error (which can be `null`) and a
3560  * transformed value. Invoked with (value, key, callback).
3561  * @param {Function} [callback] - A callback which is called when all `iteratee`
3562  * functions have finished, or an error occurs. `result` is a new object consisting
3563  * of each key from `obj`, with each transformed value on the right-hand side.
3564  * Invoked with (err, result).
3565  */
3566 var mapValuesSeries = doLimit(mapValuesLimit, 1);
3567
3568 function has(obj, key) {
3569     return key in obj;
3570 }
3571
3572 /**
3573  * Caches the results of an `async` function. When creating a hash to store
3574  * function results against, the callback is omitted from the hash and an
3575  * optional hash function can be used.
3576  *
3577  * If no hash function is specified, the first argument is used as a hash key,
3578  * which may work reasonably if it is a string or a data type that converts to a
3579  * distinct string. Note that objects and arrays will not behave reasonably.
3580  * Neither will cases where the other arguments are significant. In such cases,
3581  * specify your own hash function.
3582  *
3583  * The cache of results is exposed as the `memo` property of the function
3584  * returned by `memoize`.
3585  *
3586  * @name memoize
3587  * @static
3588  * @memberOf module:Utils
3589  * @method
3590  * @category Util
3591  * @param {Function} fn - The function to proxy and cache results from.
3592  * @param {Function} hasher - An optional function for generating a custom hash
3593  * for storing results. It has all the arguments applied to it apart from the
3594  * callback, and must be synchronous.
3595  * @returns {Function} a memoized version of `fn`
3596  * @example
3597  *
3598  * var slow_fn = function(name, callback) {
3599  *     // do something
3600  *     callback(null, result);
3601  * };
3602  * var fn = async.memoize(slow_fn);
3603  *
3604  * // fn can now be used as if it were slow_fn
3605  * fn('some name', function() {
3606  *     // callback
3607  * });
3608  */
3609 function memoize(fn, hasher) {
3610     var memo = Object.create(null);
3611     var queues = Object.create(null);
3612     hasher = hasher || identity;
3613     var memoized = initialParams(function memoized(args, callback) {
3614         var key = hasher.apply(null, args);
3615         if (has(memo, key)) {
3616             setImmediate$1(function () {
3617                 callback.apply(null, memo[key]);
3618             });
3619         } else if (has(queues, key)) {
3620             queues[key].push(callback);
3621         } else {
3622             queues[key] = [callback];
3623             fn.apply(null, args.concat(rest(function (args) {
3624                 memo[key] = args;
3625                 var q = queues[key];
3626                 delete queues[key];
3627                 for (var i = 0, l = q.length; i < l; i++) {
3628                     q[i].apply(null, args);
3629                 }
3630             })));
3631         }
3632     });
3633     memoized.memo = memo;
3634     memoized.unmemoized = fn;
3635     return memoized;
3636 }
3637
3638 /**
3639  * Calls `callback` on a later loop around the event loop. In Node.js this just
3640  * calls `setImmediate`.  In the browser it will use `setImmediate` if
3641  * available, otherwise `setTimeout(callback, 0)`, which means other higher
3642  * priority events may precede the execution of `callback`.
3643  *
3644  * This is used internally for browser-compatibility purposes.
3645  *
3646  * @name nextTick
3647  * @static
3648  * @memberOf module:Utils
3649  * @method
3650  * @alias setImmediate
3651  * @category Util
3652  * @param {Function} callback - The function to call on a later loop around
3653  * the event loop. Invoked with (args...).
3654  * @param {...*} args... - any number of additional arguments to pass to the
3655  * callback on the next tick.
3656  * @example
3657  *
3658  * var call_order = [];
3659  * async.nextTick(function() {
3660  *     call_order.push('two');
3661  *     // call_order now equals ['one','two']
3662  * });
3663  * call_order.push('one');
3664  *
3665  * async.setImmediate(function (a, b, c) {
3666  *     // a, b, and c equal 1, 2, and 3
3667  * }, 1, 2, 3);
3668  */
3669 var _defer$1;
3670
3671 if (hasNextTick) {
3672     _defer$1 = process.nextTick;
3673 } else if (hasSetImmediate) {
3674     _defer$1 = setImmediate;
3675 } else {
3676     _defer$1 = fallback;
3677 }
3678
3679 var nextTick = wrap(_defer$1);
3680
3681 function _parallel(eachfn, tasks, callback) {
3682     callback = callback || noop;
3683     var results = isArrayLike(tasks) ? [] : {};
3684
3685     eachfn(tasks, function (task, key, callback) {
3686         task(rest(function (err, args) {
3687             if (args.length <= 1) {
3688                 args = args[0];
3689             }
3690             results[key] = args;
3691             callback(err);
3692         }));
3693     }, function (err) {
3694         callback(err, results);
3695     });
3696 }
3697
3698 /**
3699  * Run the `tasks` collection of functions in parallel, without waiting until
3700  * the previous function has completed. If any of the functions pass an error to
3701  * its callback, the main `callback` is immediately called with the value of the
3702  * error. Once the `tasks` have completed, the results are passed to the final
3703  * `callback` as an array.
3704  *
3705  * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about
3706  * parallel execution of code.  If your tasks do not use any timers or perform
3707  * any I/O, they will actually be executed in series.  Any synchronous setup
3708  * sections for each task will happen one after the other.  JavaScript remains
3709  * single-threaded.
3710  *
3711  * It is also possible to use an object instead of an array. Each property will
3712  * be run as a function and the results will be passed to the final `callback`
3713  * as an object instead of an array. This can be a more readable way of handling
3714  * results from {@link async.parallel}.
3715  *
3716  * @name parallel
3717  * @static
3718  * @memberOf module:ControlFlow
3719  * @method
3720  * @category Control Flow
3721  * @param {Array|Iterable|Object} tasks - A collection containing functions to run.
3722  * Each function is passed a `callback(err, result)` which it must call on
3723  * completion with an error `err` (which can be `null`) and an optional `result`
3724  * value.
3725  * @param {Function} [callback] - An optional callback to run once all the
3726  * functions have completed successfully. This function gets a results array
3727  * (or object) containing all the result arguments passed to the task callbacks.
3728  * Invoked with (err, results).
3729  * @example
3730  * async.parallel([
3731  *     function(callback) {
3732  *         setTimeout(function() {
3733  *             callback(null, 'one');
3734  *         }, 200);
3735  *     },
3736  *     function(callback) {
3737  *         setTimeout(function() {
3738  *             callback(null, 'two');
3739  *         }, 100);
3740  *     }
3741  * ],
3742  * // optional callback
3743  * function(err, results) {
3744  *     // the results array will equal ['one','two'] even though
3745  *     // the second function had a shorter timeout.
3746  * });
3747  *
3748  * // an example using an object instead of an array
3749  * async.parallel({
3750  *     one: function(callback) {
3751  *         setTimeout(function() {
3752  *             callback(null, 1);
3753  *         }, 200);
3754  *     },
3755  *     two: function(callback) {
3756  *         setTimeout(function() {
3757  *             callback(null, 2);
3758  *         }, 100);
3759  *     }
3760  * }, function(err, results) {
3761  *     // results is now equals to: {one: 1, two: 2}
3762  * });
3763  */
3764 function parallelLimit(tasks, callback) {
3765   _parallel(eachOf, tasks, callback);
3766 }
3767
3768 /**
3769  * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a
3770  * time.
3771  *
3772  * @name parallelLimit
3773  * @static
3774  * @memberOf module:ControlFlow
3775  * @method
3776  * @see [async.parallel]{@link module:ControlFlow.parallel}
3777  * @category Control Flow
3778  * @param {Array|Collection} tasks - A collection containing functions to run.
3779  * Each function is passed a `callback(err, result)` which it must call on
3780  * completion with an error `err` (which can be `null`) and an optional `result`
3781  * value.
3782  * @param {number} limit - The maximum number of async operations at a time.
3783  * @param {Function} [callback] - An optional callback to run once all the
3784  * functions have completed successfully. This function gets a results array
3785  * (or object) containing all the result arguments passed to the task callbacks.
3786  * Invoked with (err, results).
3787  */
3788 function parallelLimit$1(tasks, limit, callback) {
3789   _parallel(_eachOfLimit(limit), tasks, callback);
3790 }
3791
3792 /**
3793  * A queue of tasks for the worker function to complete.
3794  * @typedef {Object} QueueObject
3795  * @memberOf module:ControlFlow
3796  * @property {Function} length - a function returning the number of items
3797  * waiting to be processed. Invoke with `queue.length()`.
3798  * @property {boolean} started - a boolean indicating whether or not any
3799  * items have been pushed and processed by the queue.
3800  * @property {Function} running - a function returning the number of items
3801  * currently being processed. Invoke with `queue.running()`.
3802  * @property {Function} workersList - a function returning the array of items
3803  * currently being processed. Invoke with `queue.workersList()`.
3804  * @property {Function} idle - a function returning false if there are items
3805  * waiting or being processed, or true if not. Invoke with `queue.idle()`.
3806  * @property {number} concurrency - an integer for determining how many `worker`
3807  * functions should be run in parallel. This property can be changed after a
3808  * `queue` is created to alter the concurrency on-the-fly.
3809  * @property {Function} push - add a new task to the `queue`. Calls `callback`
3810  * once the `worker` has finished processing the task. Instead of a single task,
3811  * a `tasks` array can be submitted. The respective callback is used for every
3812  * task in the list. Invoke with `queue.push(task, [callback])`,
3813  * @property {Function} unshift - add a new task to the front of the `queue`.
3814  * Invoke with `queue.unshift(task, [callback])`.
3815  * @property {Function} saturated - a callback that is called when the number of
3816  * running workers hits the `concurrency` limit, and further tasks will be
3817  * queued.
3818  * @property {Function} unsaturated - a callback that is called when the number
3819  * of running workers is less than the `concurrency` & `buffer` limits, and
3820  * further tasks will not be queued.
3821  * @property {number} buffer - A minimum threshold buffer in order to say that
3822  * the `queue` is `unsaturated`.
3823  * @property {Function} empty - a callback that is called when the last item
3824  * from the `queue` is given to a `worker`.
3825  * @property {Function} drain - a callback that is called when the last item
3826  * from the `queue` has returned from the `worker`.
3827  * @property {Function} error - a callback that is called when a task errors.
3828  * Has the signature `function(error, task)`.
3829  * @property {boolean} paused - a boolean for determining whether the queue is
3830  * in a paused state.
3831  * @property {Function} pause - a function that pauses the processing of tasks
3832  * until `resume()` is called. Invoke with `queue.pause()`.
3833  * @property {Function} resume - a function that resumes the processing of
3834  * queued tasks when the queue is paused. Invoke with `queue.resume()`.
3835  * @property {Function} kill - a function that removes the `drain` callback and
3836  * empties remaining tasks from the queue forcing it to go idle. Invoke with `queue.kill()`.
3837  */
3838
3839 /**
3840  * Creates a `queue` object with the specified `concurrency`. Tasks added to the
3841  * `queue` are processed in parallel (up to the `concurrency` limit). If all
3842  * `worker`s are in progress, the task is queued until one becomes available.
3843  * Once a `worker` completes a `task`, that `task`'s callback is called.
3844  *
3845  * @name queue
3846  * @static
3847  * @memberOf module:ControlFlow
3848  * @method
3849  * @category Control Flow
3850  * @param {Function} worker - An asynchronous function for processing a queued
3851  * task, which must call its `callback(err)` argument when finished, with an
3852  * optional `error` as an argument.  If you want to handle errors from an
3853  * individual task, pass a callback to `q.push()`. Invoked with
3854  * (task, callback).
3855  * @param {number} [concurrency=1] - An `integer` for determining how many
3856  * `worker` functions should be run in parallel.  If omitted, the concurrency
3857  * defaults to `1`.  If the concurrency is `0`, an error is thrown.
3858  * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can
3859  * attached as certain properties to listen for specific events during the
3860  * lifecycle of the queue.
3861  * @example
3862  *
3863  * // create a queue object with concurrency 2
3864  * var q = async.queue(function(task, callback) {
3865  *     console.log('hello ' + task.name);
3866  *     callback();
3867  * }, 2);
3868  *
3869  * // assign a callback
3870  * q.drain = function() {
3871  *     console.log('all items have been processed');
3872  * };
3873  *
3874  * // add some items to the queue
3875  * q.push({name: 'foo'}, function(err) {
3876  *     console.log('finished processing foo');
3877  * });
3878  * q.push({name: 'bar'}, function (err) {
3879  *     console.log('finished processing bar');
3880  * });
3881  *
3882  * // add some items to the queue (batch-wise)
3883  * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
3884  *     console.log('finished processing item');
3885  * });
3886  *
3887  * // add some items to the front of the queue
3888  * q.unshift({name: 'bar'}, function (err) {
3889  *     console.log('finished processing bar');
3890  * });
3891  */
3892 var queue$1 = function (worker, concurrency) {
3893   return queue(function (items, cb) {
3894     worker(items[0], cb);
3895   }, concurrency, 1);
3896 };
3897
3898 /**
3899  * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and
3900  * completed in ascending priority order.
3901  *
3902  * @name priorityQueue
3903  * @static
3904  * @memberOf module:ControlFlow
3905  * @method
3906  * @see [async.queue]{@link module:ControlFlow.queue}
3907  * @category Control Flow
3908  * @param {Function} worker - An asynchronous function for processing a queued
3909  * task, which must call its `callback(err)` argument when finished, with an
3910  * optional `error` as an argument.  If you want to handle errors from an
3911  * individual task, pass a callback to `q.push()`. Invoked with
3912  * (task, callback).
3913  * @param {number} concurrency - An `integer` for determining how many `worker`
3914  * functions should be run in parallel.  If omitted, the concurrency defaults to
3915  * `1`.  If the concurrency is `0`, an error is thrown.
3916  * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two
3917  * differences between `queue` and `priorityQueue` objects:
3918  * * `push(task, priority, [callback])` - `priority` should be a number. If an
3919  *   array of `tasks` is given, all tasks will be assigned the same priority.
3920  * * The `unshift` method was removed.
3921  */
3922 var priorityQueue = function (worker, concurrency) {
3923     // Start with a normal queue
3924     var q = queue$1(worker, concurrency);
3925
3926     // Override push to accept second parameter representing priority
3927     q.push = function (data, priority, callback) {
3928         if (callback == null) callback = noop;
3929         if (typeof callback !== 'function') {
3930             throw new Error('task callback must be a function');
3931         }
3932         q.started = true;
3933         if (!isArray(data)) {
3934             data = [data];
3935         }
3936         if (data.length === 0) {
3937             // call drain immediately if there are no tasks
3938             return setImmediate$1(function () {
3939                 q.drain();
3940             });
3941         }
3942
3943         priority = priority || 0;
3944         var nextNode = q._tasks.head;
3945         while (nextNode && priority >= nextNode.priority) {
3946             nextNode = nextNode.next;
3947         }
3948
3949         for (var i = 0, l = data.length; i < l; i++) {
3950             var item = {
3951                 data: data[i],
3952                 priority: priority,
3953                 callback: callback
3954             };
3955
3956             if (nextNode) {
3957                 q._tasks.insertBefore(nextNode, item);
3958             } else {
3959                 q._tasks.push(item);
3960             }
3961         }
3962         setImmediate$1(q.process);
3963     };
3964
3965     // Remove unshift function
3966     delete q.unshift;
3967
3968     return q;
3969 };
3970
3971 /**
3972  * Runs the `tasks` array of functions in parallel, without waiting until the
3973  * previous function has completed. Once any of the `tasks` complete or pass an
3974  * error to its callback, the main `callback` is immediately called. It's
3975  * equivalent to `Promise.race()`.
3976  *
3977  * @name race
3978  * @static
3979  * @memberOf module:ControlFlow
3980  * @method
3981  * @category Control Flow
3982  * @param {Array} tasks - An array containing functions to run. Each function
3983  * is passed a `callback(err, result)` which it must call on completion with an
3984  * error `err` (which can be `null`) and an optional `result` value.
3985  * @param {Function} callback - A callback to run once any of the functions have
3986  * completed. This function gets an error or result from the first function that
3987  * completed. Invoked with (err, result).
3988  * @returns undefined
3989  * @example
3990  *
3991  * async.race([
3992  *     function(callback) {
3993  *         setTimeout(function() {
3994  *             callback(null, 'one');
3995  *         }, 200);
3996  *     },
3997  *     function(callback) {
3998  *         setTimeout(function() {
3999  *             callback(null, 'two');
4000  *         }, 100);
4001  *     }
4002  * ],
4003  * // main callback
4004  * function(err, result) {
4005  *     // the result will be equal to 'two' as it finishes earlier
4006  * });
4007  */
4008 function race(tasks, callback) {
4009     callback = once(callback || noop);
4010     if (!isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));
4011     if (!tasks.length) return callback();
4012     for (var i = 0, l = tasks.length; i < l; i++) {
4013         tasks[i](callback);
4014     }
4015 }
4016
4017 var slice = Array.prototype.slice;
4018
4019 /**
4020  * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order.
4021  *
4022  * @name reduceRight
4023  * @static
4024  * @memberOf module:Collections
4025  * @method
4026  * @see [async.reduce]{@link module:Collections.reduce}
4027  * @alias foldr
4028  * @category Collection
4029  * @param {Array} array - A collection to iterate over.
4030  * @param {*} memo - The initial state of the reduction.
4031  * @param {Function} iteratee - A function applied to each item in the
4032  * array to produce the next step in the reduction. The `iteratee` is passed a
4033  * `callback(err, reduction)` which accepts an optional error as its first
4034  * argument, and the state of the reduction as the second. If an error is
4035  * passed to the callback, the reduction is stopped and the main `callback` is
4036  * immediately called with the error. Invoked with (memo, item, callback).
4037  * @param {Function} [callback] - A callback which is called after all the
4038  * `iteratee` functions have finished. Result is the reduced value. Invoked with
4039  * (err, result).
4040  */
4041 function reduceRight(array, memo, iteratee, callback) {
4042   var reversed = slice.call(array).reverse();
4043   reduce(reversed, memo, iteratee, callback);
4044 }
4045
4046 /**
4047  * Wraps the function in another function that always returns data even when it
4048  * errors.
4049  *
4050  * The object returned has either the property `error` or `value`.
4051  *
4052  * @name reflect
4053  * @static
4054  * @memberOf module:Utils
4055  * @method
4056  * @category Util
4057  * @param {Function} fn - The function you want to wrap
4058  * @returns {Function} - A function that always passes null to it's callback as
4059  * the error. The second argument to the callback will be an `object` with
4060  * either an `error` or a `value` property.
4061  * @example
4062  *
4063  * async.parallel([
4064  *     async.reflect(function(callback) {
4065  *         // do some stuff ...
4066  *         callback(null, 'one');
4067  *     }),
4068  *     async.reflect(function(callback) {
4069  *         // do some more stuff but error ...
4070  *         callback('bad stuff happened');
4071  *     }),
4072  *     async.reflect(function(callback) {
4073  *         // do some more stuff ...
4074  *         callback(null, 'two');
4075  *     })
4076  * ],
4077  * // optional callback
4078  * function(err, results) {
4079  *     // values
4080  *     // results[0].value = 'one'
4081  *     // results[1].error = 'bad stuff happened'
4082  *     // results[2].value = 'two'
4083  * });
4084  */
4085 function reflect(fn) {
4086     return initialParams(function reflectOn(args, reflectCallback) {
4087         args.push(rest(function callback(err, cbArgs) {
4088             if (err) {
4089                 reflectCallback(null, {
4090                     error: err
4091                 });
4092             } else {
4093                 var value = null;
4094                 if (cbArgs.length === 1) {
4095                     value = cbArgs[0];
4096                 } else if (cbArgs.length > 1) {
4097                     value = cbArgs;
4098                 }
4099                 reflectCallback(null, {
4100                     value: value
4101                 });
4102             }
4103         }));
4104
4105         return fn.apply(this, args);
4106     });
4107 }
4108
4109 function reject$1(eachfn, arr, iteratee, callback) {
4110     _filter(eachfn, arr, function (value, cb) {
4111         iteratee(value, function (err, v) {
4112             cb(err, !v);
4113         });
4114     }, callback);
4115 }
4116
4117 /**
4118  * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.
4119  *
4120  * @name reject
4121  * @static
4122  * @memberOf module:Collections
4123  * @method
4124  * @see [async.filter]{@link module:Collections.filter}
4125  * @category Collection
4126  * @param {Array|Iterable|Object} coll - A collection to iterate over.
4127  * @param {Function} iteratee - A truth test to apply to each item in `coll`.
4128  * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
4129  * with a boolean argument once it has completed. Invoked with (item, callback).
4130  * @param {Function} [callback] - A callback which is called after all the
4131  * `iteratee` functions have finished. Invoked with (err, results).
4132  * @example
4133  *
4134  * async.reject(['file1','file2','file3'], function(filePath, callback) {
4135  *     fs.access(filePath, function(err) {
4136  *         callback(null, !err)
4137  *     });
4138  * }, function(err, results) {
4139  *     // results now equals an array of missing files
4140  *     createFiles(results);
4141  * });
4142  */
4143 var reject = doParallel(reject$1);
4144
4145 /**
4146  * A helper function that wraps an array or an object of functions with reflect.
4147  *
4148  * @name reflectAll
4149  * @static
4150  * @memberOf module:Utils
4151  * @method
4152  * @see [async.reflect]{@link module:Utils.reflect}
4153  * @category Util
4154  * @param {Array} tasks - The array of functions to wrap in `async.reflect`.
4155  * @returns {Array} Returns an array of functions, each function wrapped in
4156  * `async.reflect`
4157  * @example
4158  *
4159  * let tasks = [
4160  *     function(callback) {
4161  *         setTimeout(function() {
4162  *             callback(null, 'one');
4163  *         }, 200);
4164  *     },
4165  *     function(callback) {
4166  *         // do some more stuff but error ...
4167  *         callback(new Error('bad stuff happened'));
4168  *     },
4169  *     function(callback) {
4170  *         setTimeout(function() {
4171  *             callback(null, 'two');
4172  *         }, 100);
4173  *     }
4174  * ];
4175  *
4176  * async.parallel(async.reflectAll(tasks),
4177  * // optional callback
4178  * function(err, results) {
4179  *     // values
4180  *     // results[0].value = 'one'
4181  *     // results[1].error = Error('bad stuff happened')
4182  *     // results[2].value = 'two'
4183  * });
4184  *
4185  * // an example using an object instead of an array
4186  * let tasks = {
4187  *     one: function(callback) {
4188  *         setTimeout(function() {
4189  *             callback(null, 'one');
4190  *         }, 200);
4191  *     },
4192  *     two: function(callback) {
4193  *         callback('two');
4194  *     },
4195  *     three: function(callback) {
4196  *         setTimeout(function() {
4197  *             callback(null, 'three');
4198  *         }, 100);
4199  *     }
4200  * };
4201  *
4202  * async.parallel(async.reflectAll(tasks),
4203  * // optional callback
4204  * function(err, results) {
4205  *     // values
4206  *     // results.one.value = 'one'
4207  *     // results.two.error = 'two'
4208  *     // results.three.value = 'three'
4209  * });
4210  */
4211 function reflectAll(tasks) {
4212     var results;
4213     if (isArray(tasks)) {
4214         results = arrayMap(tasks, reflect);
4215     } else {
4216         results = {};
4217         baseForOwn(tasks, function (task, key) {
4218             results[key] = reflect.call(this, task);
4219         });
4220     }
4221     return results;
4222 }
4223
4224 /**
4225  * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a
4226  * time.
4227  *
4228  * @name rejectLimit
4229  * @static
4230  * @memberOf module:Collections
4231  * @method
4232  * @see [async.reject]{@link module:Collections.reject}
4233  * @category Collection
4234  * @param {Array|Iterable|Object} coll - A collection to iterate over.
4235  * @param {number} limit - The maximum number of async operations at a time.
4236  * @param {Function} iteratee - A truth test to apply to each item in `coll`.
4237  * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
4238  * with a boolean argument once it has completed. Invoked with (item, callback).
4239  * @param {Function} [callback] - A callback which is called after all the
4240  * `iteratee` functions have finished. Invoked with (err, results).
4241  */
4242 var rejectLimit = doParallelLimit(reject$1);
4243
4244 /**
4245  * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.
4246  *
4247  * @name rejectSeries
4248  * @static
4249  * @memberOf module:Collections
4250  * @method
4251  * @see [async.reject]{@link module:Collections.reject}
4252  * @category Collection
4253  * @param {Array|Iterable|Object} coll - A collection to iterate over.
4254  * @param {Function} iteratee - A truth test to apply to each item in `coll`.
4255  * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
4256  * with a boolean argument once it has completed. Invoked with (item, callback).
4257  * @param {Function} [callback] - A callback which is called after all the
4258  * `iteratee` functions have finished. Invoked with (err, results).
4259  */
4260 var rejectSeries = doLimit(rejectLimit, 1);
4261
4262 /**
4263  * Creates a function that returns `value`.
4264  *
4265  * @static
4266  * @memberOf _
4267  * @since 2.4.0
4268  * @category Util
4269  * @param {*} value The value to return from the new function.
4270  * @returns {Function} Returns the new constant function.
4271  * @example
4272  *
4273  * var objects = _.times(2, _.constant({ 'a': 1 }));
4274  *
4275  * console.log(objects);
4276  * // => [{ 'a': 1 }, { 'a': 1 }]
4277  *
4278  * console.log(objects[0] === objects[1]);
4279  * // => true
4280  */
4281 function constant$1(value) {
4282   return function() {
4283     return value;
4284   };
4285 }
4286
4287 /**
4288  * Attempts to get a successful response from `task` no more than `times` times
4289  * before returning an error. If the task is successful, the `callback` will be
4290  * passed the result of the successful task. If all attempts fail, the callback
4291  * will be passed the error and result (if any) of the final attempt.
4292  *
4293  * @name retry
4294  * @static
4295  * @memberOf module:ControlFlow
4296  * @method
4297  * @category Control Flow
4298  * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an
4299  * object with `times` and `interval` or a number.
4300  * * `times` - The number of attempts to make before giving up.  The default
4301  *   is `5`.
4302  * * `interval` - The time to wait between retries, in milliseconds.  The
4303  *   default is `0`. The interval may also be specified as a function of the
4304  *   retry count (see example).
4305  * * `errorFilter` - An optional synchronous function that is invoked on
4306  *   erroneous result. If it returns `true` the retry attempts will continue;
4307  *   if the function returns `false` the retry flow is aborted with the current
4308  *   attempt's error and result being returned to the final callback.
4309  *   Invoked with (err).
4310  * * If `opts` is a number, the number specifies the number of times to retry,
4311  *   with the default interval of `0`.
4312  * @param {Function} task - A function which receives two arguments: (1) a
4313  * `callback(err, result)` which must be called when finished, passing `err`
4314  * (which can be `null`) and the `result` of the function's execution, and (2)
4315  * a `results` object, containing the results of the previously executed
4316  * functions (if nested inside another control flow). Invoked with
4317  * (callback, results).
4318  * @param {Function} [callback] - An optional callback which is called when the
4319  * task has succeeded, or after the final failed attempt. It receives the `err`
4320  * and `result` arguments of the last attempt at completing the `task`. Invoked
4321  * with (err, results).
4322  * @example
4323  *
4324  * // The `retry` function can be used as a stand-alone control flow by passing
4325  * // a callback, as shown below:
4326  *
4327  * // try calling apiMethod 3 times
4328  * async.retry(3, apiMethod, function(err, result) {
4329  *     // do something with the result
4330  * });
4331  *
4332  * // try calling apiMethod 3 times, waiting 200 ms between each retry
4333  * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
4334  *     // do something with the result
4335  * });
4336  *
4337  * // try calling apiMethod 10 times with exponential backoff
4338  * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)
4339  * async.retry({
4340  *   times: 10,
4341  *   interval: function(retryCount) {
4342  *     return 50 * Math.pow(2, retryCount);
4343  *   }
4344  * }, apiMethod, function(err, result) {
4345  *     // do something with the result
4346  * });
4347  *
4348  * // try calling apiMethod the default 5 times no delay between each retry
4349  * async.retry(apiMethod, function(err, result) {
4350  *     // do something with the result
4351  * });
4352  *
4353  * // try calling apiMethod only when error condition satisfies, all other
4354  * // errors will abort the retry control flow and return to final callback
4355  * async.retry({
4356  *   errorFilter: function(err) {
4357  *     return err.message === 'Temporary error'; // only retry on a specific error
4358  *   }
4359  * }, apiMethod, function(err, result) {
4360  *     // do something with the result
4361  * });
4362  *
4363  * // It can also be embedded within other control flow functions to retry
4364  * // individual methods that are not as reliable, like this:
4365  * async.auto({
4366  *     users: api.getUsers.bind(api),
4367  *     payments: async.retry(3, api.getPayments.bind(api))
4368  * }, function(err, results) {
4369  *     // do something with the results
4370  * });
4371  *
4372  */
4373 function retry(opts, task, callback) {
4374     var DEFAULT_TIMES = 5;
4375     var DEFAULT_INTERVAL = 0;
4376
4377     var options = {
4378         times: DEFAULT_TIMES,
4379         intervalFunc: constant$1(DEFAULT_INTERVAL)
4380     };
4381
4382     function parseTimes(acc, t) {
4383         if (typeof t === 'object') {
4384             acc.times = +t.times || DEFAULT_TIMES;
4385
4386             acc.intervalFunc = typeof t.interval === 'function' ? t.interval : constant$1(+t.interval || DEFAULT_INTERVAL);
4387
4388             acc.errorFilter = t.errorFilter;
4389         } else if (typeof t === 'number' || typeof t === 'string') {
4390             acc.times = +t || DEFAULT_TIMES;
4391         } else {
4392             throw new Error("Invalid arguments for async.retry");
4393         }
4394     }
4395
4396     if (arguments.length < 3 && typeof opts === 'function') {
4397         callback = task || noop;
4398         task = opts;
4399     } else {
4400         parseTimes(options, opts);
4401         callback = callback || noop;
4402     }
4403
4404     if (typeof task !== 'function') {
4405         throw new Error("Invalid arguments for async.retry");
4406     }
4407
4408     var attempt = 1;
4409     function retryAttempt() {
4410         task(function (err) {
4411             if (err && attempt++ < options.times && (typeof options.errorFilter != 'function' || options.errorFilter(err))) {
4412                 setTimeout(retryAttempt, options.intervalFunc(attempt));
4413             } else {
4414                 callback.apply(null, arguments);
4415             }
4416         });
4417     }
4418
4419     retryAttempt();
4420 }
4421
4422 /**
4423  * A close relative of [`retry`]{@link module:ControlFlow.retry}.  This method wraps a task and makes it
4424  * retryable, rather than immediately calling it with retries.
4425  *
4426  * @name retryable
4427  * @static
4428  * @memberOf module:ControlFlow
4429  * @method
4430  * @see [async.retry]{@link module:ControlFlow.retry}
4431  * @category Control Flow
4432  * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional
4433  * options, exactly the same as from `retry`
4434  * @param {Function} task - the asynchronous function to wrap
4435  * @returns {Functions} The wrapped function, which when invoked, will retry on
4436  * an error, based on the parameters specified in `opts`.
4437  * @example
4438  *
4439  * async.auto({
4440  *     dep1: async.retryable(3, getFromFlakyService),
4441  *     process: ["dep1", async.retryable(3, function (results, cb) {
4442  *         maybeProcessData(results.dep1, cb);
4443  *     })]
4444  * }, callback);
4445  */
4446 var retryable = function (opts, task) {
4447     if (!task) {
4448         task = opts;
4449         opts = null;
4450     }
4451     return initialParams(function (args, callback) {
4452         function taskFn(cb) {
4453             task.apply(null, args.concat(cb));
4454         }
4455
4456         if (opts) retry(opts, taskFn, callback);else retry(taskFn, callback);
4457     });
4458 };
4459
4460 /**
4461  * Run the functions in the `tasks` collection in series, each one running once
4462  * the previous function has completed. If any functions in the series pass an
4463  * error to its callback, no more functions are run, and `callback` is
4464  * immediately called with the value of the error. Otherwise, `callback`
4465  * receives an array of results when `tasks` have completed.
4466  *
4467  * It is also possible to use an object instead of an array. Each property will
4468  * be run as a function, and the results will be passed to the final `callback`
4469  * as an object instead of an array. This can be a more readable way of handling
4470  *  results from {@link async.series}.
4471  *
4472  * **Note** that while many implementations preserve the order of object
4473  * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
4474  * explicitly states that
4475  *
4476  * > The mechanics and order of enumerating the properties is not specified.
4477  *
4478  * So if you rely on the order in which your series of functions are executed,
4479  * and want this to work on all platforms, consider using an array.
4480  *
4481  * @name series
4482  * @static
4483  * @memberOf module:ControlFlow
4484  * @method
4485  * @category Control Flow
4486  * @param {Array|Iterable|Object} tasks - A collection containing functions to run, each
4487  * function is passed a `callback(err, result)` it must call on completion with
4488  * an error `err` (which can be `null`) and an optional `result` value.
4489  * @param {Function} [callback] - An optional callback to run once all the
4490  * functions have completed. This function gets a results array (or object)
4491  * containing all the result arguments passed to the `task` callbacks. Invoked
4492  * with (err, result).
4493  * @example
4494  * async.series([
4495  *     function(callback) {
4496  *         // do some stuff ...
4497  *         callback(null, 'one');
4498  *     },
4499  *     function(callback) {
4500  *         // do some more stuff ...
4501  *         callback(null, 'two');
4502  *     }
4503  * ],
4504  * // optional callback
4505  * function(err, results) {
4506  *     // results is now equal to ['one', 'two']
4507  * });
4508  *
4509  * async.series({
4510  *     one: function(callback) {
4511  *         setTimeout(function() {
4512  *             callback(null, 1);
4513  *         }, 200);
4514  *     },
4515  *     two: function(callback){
4516  *         setTimeout(function() {
4517  *             callback(null, 2);
4518  *         }, 100);
4519  *     }
4520  * }, function(err, results) {
4521  *     // results is now equal to: {one: 1, two: 2}
4522  * });
4523  */
4524 function series(tasks, callback) {
4525   _parallel(eachOfSeries, tasks, callback);
4526 }
4527
4528 /**
4529  * Returns `true` if at least one element in the `coll` satisfies an async test.
4530  * If any iteratee call returns `true`, the main `callback` is immediately
4531  * called.
4532  *
4533  * @name some
4534  * @static
4535  * @memberOf module:Collections
4536  * @method
4537  * @alias any
4538  * @category Collection
4539  * @param {Array|Iterable|Object} coll - A collection to iterate over.
4540  * @param {Function} iteratee - A truth test to apply to each item in the array
4541  * in parallel. The iteratee is passed a `callback(err, truthValue)` which must
4542  * be called with a boolean argument once it has completed. Invoked with
4543  * (item, callback).
4544  * @param {Function} [callback] - A callback which is called as soon as any
4545  * iteratee returns `true`, or after all the iteratee functions have finished.
4546  * Result will be either `true` or `false` depending on the values of the async
4547  * tests. Invoked with (err, result).
4548  * @example
4549  *
4550  * async.some(['file1','file2','file3'], function(filePath, callback) {
4551  *     fs.access(filePath, function(err) {
4552  *         callback(null, !err)
4553  *     });
4554  * }, function(err, result) {
4555  *     // if result is true then at least one of the files exists
4556  * });
4557  */
4558 var some = doParallel(_createTester(Boolean, identity));
4559
4560 /**
4561  * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.
4562  *
4563  * @name someLimit
4564  * @static
4565  * @memberOf module:Collections
4566  * @method
4567  * @see [async.some]{@link module:Collections.some}
4568  * @alias anyLimit
4569  * @category Collection
4570  * @param {Array|Iterable|Object} coll - A collection to iterate over.
4571  * @param {number} limit - The maximum number of async operations at a time.
4572  * @param {Function} iteratee - A truth test to apply to each item in the array
4573  * in parallel. The iteratee is passed a `callback(err, truthValue)` which must
4574  * be called with a boolean argument once it has completed. Invoked with
4575  * (item, callback).
4576  * @param {Function} [callback] - A callback which is called as soon as any
4577  * iteratee returns `true`, or after all the iteratee functions have finished.
4578  * Result will be either `true` or `false` depending on the values of the async
4579  * tests. Invoked with (err, result).
4580  */
4581 var someLimit = doParallelLimit(_createTester(Boolean, identity));
4582
4583 /**
4584  * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.
4585  *
4586  * @name someSeries
4587  * @static
4588  * @memberOf module:Collections
4589  * @method
4590  * @see [async.some]{@link module:Collections.some}
4591  * @alias anySeries
4592  * @category Collection
4593  * @param {Array|Iterable|Object} coll - A collection to iterate over.
4594  * @param {Function} iteratee - A truth test to apply to each item in the array
4595  * in parallel. The iteratee is passed a `callback(err, truthValue)` which must
4596  * be called with a boolean argument once it has completed. Invoked with
4597  * (item, callback).
4598  * @param {Function} [callback] - A callback which is called as soon as any
4599  * iteratee returns `true`, or after all the iteratee functions have finished.
4600  * Result will be either `true` or `false` depending on the values of the async
4601  * tests. Invoked with (err, result).
4602  */
4603 var someSeries = doLimit(someLimit, 1);
4604
4605 /**
4606  * Sorts a list by the results of running each `coll` value through an async
4607  * `iteratee`.
4608  *
4609  * @name sortBy
4610  * @static
4611  * @memberOf module:Collections
4612  * @method
4613  * @category Collection
4614  * @param {Array|Iterable|Object} coll - A collection to iterate over.
4615  * @param {Function} iteratee - A function to apply to each item in `coll`.
4616  * The iteratee is passed a `callback(err, sortValue)` which must be called once
4617  * it has completed with an error (which can be `null`) and a value to use as
4618  * the sort criteria. Invoked with (item, callback).
4619  * @param {Function} callback - A callback which is called after all the
4620  * `iteratee` functions have finished, or an error occurs. Results is the items
4621  * from the original `coll` sorted by the values returned by the `iteratee`
4622  * calls. Invoked with (err, results).
4623  * @example
4624  *
4625  * async.sortBy(['file1','file2','file3'], function(file, callback) {
4626  *     fs.stat(file, function(err, stats) {
4627  *         callback(err, stats.mtime);
4628  *     });
4629  * }, function(err, results) {
4630  *     // results is now the original array of files sorted by
4631  *     // modified date
4632  * });
4633  *
4634  * // By modifying the callback parameter the
4635  * // sorting order can be influenced:
4636  *
4637  * // ascending order
4638  * async.sortBy([1,9,3,5], function(x, callback) {
4639  *     callback(null, x);
4640  * }, function(err,result) {
4641  *     // result callback
4642  * });
4643  *
4644  * // descending order
4645  * async.sortBy([1,9,3,5], function(x, callback) {
4646  *     callback(null, x*-1);    //<- x*-1 instead of x, turns the order around
4647  * }, function(err,result) {
4648  *     // result callback
4649  * });
4650  */
4651 function sortBy(coll, iteratee, callback) {
4652     map(coll, function (x, callback) {
4653         iteratee(x, function (err, criteria) {
4654             if (err) return callback(err);
4655             callback(null, { value: x, criteria: criteria });
4656         });
4657     }, function (err, results) {
4658         if (err) return callback(err);
4659         callback(null, arrayMap(results.sort(comparator), baseProperty('value')));
4660     });
4661
4662     function comparator(left, right) {
4663         var a = left.criteria,
4664             b = right.criteria;
4665         return a < b ? -1 : a > b ? 1 : 0;
4666     }
4667 }
4668
4669 /**
4670  * Sets a time limit on an asynchronous function. If the function does not call
4671  * its callback within the specified milliseconds, it will be called with a
4672  * timeout error. The code property for the error object will be `'ETIMEDOUT'`.
4673  *
4674  * @name timeout
4675  * @static
4676  * @memberOf module:Utils
4677  * @method
4678  * @category Util
4679  * @param {Function} asyncFn - The asynchronous function you want to set the
4680  * time limit.
4681  * @param {number} milliseconds - The specified time limit.
4682  * @param {*} [info] - Any variable you want attached (`string`, `object`, etc)
4683  * to timeout Error for more information..
4684  * @returns {Function} Returns a wrapped function that can be used with any of
4685  * the control flow functions. Invoke this function with the same
4686  * parameters as you would `asyncFunc`.
4687  * @example
4688  *
4689  * function myFunction(foo, callback) {
4690  *     doAsyncTask(foo, function(err, data) {
4691  *         // handle errors
4692  *         if (err) return callback(err);
4693  *
4694  *         // do some stuff ...
4695  *
4696  *         // return processed data
4697  *         return callback(null, data);
4698  *     });
4699  * }
4700  *
4701  * var wrapped = async.timeout(myFunction, 1000);
4702  *
4703  * // call `wrapped` as you would `myFunction`
4704  * wrapped({ bar: 'bar' }, function(err, data) {
4705  *     // if `myFunction` takes < 1000 ms to execute, `err`
4706  *     // and `data` will have their expected values
4707  *
4708  *     // else `err` will be an Error with the code 'ETIMEDOUT'
4709  * });
4710  */
4711 function timeout(asyncFn, milliseconds, info) {
4712     var originalCallback, timer;
4713     var timedOut = false;
4714
4715     function injectedCallback() {
4716         if (!timedOut) {
4717             originalCallback.apply(null, arguments);
4718             clearTimeout(timer);
4719         }
4720     }
4721
4722     function timeoutCallback() {
4723         var name = asyncFn.name || 'anonymous';
4724         var error = new Error('Callback function "' + name + '" timed out.');
4725         error.code = 'ETIMEDOUT';
4726         if (info) {
4727             error.info = info;
4728         }
4729         timedOut = true;
4730         originalCallback(error);
4731     }
4732
4733     return initialParams(function (args, origCallback) {
4734         originalCallback = origCallback;
4735         // setup timer and call original function
4736         timer = setTimeout(timeoutCallback, milliseconds);
4737         asyncFn.apply(null, args.concat(injectedCallback));
4738     });
4739 }
4740
4741 /* Built-in method references for those with the same name as other `lodash` methods. */
4742 var nativeCeil = Math.ceil;
4743 var nativeMax$1 = Math.max;
4744
4745 /**
4746  * The base implementation of `_.range` and `_.rangeRight` which doesn't
4747  * coerce arguments.
4748  *
4749  * @private
4750  * @param {number} start The start of the range.
4751  * @param {number} end The end of the range.
4752  * @param {number} step The value to increment or decrement by.
4753  * @param {boolean} [fromRight] Specify iterating from right to left.
4754  * @returns {Array} Returns the range of numbers.
4755  */
4756 function baseRange(start, end, step, fromRight) {
4757   var index = -1,
4758       length = nativeMax$1(nativeCeil((end - start) / (step || 1)), 0),
4759       result = Array(length);
4760
4761   while (length--) {
4762     result[fromRight ? length : ++index] = start;
4763     start += step;
4764   }
4765   return result;
4766 }
4767
4768 /**
4769  * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a
4770  * time.
4771  *
4772  * @name timesLimit
4773  * @static
4774  * @memberOf module:ControlFlow
4775  * @method
4776  * @see [async.times]{@link module:ControlFlow.times}
4777  * @category Control Flow
4778  * @param {number} count - The number of times to run the function.
4779  * @param {number} limit - The maximum number of async operations at a time.
4780  * @param {Function} iteratee - The function to call `n` times. Invoked with the
4781  * iteration index and a callback (n, next).
4782  * @param {Function} callback - see [async.map]{@link module:Collections.map}.
4783  */
4784 function timeLimit(count, limit, iteratee, callback) {
4785   mapLimit(baseRange(0, count, 1), limit, iteratee, callback);
4786 }
4787
4788 /**
4789  * Calls the `iteratee` function `n` times, and accumulates results in the same
4790  * manner you would use with [map]{@link module:Collections.map}.
4791  *
4792  * @name times
4793  * @static
4794  * @memberOf module:ControlFlow
4795  * @method
4796  * @see [async.map]{@link module:Collections.map}
4797  * @category Control Flow
4798  * @param {number} n - The number of times to run the function.
4799  * @param {Function} iteratee - The function to call `n` times. Invoked with the
4800  * iteration index and a callback (n, next).
4801  * @param {Function} callback - see {@link module:Collections.map}.
4802  * @example
4803  *
4804  * // Pretend this is some complicated async factory
4805  * var createUser = function(id, callback) {
4806  *     callback(null, {
4807  *         id: 'user' + id
4808  *     });
4809  * };
4810  *
4811  * // generate 5 users
4812  * async.times(5, function(n, next) {
4813  *     createUser(n, function(err, user) {
4814  *         next(err, user);
4815  *     });
4816  * }, function(err, users) {
4817  *     // we should now have 5 users
4818  * });
4819  */
4820 var times = doLimit(timeLimit, Infinity);
4821
4822 /**
4823  * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time.
4824  *
4825  * @name timesSeries
4826  * @static
4827  * @memberOf module:ControlFlow
4828  * @method
4829  * @see [async.times]{@link module:ControlFlow.times}
4830  * @category Control Flow
4831  * @param {number} n - The number of times to run the function.
4832  * @param {Function} iteratee - The function to call `n` times. Invoked with the
4833  * iteration index and a callback (n, next).
4834  * @param {Function} callback - see {@link module:Collections.map}.
4835  */
4836 var timesSeries = doLimit(timeLimit, 1);
4837
4838 /**
4839  * A relative of `reduce`.  Takes an Object or Array, and iterates over each
4840  * element in series, each step potentially mutating an `accumulator` value.
4841  * The type of the accumulator defaults to the type of collection passed in.
4842  *
4843  * @name transform
4844  * @static
4845  * @memberOf module:Collections
4846  * @method
4847  * @category Collection
4848  * @param {Array|Iterable|Object} coll - A collection to iterate over.
4849  * @param {*} [accumulator] - The initial state of the transform.  If omitted,
4850  * it will default to an empty Object or Array, depending on the type of `coll`
4851  * @param {Function} iteratee - A function applied to each item in the
4852  * collection that potentially modifies the accumulator. The `iteratee` is
4853  * passed a `callback(err)` which accepts an optional error as its first
4854  * argument. If an error is passed to the callback, the transform is stopped
4855  * and the main `callback` is immediately called with the error.
4856  * Invoked with (accumulator, item, key, callback).
4857  * @param {Function} [callback] - A callback which is called after all the
4858  * `iteratee` functions have finished. Result is the transformed accumulator.
4859  * Invoked with (err, result).
4860  * @example
4861  *
4862  * async.transform([1,2,3], function(acc, item, index, callback) {
4863  *     // pointless async:
4864  *     process.nextTick(function() {
4865  *         acc.push(item * 2)
4866  *         callback(null)
4867  *     });
4868  * }, function(err, result) {
4869  *     // result is now equal to [2, 4, 6]
4870  * });
4871  *
4872  * @example
4873  *
4874  * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) {
4875  *     setImmediate(function () {
4876  *         obj[key] = val * 2;
4877  *         callback();
4878  *     })
4879  * }, function (err, result) {
4880  *     // result is equal to {a: 2, b: 4, c: 6}
4881  * })
4882  */
4883 function transform(coll, accumulator, iteratee, callback) {
4884     if (arguments.length === 3) {
4885         callback = iteratee;
4886         iteratee = accumulator;
4887         accumulator = isArray(coll) ? [] : {};
4888     }
4889     callback = once(callback || noop);
4890
4891     eachOf(coll, function (v, k, cb) {
4892         iteratee(accumulator, v, k, cb);
4893     }, function (err) {
4894         callback(err, accumulator);
4895     });
4896 }
4897
4898 /**
4899  * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original,
4900  * unmemoized form. Handy for testing.
4901  *
4902  * @name unmemoize
4903  * @static
4904  * @memberOf module:Utils
4905  * @method
4906  * @see [async.memoize]{@link module:Utils.memoize}
4907  * @category Util
4908  * @param {Function} fn - the memoized function
4909  * @returns {Function} a function that calls the original unmemoized function
4910  */
4911 function unmemoize(fn) {
4912     return function () {
4913         return (fn.unmemoized || fn).apply(null, arguments);
4914     };
4915 }
4916
4917 /**
4918  * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when
4919  * stopped, or an error occurs.
4920  *
4921  * @name whilst
4922  * @static
4923  * @memberOf module:ControlFlow
4924  * @method
4925  * @category Control Flow
4926  * @param {Function} test - synchronous truth test to perform before each
4927  * execution of `iteratee`. Invoked with ().
4928  * @param {Function} iteratee - A function which is called each time `test` passes.
4929  * The function is passed a `callback(err)`, which must be called once it has
4930  * completed with an optional `err` argument. Invoked with (callback).
4931  * @param {Function} [callback] - A callback which is called after the test
4932  * function has failed and repeated execution of `iteratee` has stopped. `callback`
4933  * will be passed an error and any arguments passed to the final `iteratee`'s
4934  * callback. Invoked with (err, [results]);
4935  * @returns undefined
4936  * @example
4937  *
4938  * var count = 0;
4939  * async.whilst(
4940  *     function() { return count < 5; },
4941  *     function(callback) {
4942  *         count++;
4943  *         setTimeout(function() {
4944  *             callback(null, count);
4945  *         }, 1000);
4946  *     },
4947  *     function (err, n) {
4948  *         // 5 seconds have passed, n = 5
4949  *     }
4950  * );
4951  */
4952 function whilst(test, iteratee, callback) {
4953     callback = onlyOnce(callback || noop);
4954     if (!test()) return callback(null);
4955     var next = rest(function (err, args) {
4956         if (err) return callback(err);
4957         if (test()) return iteratee(next);
4958         callback.apply(null, [null].concat(args));
4959     });
4960     iteratee(next);
4961 }
4962
4963 /**
4964  * Repeatedly call `fn` until `test` returns `true`. Calls `callback` when
4965  * stopped, or an error occurs. `callback` will be passed an error and any
4966  * arguments passed to the final `fn`'s callback.
4967  *
4968  * The inverse of [whilst]{@link module:ControlFlow.whilst}.
4969  *
4970  * @name until
4971  * @static
4972  * @memberOf module:ControlFlow
4973  * @method
4974  * @see [async.whilst]{@link module:ControlFlow.whilst}
4975  * @category Control Flow
4976  * @param {Function} test - synchronous truth test to perform before each
4977  * execution of `fn`. Invoked with ().
4978  * @param {Function} fn - A function which is called each time `test` fails.
4979  * The function is passed a `callback(err)`, which must be called once it has
4980  * completed with an optional `err` argument. Invoked with (callback).
4981  * @param {Function} [callback] - A callback which is called after the test
4982  * function has passed and repeated execution of `fn` has stopped. `callback`
4983  * will be passed an error and any arguments passed to the final `fn`'s
4984  * callback. Invoked with (err, [results]);
4985  */
4986 function until(test, fn, callback) {
4987     whilst(function () {
4988         return !test.apply(this, arguments);
4989     }, fn, callback);
4990 }
4991
4992 /**
4993  * Runs the `tasks` array of functions in series, each passing their results to
4994  * the next in the array. However, if any of the `tasks` pass an error to their
4995  * own callback, the next function is not executed, and the main `callback` is
4996  * immediately called with the error.
4997  *
4998  * @name waterfall
4999  * @static
5000  * @memberOf module:ControlFlow
5001  * @method
5002  * @category Control Flow
5003  * @param {Array} tasks - An array of functions to run, each function is passed
5004  * a `callback(err, result1, result2, ...)` it must call on completion. The
5005  * first argument is an error (which can be `null`) and any further arguments
5006  * will be passed as arguments in order to the next task.
5007  * @param {Function} [callback] - An optional callback to run once all the
5008  * functions have completed. This will be passed the results of the last task's
5009  * callback. Invoked with (err, [results]).
5010  * @returns undefined
5011  * @example
5012  *
5013  * async.waterfall([
5014  *     function(callback) {
5015  *         callback(null, 'one', 'two');
5016  *     },
5017  *     function(arg1, arg2, callback) {
5018  *         // arg1 now equals 'one' and arg2 now equals 'two'
5019  *         callback(null, 'three');
5020  *     },
5021  *     function(arg1, callback) {
5022  *         // arg1 now equals 'three'
5023  *         callback(null, 'done');
5024  *     }
5025  * ], function (err, result) {
5026  *     // result now equals 'done'
5027  * });
5028  *
5029  * // Or, with named functions:
5030  * async.waterfall([
5031  *     myFirstFunction,
5032  *     mySecondFunction,
5033  *     myLastFunction,
5034  * ], function (err, result) {
5035  *     // result now equals 'done'
5036  * });
5037  * function myFirstFunction(callback) {
5038  *     callback(null, 'one', 'two');
5039  * }
5040  * function mySecondFunction(arg1, arg2, callback) {
5041  *     // arg1 now equals 'one' and arg2 now equals 'two'
5042  *     callback(null, 'three');
5043  * }
5044  * function myLastFunction(arg1, callback) {
5045  *     // arg1 now equals 'three'
5046  *     callback(null, 'done');
5047  * }
5048  */
5049 var waterfall = function (tasks, callback) {
5050     callback = once(callback || noop);
5051     if (!isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));
5052     if (!tasks.length) return callback();
5053     var taskIndex = 0;
5054
5055     function nextTask(args) {
5056         if (taskIndex === tasks.length) {
5057             return callback.apply(null, [null].concat(args));
5058         }
5059
5060         var taskCallback = onlyOnce(rest(function (err, args) {
5061             if (err) {
5062                 return callback.apply(null, [err].concat(args));
5063             }
5064             nextTask(args);
5065         }));
5066
5067         args.push(taskCallback);
5068
5069         var task = tasks[taskIndex++];
5070         task.apply(null, args);
5071     }
5072
5073     nextTask([]);
5074 };
5075
5076 /**
5077  * Async is a utility module which provides straight-forward, powerful functions
5078  * for working with asynchronous JavaScript. Although originally designed for
5079  * use with [Node.js](http://nodejs.org) and installable via
5080  * `npm install --save async`, it can also be used directly in the browser.
5081  * @module async
5082  */
5083
5084 /**
5085  * A collection of `async` functions for manipulating collections, such as
5086  * arrays and objects.
5087  * @module Collections
5088  */
5089
5090 /**
5091  * A collection of `async` functions for controlling the flow through a script.
5092  * @module ControlFlow
5093  */
5094
5095 /**
5096  * A collection of `async` utility functions.
5097  * @module Utils
5098  */
5099 var index = {
5100   applyEach: applyEach,
5101   applyEachSeries: applyEachSeries,
5102   apply: apply$2,
5103   asyncify: asyncify,
5104   auto: auto,
5105   autoInject: autoInject,
5106   cargo: cargo,
5107   compose: compose,
5108   concat: concat,
5109   concatSeries: concatSeries,
5110   constant: constant,
5111   detect: detect,
5112   detectLimit: detectLimit,
5113   detectSeries: detectSeries,
5114   dir: dir,
5115   doDuring: doDuring,
5116   doUntil: doUntil,
5117   doWhilst: doWhilst,
5118   during: during,
5119   each: eachLimit,
5120   eachLimit: eachLimit$1,
5121   eachOf: eachOf,
5122   eachOfLimit: eachOfLimit,
5123   eachOfSeries: eachOfSeries,
5124   eachSeries: eachSeries,
5125   ensureAsync: ensureAsync,
5126   every: every,
5127   everyLimit: everyLimit,
5128   everySeries: everySeries,
5129   filter: filter,
5130   filterLimit: filterLimit,
5131   filterSeries: filterSeries,
5132   forever: forever,
5133   log: log,
5134   map: map,
5135   mapLimit: mapLimit,
5136   mapSeries: mapSeries,
5137   mapValues: mapValues,
5138   mapValuesLimit: mapValuesLimit,
5139   mapValuesSeries: mapValuesSeries,
5140   memoize: memoize,
5141   nextTick: nextTick,
5142   parallel: parallelLimit,
5143   parallelLimit: parallelLimit$1,
5144   priorityQueue: priorityQueue,
5145   queue: queue$1,
5146   race: race,
5147   reduce: reduce,
5148   reduceRight: reduceRight,
5149   reflect: reflect,
5150   reflectAll: reflectAll,
5151   reject: reject,
5152   rejectLimit: rejectLimit,
5153   rejectSeries: rejectSeries,
5154   retry: retry,
5155   retryable: retryable,
5156   seq: seq$1,
5157   series: series,
5158   setImmediate: setImmediate$1,
5159   some: some,
5160   someLimit: someLimit,
5161   someSeries: someSeries,
5162   sortBy: sortBy,
5163   timeout: timeout,
5164   times: times,
5165   timesLimit: timeLimit,
5166   timesSeries: timesSeries,
5167   transform: transform,
5168   unmemoize: unmemoize,
5169   until: until,
5170   waterfall: waterfall,
5171   whilst: whilst,
5172
5173   // aliases
5174   all: every,
5175   any: some,
5176   forEach: eachLimit,
5177   forEachSeries: eachSeries,
5178   forEachLimit: eachLimit$1,
5179   forEachOf: eachOf,
5180   forEachOfSeries: eachOfSeries,
5181   forEachOfLimit: eachOfLimit,
5182   inject: reduce,
5183   foldl: reduce,
5184   foldr: reduceRight,
5185   select: filter,
5186   selectLimit: filterLimit,
5187   selectSeries: filterSeries,
5188   wrapSync: asyncify
5189 };
5190
5191 exports['default'] = index;
5192 exports.applyEach = applyEach;
5193 exports.applyEachSeries = applyEachSeries;
5194 exports.apply = apply$2;
5195 exports.asyncify = asyncify;
5196 exports.auto = auto;
5197 exports.autoInject = autoInject;
5198 exports.cargo = cargo;
5199 exports.compose = compose;
5200 exports.concat = concat;
5201 exports.concatSeries = concatSeries;
5202 exports.constant = constant;
5203 exports.detect = detect;
5204 exports.detectLimit = detectLimit;
5205 exports.detectSeries = detectSeries;
5206 exports.dir = dir;
5207 exports.doDuring = doDuring;
5208 exports.doUntil = doUntil;
5209 exports.doWhilst = doWhilst;
5210 exports.during = during;
5211 exports.each = eachLimit;
5212 exports.eachLimit = eachLimit$1;
5213 exports.eachOf = eachOf;
5214 exports.eachOfLimit = eachOfLimit;
5215 exports.eachOfSeries = eachOfSeries;
5216 exports.eachSeries = eachSeries;
5217 exports.ensureAsync = ensureAsync;
5218 exports.every = every;
5219 exports.everyLimit = everyLimit;
5220 exports.everySeries = everySeries;
5221 exports.filter = filter;
5222 exports.filterLimit = filterLimit;
5223 exports.filterSeries = filterSeries;
5224 exports.forever = forever;
5225 exports.log = log;
5226 exports.map = map;
5227 exports.mapLimit = mapLimit;
5228 exports.mapSeries = mapSeries;
5229 exports.mapValues = mapValues;
5230 exports.mapValuesLimit = mapValuesLimit;
5231 exports.mapValuesSeries = mapValuesSeries;
5232 exports.memoize = memoize;
5233 exports.nextTick = nextTick;
5234 exports.parallel = parallelLimit;
5235 exports.parallelLimit = parallelLimit$1;
5236 exports.priorityQueue = priorityQueue;
5237 exports.queue = queue$1;
5238 exports.race = race;
5239 exports.reduce = reduce;
5240 exports.reduceRight = reduceRight;
5241 exports.reflect = reflect;
5242 exports.reflectAll = reflectAll;
5243 exports.reject = reject;
5244 exports.rejectLimit = rejectLimit;
5245 exports.rejectSeries = rejectSeries;
5246 exports.retry = retry;
5247 exports.retryable = retryable;
5248 exports.seq = seq$1;
5249 exports.series = series;
5250 exports.setImmediate = setImmediate$1;
5251 exports.some = some;
5252 exports.someLimit = someLimit;
5253 exports.someSeries = someSeries;
5254 exports.sortBy = sortBy;
5255 exports.timeout = timeout;
5256 exports.times = times;
5257 exports.timesLimit = timeLimit;
5258 exports.timesSeries = timesSeries;
5259 exports.transform = transform;
5260 exports.unmemoize = unmemoize;
5261 exports.until = until;
5262 exports.waterfall = waterfall;
5263 exports.whilst = whilst;
5264 exports.all = every;
5265 exports.allLimit = everyLimit;
5266 exports.allSeries = everySeries;
5267 exports.any = some;
5268 exports.anyLimit = someLimit;
5269 exports.anySeries = someSeries;
5270 exports.find = detect;
5271 exports.findLimit = detectLimit;
5272 exports.findSeries = detectSeries;
5273 exports.forEach = eachLimit;
5274 exports.forEachSeries = eachSeries;
5275 exports.forEachLimit = eachLimit$1;
5276 exports.forEachOf = eachOf;
5277 exports.forEachOfSeries = eachOfSeries;
5278 exports.forEachOfLimit = eachOfLimit;
5279 exports.inject = reduce;
5280 exports.foldl = reduce;
5281 exports.foldr = reduceRight;
5282 exports.select = filter;
5283 exports.selectLimit = filterLimit;
5284 exports.selectSeries = filterSeries;
5285 exports.wrapSync = asyncify;
5286
5287 Object.defineProperty(exports, '__esModule', { value: true });
5288
5289 })));