basant307/AI_Governance_Project
048
1(function (global, factory) {2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :3 typeof define === 'function' && define.amd ? define(['exports'], factory) :4 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.async = {}));5})(this, (function (exports) { 'use strict';6 7 /**8 * Creates a continuation function with some arguments already applied.9 *10 * Useful as a shorthand when combined with other control flow functions. Any11 * arguments passed to the returned function are added to the arguments12 * originally passed to apply.13 *14 * @name apply15 * @static16 * @memberOf module:Utils17 * @method18 * @category Util19 * @param {Function} fn - The function you want to eventually apply all20 * arguments to. Invokes with (arguments...).21 * @param {...*} arguments... - Any number of arguments to automatically apply22 * when the continuation is called.23 * @returns {Function} the partially-applied function24 * @example25 *26 * // using apply27 * async.parallel([28 * async.apply(fs.writeFile, 'testfile1', 'test1'),29 * async.apply(fs.writeFile, 'testfile2', 'test2')30 * ]);31 *32 *33 * // the same process without using apply34 * async.parallel([35 * function(callback) {36 * fs.writeFile('testfile1', 'test1', callback);37 * },38 * function(callback) {39 * fs.writeFile('testfile2', 'test2', callback);40 * }41 * ]);42 *43 * // It's possible to pass any number of additional arguments when calling the44 * // continuation:45 *46 * node> var fn = async.apply(sys.puts, 'one');47 * node> fn('two', 'three');48 * one49 * two50 * three51 */52 function apply(fn, ...args) {53 return (...callArgs) => fn(...args,...callArgs);54 }55 56 function initialParams (fn) {57 return function (...args/*, callback*/) {58 var callback = args.pop();59 return fn.call(this, args, callback);60 };61 }62 63 /* istanbul ignore file */64 65 var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask;66 var hasSetImmediate = typeof setImmediate === 'function' && setImmediate;67 var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';68 69 function fallback(fn) {70 setTimeout(fn, 0);71 }72 73 function wrap(defer) {74 return (fn, ...args) => defer(() => fn(...args));75 }76 77 var _defer$1;78 79 if (hasQueueMicrotask) {80 _defer$1 = queueMicrotask;81 } else if (hasSetImmediate) {82 _defer$1 = setImmediate;83 } else if (hasNextTick) {84 _defer$1 = process.nextTick;85 } else {86 _defer$1 = fallback;87 }88 89 var setImmediate$1 = wrap(_defer$1);90 91 /**92 * Take a sync function and make it async, passing its return value to a93 * callback. This is useful for plugging sync functions into a waterfall,94 * series, or other async functions. Any arguments passed to the generated95 * function will be passed to the wrapped function (except for the final96 * callback argument). Errors thrown will be passed to the callback.97 *98 * If the function passed to `asyncify` returns a Promise, that promises's99 * resolved/rejected state will be used to call the callback, rather than simply100 * the synchronous return value.101 *102 * This also means you can asyncify ES2017 `async` functions.103 *104 * @name asyncify105 * @static106 * @memberOf module:Utils107 * @method108 * @alias wrapSync109 * @category Util110 * @param {Function} func - The synchronous function, or Promise-returning111 * function to convert to an {@link AsyncFunction}.112 * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be113 * invoked with `(args..., callback)`.114 * @example115 *116 * // passing a regular synchronous function117 * async.waterfall([118 * async.apply(fs.readFile, filename, "utf8"),119 * async.asyncify(JSON.parse),120 * function (data, next) {121 * // data is the result of parsing the text.122 * // If there was a parsing error, it would have been caught.123 * }124 * ], callback);125 *126 * // passing a function returning a promise127 * async.waterfall([128 * async.apply(fs.readFile, filename, "utf8"),129 * async.asyncify(function (contents) {130 * return db.model.create(contents);131 * }),132 * function (model, next) {133 * // `model` is the instantiated model object.134 * // If there was an error, this function would be skipped.135 * }136 * ], callback);137 *138 * // es2017 example, though `asyncify` is not needed if your JS environment139 * // supports async functions out of the box140 * var q = async.queue(async.asyncify(async function(file) {141 * var intermediateStep = await processFile(file);142 * return await somePromise(intermediateStep)143 * }));144 *145 * q.push(files);146 */147 function asyncify(func) {148 if (isAsync(func)) {149 return function (...args/*, callback*/) {150 const callback = args.pop();151 const promise = func.apply(this, args);152 return handlePromise(promise, callback)153 }154 }155 156 return initialParams(function (args, callback) {157 var result;158 try {159 result = func.apply(this, args);160 } catch (e) {161 return callback(e);162 }163 // if result is Promise object164 if (result && typeof result.then === 'function') {165 return handlePromise(result, callback)166 } else {167 callback(null, result);168 }169 });170 }171 172 function handlePromise(promise, callback) {173 return promise.then(value => {174 invokeCallback(callback, null, value);175 }, err => {176 invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err));177 });178 }179 180 function invokeCallback(callback, error, value) {181 try {182 callback(error, value);183 } catch (err) {184 setImmediate$1(e => { throw e }, err);185 }186 }187 188 function isAsync(fn) {189 return fn[Symbol.toStringTag] === 'AsyncFunction';190 }191 192 function isAsyncGenerator(fn) {193 return fn[Symbol.toStringTag] === 'AsyncGenerator';194 }195 196 function isAsyncIterable(obj) {197 return typeof obj[Symbol.asyncIterator] === 'function';198 }199 200 function wrapAsync(asyncFn) {201 if (typeof asyncFn !== 'function') throw new Error('expected a function')202 return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;203 }204 205 // conditionally promisify a function.206 // only return a promise if a callback is omitted207 function awaitify (asyncFn, arity) {208 if (!arity) arity = asyncFn.length;209 if (!arity) throw new Error('arity is undefined')210 function awaitable (...args) {211 if (typeof args[arity - 1] === 'function') {212 return asyncFn.apply(this, args)213 }214 215 return new Promise((resolve, reject) => {216 args[arity - 1] = (err, ...cbArgs) => {217 if (err) return reject(err)218 resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);219 };220 asyncFn.apply(this, args);221 })222 }223 224 return awaitable225 }226 227 function applyEach$1 (eachfn) {228 return function applyEach(fns, ...callArgs) {229 const go = awaitify(function (callback) {230 var that = this;231 return eachfn(fns, (fn, cb) => {232 wrapAsync(fn).apply(that, callArgs.concat(cb));233 }, callback);234 });235 return go;236 };237 }238 239 function _asyncMap(eachfn, arr, iteratee, callback) {240 arr = arr || [];241 var results = [];242 var counter = 0;243 var _iteratee = wrapAsync(iteratee);244 245 return eachfn(arr, (value, _, iterCb) => {246 var index = counter++;247 _iteratee(value, (err, v) => {248 results[index] = v;249 iterCb(err);250 });251 }, err => {252 callback(err, results);253 });254 }255 256 function isArrayLike(value) {257 return value &&258 typeof value.length === 'number' &&259 value.length >= 0 &&260 value.length % 1 === 0;261 }262 263 // A temporary value used to identify if the loop should be broken.264 // See #1064, #1293265 const breakLoop = {};266 267 function once(fn) {268 function wrapper (...args) {269 if (fn === null) return;270 var callFn = fn;271 fn = null;272 callFn.apply(this, args);273 }274 Object.assign(wrapper, fn);275 return wrapper276 }277 278 function getIterator (coll) {279 return coll[Symbol.iterator] && coll[Symbol.iterator]();280 }281 282 function createArrayIterator(coll) {283 var i = -1;284 var len = coll.length;285 return function next() {286 return ++i < len ? {value: coll[i], key: i} : null;287 }288 }289 290 function createES2015Iterator(iterator) {291 var i = -1;292 return function next() {293 var item = iterator.next();294 if (item.done)295 return null;296 i++;297 return {value: item.value, key: i};298 }299 }300 301 function createObjectIterator(obj) {302 var okeys = obj ? Object.keys(obj) : [];303 var i = -1;304 var len = okeys.length;305 return function next() {306 var key = okeys[++i];307 if (key === '__proto__') {308 return next();309 }310 return i < len ? {value: obj[key], key} : null;311 };312 }313 314 function createIterator(coll) {315 if (isArrayLike(coll)) {316 return createArrayIterator(coll);317 }318 319 var iterator = getIterator(coll);320 return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);321 }322 323 function onlyOnce(fn) {324 return function (...args) {325 if (fn === null) throw new Error("Callback was already called.");326 var callFn = fn;327 fn = null;328 callFn.apply(this, args);329 };330 }331 332 // for async generators333 function asyncEachOfLimit(generator, limit, iteratee, callback) {334 let done = false;335 let canceled = false;336 let awaiting = false;337 let running = 0;338 let idx = 0;339 340 function replenish() {341 //console.log('replenish')342 if (running >= limit || awaiting || done) return343 //console.log('replenish awaiting')344 awaiting = true;345 generator.next().then(({value, done: iterDone}) => {346 //console.log('got value', value)347 if (canceled || done) return348 awaiting = false;349 if (iterDone) {350 done = true;351 if (running <= 0) {352 //console.log('done nextCb')353 callback(null);354 }355 return;356 }357 running++;358 iteratee(value, idx, iterateeCallback);359 idx++;360 replenish();361 }).catch(handleError);362 }363 364 function iterateeCallback(err, result) {365 //console.log('iterateeCallback')366 running -= 1;367 if (canceled) return368 if (err) return handleError(err)369 370 if (err === false) {371 done = true;372 canceled = true;373 return374 }375 376 if (result === breakLoop || (done && running <= 0)) {377 done = true;378 //console.log('done iterCb')379 return callback(null);380 }381 replenish();382 }383 384 function handleError(err) {385 if (canceled) return386 awaiting = false;387 done = true;388 callback(err);389 }390 391 replenish();392 }393 394 var eachOfLimit$2 = (limit) => {395 return (obj, iteratee, callback) => {396 callback = once(callback);397 if (limit <= 0) {398 throw new RangeError('concurrency limit cannot be less than 1')399 }400 if (!obj) {401 return callback(null);402 }403 if (isAsyncGenerator(obj)) {404 return asyncEachOfLimit(obj, limit, iteratee, callback)405 }406 if (isAsyncIterable(obj)) {407 return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback)408 }409 var nextElem = createIterator(obj);410 var done = false;411 var canceled = false;412 var running = 0;413 var looping = false;414 415 function iterateeCallback(err, value) {416 if (canceled) return417 running -= 1;418 if (err) {419 done = true;420 callback(err);421 }422 else if (err === false) {423 done = true;424 canceled = true;425 }426 else if (value === breakLoop || (done && running <= 0)) {427 done = true;428 return callback(null);429 }430 else if (!looping) {431 replenish();432 }433 }434 435 function replenish () {436 looping = true;437 while (running < limit && !done) {438 var elem = nextElem();439 if (elem === null) {440 done = true;441 if (running <= 0) {442 callback(null);443 }444 return;445 }446 running += 1;447 iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));448 }449 looping = false;450 }451 452 replenish();453 };454 };455 456 /**457 * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a458 * time.459 *460 * @name eachOfLimit461 * @static462 * @memberOf module:Collections463 * @method464 * @see [async.eachOf]{@link module:Collections.eachOf}465 * @alias forEachOfLimit466 * @category Collection467 * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.468 * @param {number} limit - The maximum number of async operations at a time.469 * @param {AsyncFunction} iteratee - An async function to apply to each470 * item in `coll`. The `key` is the item's key, or index in the case of an471 * array.472 * Invoked with (item, key, callback).473 * @param {Function} [callback] - A callback which is called when all474 * `iteratee` functions have finished, or an error occurs. Invoked with (err).475 * @returns {Promise} a promise, if a callback is omitted476 */477 function eachOfLimit(coll, limit, iteratee, callback) {478 return eachOfLimit$2(limit)(coll, wrapAsync(iteratee), callback);479 }480 481 var eachOfLimit$1 = awaitify(eachOfLimit, 4);482 483 // eachOf implementation optimized for array-likes484 function eachOfArrayLike(coll, iteratee, callback) {485 callback = once(callback);486 var index = 0,487 completed = 0,488 {length} = coll,489 canceled = false;490 if (length === 0) {491 callback(null);492 }493 494 function iteratorCallback(err, value) {495 if (err === false) {496 canceled = true;497 }498 if (canceled === true) return499 if (err) {500 callback(err);501 } else if ((++completed === length) || value === breakLoop) {502 callback(null);503 }504 }505 506 for (; index < length; index++) {507 iteratee(coll[index], index, onlyOnce(iteratorCallback));508 }509 }510 511 // a generic version of eachOf which can handle array, object, and iterator cases.512 function eachOfGeneric (coll, iteratee, callback) {513 return eachOfLimit$1(coll, Infinity, iteratee, callback);514 }515 516 /**517 * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument518 * to the iteratee.519 *520 * @name eachOf521 * @static522 * @memberOf module:Collections523 * @method524 * @alias forEachOf525 * @category Collection526 * @see [async.each]{@link module:Collections.each}527 * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.528 * @param {AsyncFunction} iteratee - A function to apply to each529 * item in `coll`.530 * The `key` is the item's key, or index in the case of an array.531 * Invoked with (item, key, callback).532 * @param {Function} [callback] - A callback which is called when all533 * `iteratee` functions have finished, or an error occurs. Invoked with (err).534 * @returns {Promise} a promise, if a callback is omitted535 * @example536 *537 * // dev.json is a file containing a valid json object config for dev environment538 * // dev.json is a file containing a valid json object config for test environment539 * // prod.json is a file containing a valid json object config for prod environment540 * // invalid.json is a file with a malformed json object541 *542 * let configs = {}; //global variable543 * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'};544 * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'};545 *546 * // asynchronous function that reads a json file and parses the contents as json object547 * function parseFile(file, key, callback) {548 * fs.readFile(file, "utf8", function(err, data) {549 * if (err) return calback(err);550 * try {551 * configs[key] = JSON.parse(data);552 * } catch (e) {553 * return callback(e);554 * }555 * callback();556 * });557 * }558 *559 * // Using callbacks560 * async.forEachOf(validConfigFileMap, parseFile, function (err) {561 * if (err) {562 * console.error(err);563 * } else {564 * console.log(configs);565 * // configs is now a map of JSON data, e.g.566 * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}567 * }568 * });569 *570 * //Error handing571 * async.forEachOf(invalidConfigFileMap, parseFile, function (err) {572 * if (err) {573 * console.error(err);574 * // JSON parse error exception575 * } else {576 * console.log(configs);577 * }578 * });579 *580 * // Using Promises581 * async.forEachOf(validConfigFileMap, parseFile)582 * .then( () => {583 * console.log(configs);584 * // configs is now a map of JSON data, e.g.585 * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}586 * }).catch( err => {587 * console.error(err);588 * });589 *590 * //Error handing591 * async.forEachOf(invalidConfigFileMap, parseFile)592 * .then( () => {593 * console.log(configs);594 * }).catch( err => {595 * console.error(err);596 * // JSON parse error exception597 * });598 *599 * // Using async/await600 * async () => {601 * try {602 * let result = await async.forEachOf(validConfigFileMap, parseFile);603 * console.log(configs);604 * // configs is now a map of JSON data, e.g.605 * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}606 * }607 * catch (err) {608 * console.log(err);609 * }610 * }611 *612 * //Error handing613 * async () => {614 * try {615 * let result = await async.forEachOf(invalidConfigFileMap, parseFile);616 * console.log(configs);617 * }618 * catch (err) {619 * console.log(err);620 * // JSON parse error exception621 * }622 * }623 *624 */625 function eachOf(coll, iteratee, callback) {626 var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;627 return eachOfImplementation(coll, wrapAsync(iteratee), callback);628 }629 630 var eachOf$1 = awaitify(eachOf, 3);631 632 /**633 * Produces a new collection of values by mapping each value in `coll` through634 * the `iteratee` function. The `iteratee` is called with an item from `coll`635 * and a callback for when it has finished processing. Each of these callbacks636 * takes 2 arguments: an `error`, and the transformed item from `coll`. If637 * `iteratee` passes an error to its callback, the main `callback` (for the638 * `map` function) is immediately called with the error.639 *640 * Note, that since this function applies the `iteratee` to each item in641 * parallel, there is no guarantee that the `iteratee` functions will complete642 * in order. However, the results array will be in the same order as the643 * original `coll`.644 *645 * If `map` is passed an Object, the results will be an Array. The results646 * will roughly be in the order of the original Objects' keys (but this can647 * vary across JavaScript engines).648 *649 * @name map650 * @static651 * @memberOf module:Collections652 * @method653 * @category Collection654 * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.655 * @param {AsyncFunction} iteratee - An async function to apply to each item in656 * `coll`.657 * The iteratee should complete with the transformed item.658 * Invoked with (item, callback).659 * @param {Function} [callback] - A callback which is called when all `iteratee`660 * functions have finished, or an error occurs. Results is an Array of the661 * transformed items from the `coll`. Invoked with (err, results).662 * @returns {Promise} a promise, if no callback is passed663 * @example664 *665 * // file1.txt is a file that is 1000 bytes in size666 * // file2.txt is a file that is 2000 bytes in size667 * // file3.txt is a file that is 3000 bytes in size668 * // file4.txt does not exist669 *670 * const fileList = ['file1.txt','file2.txt','file3.txt'];671 * const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];672 *673 * // asynchronous function that returns the file size in bytes674 * function getFileSizeInBytes(file, callback) {675 * fs.stat(file, function(err, stat) {676 * if (err) {677 * return callback(err);678 * }679 * callback(null, stat.size);680 * });681 * }682 *683 * // Using callbacks684 * async.map(fileList, getFileSizeInBytes, function(err, results) {685 * if (err) {686 * console.log(err);687 * } else {688 * console.log(results);689 * // results is now an array of the file size in bytes for each file, e.g.690 * // [ 1000, 2000, 3000]691 * }692 * });693 *694 * // Error Handling695 * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) {696 * if (err) {697 * console.log(err);698 * // [ Error: ENOENT: no such file or directory ]699 * } else {700 * console.log(results);701 * }702 * });703 *704 * // Using Promises705 * async.map(fileList, getFileSizeInBytes)706 * .then( results => {707 * console.log(results);708 * // results is now an array of the file size in bytes for each file, e.g.709 * // [ 1000, 2000, 3000]710 * }).catch( err => {711 * console.log(err);712 * });713 *714 * // Error Handling715 * async.map(withMissingFileList, getFileSizeInBytes)716 * .then( results => {717 * console.log(results);718 * }).catch( err => {719 * console.log(err);720 * // [ Error: ENOENT: no such file or directory ]721 * });722 *723 * // Using async/await724 * async () => {725 * try {726 * let results = await async.map(fileList, getFileSizeInBytes);727 * console.log(results);728 * // results is now an array of the file size in bytes for each file, e.g.729 * // [ 1000, 2000, 3000]730 * }731 * catch (err) {732 * console.log(err);733 * }734 * }735 *736 * // Error Handling737 * async () => {738 * try {739 * let results = await async.map(withMissingFileList, getFileSizeInBytes);740 * console.log(results);741 * }742 * catch (err) {743 * console.log(err);744 * // [ Error: ENOENT: no such file or directory ]745 * }746 * }747 *748 */749 function map (coll, iteratee, callback) {750 return _asyncMap(eachOf$1, coll, iteratee, callback)751 }752 var map$1 = awaitify(map, 3);753 754 /**755 * Applies the provided arguments to each function in the array, calling756 * `callback` after all functions have completed. If you only provide the first757 * argument, `fns`, then it will return a function which lets you pass in the758 * arguments as if it were a single function call. If more arguments are759 * provided, `callback` is required while `args` is still optional. The results760 * for each of the applied async functions are passed to the final callback761 * as an array.762 *763 * @name applyEach764 * @static765 * @memberOf module:ControlFlow766 * @method767 * @category Control Flow768 * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s769 * to all call with the same arguments770 * @param {...*} [args] - any number of separate arguments to pass to the771 * function.772 * @param {Function} [callback] - the final argument should be the callback,773 * called when all functions have completed processing.774 * @returns {AsyncFunction} - Returns a function that takes no args other than775 * an optional callback, that is the result of applying the `args` to each776 * of the functions.777 * @example778 *779 * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket')780 *781 * appliedFn((err, results) => {782 * // results[0] is the results for `enableSearch`783 * // results[1] is the results for `updateSchema`784 * });785 *786 * // partial application example:787 * async.each(788 * buckets,789 * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(),790 * callback791 * );792 */793 var applyEach = applyEach$1(map$1);794 795 /**796 * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.797 *798 * @name eachOfSeries799 * @static800 * @memberOf module:Collections801 * @method802 * @see [async.eachOf]{@link module:Collections.eachOf}803 * @alias forEachOfSeries804 * @category Collection805 * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.806 * @param {AsyncFunction} iteratee - An async function to apply to each item in807 * `coll`.808 * Invoked with (item, key, callback).809 * @param {Function} [callback] - A callback which is called when all `iteratee`810 * functions have finished, or an error occurs. Invoked with (err).811 * @returns {Promise} a promise, if a callback is omitted812 */813 function eachOfSeries(coll, iteratee, callback) {814 return eachOfLimit$1(coll, 1, iteratee, callback)815 }816 var eachOfSeries$1 = awaitify(eachOfSeries, 3);817 818 /**819 * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.820 *821 * @name mapSeries822 * @static823 * @memberOf module:Collections824 * @method825 * @see [async.map]{@link module:Collections.map}826 * @category Collection827 * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.828 * @param {AsyncFunction} iteratee - An async function to apply to each item in829 * `coll`.830 * The iteratee should complete with the transformed item.831 * Invoked with (item, callback).832 * @param {Function} [callback] - A callback which is called when all `iteratee`833 * functions have finished, or an error occurs. Results is an array of the834 * transformed items from the `coll`. Invoked with (err, results).835 * @returns {Promise} a promise, if no callback is passed836 */837 function mapSeries (coll, iteratee, callback) {838 return _asyncMap(eachOfSeries$1, coll, iteratee, callback)839 }840 var mapSeries$1 = awaitify(mapSeries, 3);841 842 /**843 * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.844 *845 * @name applyEachSeries846 * @static847 * @memberOf module:ControlFlow848 * @method849 * @see [async.applyEach]{@link module:ControlFlow.applyEach}850 * @category Control Flow851 * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all852 * call with the same arguments853 * @param {...*} [args] - any number of separate arguments to pass to the854 * function.855 * @param {Function} [callback] - the final argument should be the callback,856 * called when all functions have completed processing.857 * @returns {AsyncFunction} - A function, that when called, is the result of858 * appling the `args` to the list of functions. It takes no args, other than859 * a callback.860 */861 var applyEachSeries = applyEach$1(mapSeries$1);862 863 const PROMISE_SYMBOL = Symbol('promiseCallback');864 865 function promiseCallback () {866 let resolve, reject;867 function callback (err, ...args) {868 if (err) return reject(err)869 resolve(args.length > 1 ? args : args[0]);870 }871 872 callback[PROMISE_SYMBOL] = new Promise((res, rej) => {873 resolve = res,874 reject = rej;875 });876 877 return callback878 }879 880 /**881 * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on882 * their requirements. Each function can optionally depend on other functions883 * being completed first, and each function is run as soon as its requirements884 * are satisfied.885 *886 * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence887 * will stop. Further tasks will not execute (so any other functions depending888 * on it will not run), and the main `callback` is immediately called with the889 * error.890 *891 * {@link AsyncFunction}s also receive an object containing the results of functions which892 * have completed so far as the first argument, if they have dependencies. If a893 * task function has no dependencies, it will only be passed a callback.894 *895 * @name auto896 * @static897 * @memberOf module:ControlFlow898 * @method899 * @category Control Flow900 * @param {Object} tasks - An object. Each of its properties is either a901 * function or an array of requirements, with the {@link AsyncFunction} itself the last item902 * in the array. The object's key of a property serves as the name of the task903 * defined by that property, i.e. can be used when specifying requirements for904 * other tasks. The function receives one or two arguments:905 * * a `results` object, containing the results of the previously executed906 * functions, only passed if the task has any dependencies,907 * * a `callback(err, result)` function, which must be called when finished,908 * passing an `error` (which can be `null`) and the result of the function's909 * execution.910 * @param {number} [concurrency=Infinity] - An optional `integer` for911 * determining the maximum number of tasks that can be run in parallel. By912 * default, as many as possible.913 * @param {Function} [callback] - An optional callback which is called when all914 * the tasks have been completed. It receives the `err` argument if any `tasks`915 * pass an error to their callback. Results are always returned; however, if an916 * error occurs, no further `tasks` will be performed, and the results object917 * will only contain partial results. Invoked with (err, results).918 * @returns {Promise} a promise, if a callback is not passed919 * @example920 *921 * //Using Callbacks922 * async.auto({923 * get_data: function(callback) {924 * // async code to get some data925 * callback(null, 'data', 'converted to array');926 * },927 * make_folder: function(callback) {928 * // async code to create a directory to store a file in929 * // this is run at the same time as getting the data930 * callback(null, 'folder');931 * },932 * write_file: ['get_data', 'make_folder', function(results, callback) {933 * // once there is some data and the directory exists,934 * // write the data to a file in the directory935 * callback(null, 'filename');936 * }],937 * email_link: ['write_file', function(results, callback) {938 * // once the file is written let's email a link to it...939 * callback(null, {'file':results.write_file, 'email':'user@example.com'});940 * }]941 * }, function(err, results) {942 * if (err) {943 * console.log('err = ', err);944 * }945 * console.log('results = ', results);946 * // results = {947 * // get_data: ['data', 'converted to array']948 * // make_folder; 'folder',949 * // write_file: 'filename'950 * // email_link: { file: 'filename', email: 'user@example.com' }951 * // }952 * });953 *954 * //Using Promises955 * async.auto({956 * get_data: function(callback) {957 * console.log('in get_data');958 * // async code to get some data959 * callback(null, 'data', 'converted to array');960 * },961 * make_folder: function(callback) {962 * console.log('in make_folder');963 * // async code to create a directory to store a file in964 * // this is run at the same time as getting the data965 * callback(null, 'folder');966 * },967 * write_file: ['get_data', 'make_folder', function(results, callback) {968 * // once there is some data and the directory exists,969 * // write the data to a file in the directory970 * callback(null, 'filename');971 * }],972 * email_link: ['write_file', function(results, callback) {973 * // once the file is written let's email a link to it...974 * callback(null, {'file':results.write_file, 'email':'user@example.com'});975 * }]976 * }).then(results => {977 * console.log('results = ', results);978 * // results = {979 * // get_data: ['data', 'converted to array']980 * // make_folder; 'folder',981 * // write_file: 'filename'982 * // email_link: { file: 'filename', email: 'user@example.com' }983 * // }984 * }).catch(err => {985 * console.log('err = ', err);986 * });987 *988 * //Using async/await989 * async () => {990 * try {991 * let results = await async.auto({992 * get_data: function(callback) {993 * // async code to get some data994 * callback(null, 'data', 'converted to array');995 * },996 * make_folder: function(callback) {997 * // async code to create a directory to store a file in998 * // this is run at the same time as getting the data999 * callback(null, 'folder');1000 * },1001 * write_file: ['get_data', 'make_folder', function(results, callback) {1002 * // once there is some data and the directory exists,1003 * // write the data to a file in the directory1004 * callback(null, 'filename');1005 * }],1006 * email_link: ['write_file', function(results, callback) {1007 * // once the file is written let's email a link to it...1008 * callback(null, {'file':results.write_file, 'email':'user@example.com'});1009 * }]1010 * });1011 * console.log('results = ', results);1012 * // results = {1013 * // get_data: ['data', 'converted to array']1014 * // make_folder; 'folder',1015 * // write_file: 'filename'1016 * // email_link: { file: 'filename', email: 'user@example.com' }1017 * // }1018 * }1019 * catch (err) {1020 * console.log(err);1021 * }1022 * }1023 *1024 */1025 function auto(tasks, concurrency, callback) {1026 if (typeof concurrency !== 'number') {1027 // concurrency is optional, shift the args.1028 callback = concurrency;1029 concurrency = null;1030 }1031 callback = once(callback || promiseCallback());1032 var numTasks = Object.keys(tasks).length;1033 if (!numTasks) {1034 return callback(null);1035 }1036 if (!concurrency) {1037 concurrency = numTasks;1038 }1039 1040 var results = {};1041 var runningTasks = 0;1042 var canceled = false;1043 var hasError = false;1044 1045 var listeners = Object.create(null);1046 1047 var readyTasks = [];1048 1049 // for cycle detection:1050 var readyToCheck = []; // tasks that have been identified as reachable1051 // without the possibility of returning to an ancestor task1052 var uncheckedDependencies = {};1053 1054 Object.keys(tasks).forEach(key => {1055 var task = tasks[key];1056 if (!Array.isArray(task)) {1057 // no dependencies1058 enqueueTask(key, [task]);1059 readyToCheck.push(key);1060 return;1061 }1062 1063 var dependencies = task.slice(0, task.length - 1);1064 var remainingDependencies = dependencies.length;1065 if (remainingDependencies === 0) {1066 enqueueTask(key, task);1067 readyToCheck.push(key);1068 return;1069 }1070 uncheckedDependencies[key] = remainingDependencies;1071 1072 dependencies.forEach(dependencyName => {1073 if (!tasks[dependencyName]) {1074 throw new Error('async.auto task `' + key +1075 '` has a non-existent dependency `' +1076 dependencyName + '` in ' +1077 dependencies.join(', '));1078 }1079 addListener(dependencyName, () => {1080 remainingDependencies--;1081 if (remainingDependencies === 0) {1082 enqueueTask(key, task);1083 }1084 });1085 });1086 });1087 1088 checkForDeadlocks();1089 processQueue();1090 1091 function enqueueTask(key, task) {1092 readyTasks.push(() => runTask(key, task));1093 }1094 1095 function processQueue() {1096 if (canceled) return1097 if (readyTasks.length === 0 && runningTasks === 0) {1098 return callback(null, results);1099 }1100 while(readyTasks.length && runningTasks < concurrency) {1101 var run = readyTasks.shift();1102 run();1103 }1104 1105 }1106 1107 function addListener(taskName, fn) {1108 var taskListeners = listeners[taskName];1109 if (!taskListeners) {1110 taskListeners = listeners[taskName] = [];1111 }1112 1113 taskListeners.push(fn);1114 }1115 1116 function taskComplete(taskName) {1117 var taskListeners = listeners[taskName] || [];1118 taskListeners.forEach(fn => fn());1119 processQueue();1120 }1121 1122 1123 function runTask(key, task) {1124 if (hasError) return;1125 1126 var taskCallback = onlyOnce((err, ...result) => {1127 runningTasks--;1128 if (err === false) {1129 canceled = true;1130 return1131 }1132 if (result.length < 2) {1133 [result] = result;1134 }1135 if (err) {1136 var safeResults = {};1137 Object.keys(results).forEach(rkey => {1138 safeResults[rkey] = results[rkey];1139 });1140 safeResults[key] = result;1141 hasError = true;1142 listeners = Object.create(null);1143 if (canceled) return1144 callback(err, safeResults);1145 } else {1146 results[key] = result;1147 taskComplete(key);1148 }1149 });1150 1151 runningTasks++;1152 var taskFn = wrapAsync(task[task.length - 1]);1153 if (task.length > 1) {1154 taskFn(results, taskCallback);1155 } else {1156 taskFn(taskCallback);1157 }1158 }1159 1160 function checkForDeadlocks() {1161 // Kahn's algorithm1162 // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm1163 // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html1164 var currentTask;1165 var counter = 0;1166 while (readyToCheck.length) {1167 currentTask = readyToCheck.pop();1168 counter++;1169 getDependents(currentTask).forEach(dependent => {1170 if (--uncheckedDependencies[dependent] === 0) {1171 readyToCheck.push(dependent);1172 }1173 });1174 }1175 1176 if (counter !== numTasks) {1177 throw new Error(1178 'async.auto cannot execute tasks due to a recursive dependency'1179 );1180 }1181 }1182 1183 function getDependents(taskName) {1184 var result = [];1185 Object.keys(tasks).forEach(key => {1186 const task = tasks[key];1187 if (Array.isArray(task) && task.indexOf(taskName) >= 0) {1188 result.push(key);1189 }1190 });1191 return result;1192 }1193 1194 return callback[PROMISE_SYMBOL]1195 }1196 1197 var FN_ARGS = /^(?:async\s)?(?:function)?\s*(?:\w+\s*)?\(([^)]+)\)(?:\s*{)/;1198 var ARROW_FN_ARGS = /^(?:async\s)?\s*(?:\(\s*)?((?:[^)=\s]\s*)*)(?:\)\s*)?=>/;1199 var FN_ARG_SPLIT = /,/;1200 var FN_ARG = /(=.+)?(\s*)$/;