Brunobkr/llama.cpp_AlgMor24_github
ΩFFFΣLLIa • llama.cpp • AlgMor24 ██████╗ ███████╗███████╗███████╗██╗ ██╗ ██╗ █████╗ ██╔═══██╗██╔════╝██╔════╝██╔════╝██║ ██║ ██║██╔══██╗ ██║ ██║█████╗ █████╗ █████╗ ██║ ██║ ██║███████║ ██║ ██║██╔══╝ ██╔══╝ ██╔══╝ ██║ ██║ ██║██╔══██║ ╚██████╔╝██║ ██║ ███████╗███████╗███████╗██║██║ ██║ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚═╝╚═╝ ╚═╝ High-Performance LLM / VLM Inference & Autonomous Agentic Ecosystem… See the full description on the dataset page: https://huggingface.co/datasets/Brunobkr/llama.cpp_AlgMor24_github.
03.1k
1/**2 * Creates a continuation function with some arguments already applied.3 *4 * Useful as a shorthand when combined with other control flow functions. Any5 * arguments passed to the returned function are added to the arguments6 * originally passed to apply.7 *8 * @name apply9 * @static10 * @memberOf module:Utils11 * @method12 * @category Util13 * @param {Function} fn - The function you want to eventually apply all14 * arguments to. Invokes with (arguments...).15 * @param {...*} arguments... - Any number of arguments to automatically apply16 * when the continuation is called.17 * @returns {Function} the partially-applied function18 * @example19 *20 * // using apply21 * async.parallel([22 * async.apply(fs.writeFile, 'testfile1', 'test1'),23 * async.apply(fs.writeFile, 'testfile2', 'test2')24 * ]);25 *26 *27 * // the same process without using apply28 * async.parallel([29 * function(callback) {30 * fs.writeFile('testfile1', 'test1', callback);31 * },32 * function(callback) {33 * fs.writeFile('testfile2', 'test2', callback);34 * }35 * ]);36 *37 * // It's possible to pass any number of additional arguments when calling the38 * // continuation:39 *40 * node> var fn = async.apply(sys.puts, 'one');41 * node> fn('two', 'three');42 * one43 * two44 * three45 */46function apply(fn, ...args) {47 return (...callArgs) => fn(...args,...callArgs);48}49 50function initialParams (fn) {51 return function (...args/*, callback*/) {52 var callback = args.pop();53 return fn.call(this, args, callback);54 };55}56 57/* istanbul ignore file */58 59var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask;60var hasSetImmediate = typeof setImmediate === 'function' && setImmediate;61var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';62 63function fallback(fn) {64 setTimeout(fn, 0);65}66 67function wrap(defer) {68 return (fn, ...args) => defer(() => fn(...args));69}70 71var _defer$1;72 73if (hasQueueMicrotask) {74 _defer$1 = queueMicrotask;75} else if (hasSetImmediate) {76 _defer$1 = setImmediate;77} else if (hasNextTick) {78 _defer$1 = process.nextTick;79} else {80 _defer$1 = fallback;81}82 83var setImmediate$1 = wrap(_defer$1);84 85/**86 * Take a sync function and make it async, passing its return value to a87 * callback. This is useful for plugging sync functions into a waterfall,88 * series, or other async functions. Any arguments passed to the generated89 * function will be passed to the wrapped function (except for the final90 * callback argument). Errors thrown will be passed to the callback.91 *92 * If the function passed to `asyncify` returns a Promise, that promises's93 * resolved/rejected state will be used to call the callback, rather than simply94 * the synchronous return value.95 *96 * This also means you can asyncify ES2017 `async` functions.97 *98 * @name asyncify99 * @static100 * @memberOf module:Utils101 * @method102 * @alias wrapSync103 * @category Util104 * @param {Function} func - The synchronous function, or Promise-returning105 * function to convert to an {@link AsyncFunction}.106 * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be107 * invoked with `(args..., callback)`.108 * @example109 *110 * // passing a regular synchronous function111 * async.waterfall([112 * async.apply(fs.readFile, filename, "utf8"),113 * async.asyncify(JSON.parse),114 * function (data, next) {115 * // data is the result of parsing the text.116 * // If there was a parsing error, it would have been caught.117 * }118 * ], callback);119 *120 * // passing a function returning a promise121 * async.waterfall([122 * async.apply(fs.readFile, filename, "utf8"),123 * async.asyncify(function (contents) {124 * return db.model.create(contents);125 * }),126 * function (model, next) {127 * // `model` is the instantiated model object.128 * // If there was an error, this function would be skipped.129 * }130 * ], callback);131 *132 * // es2017 example, though `asyncify` is not needed if your JS environment133 * // supports async functions out of the box134 * var q = async.queue(async.asyncify(async function(file) {135 * var intermediateStep = await processFile(file);136 * return await somePromise(intermediateStep)137 * }));138 *139 * q.push(files);140 */141function asyncify(func) {142 if (isAsync(func)) {143 return function (...args/*, callback*/) {144 const callback = args.pop();145 const promise = func.apply(this, args);146 return handlePromise(promise, callback)147 }148 }149 150 return initialParams(function (args, callback) {151 var result;152 try {153 result = func.apply(this, args);154 } catch (e) {155 return callback(e);156 }157 // if result is Promise object158 if (result && typeof result.then === 'function') {159 return handlePromise(result, callback)160 } else {161 callback(null, result);162 }163 });164}165 166function handlePromise(promise, callback) {167 return promise.then(value => {168 invokeCallback(callback, null, value);169 }, err => {170 invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err));171 });172}173 174function invokeCallback(callback, error, value) {175 try {176 callback(error, value);177 } catch (err) {178 setImmediate$1(e => { throw e }, err);179 }180}181 182function isAsync(fn) {183 return fn[Symbol.toStringTag] === 'AsyncFunction';184}185 186function isAsyncGenerator(fn) {187 return fn[Symbol.toStringTag] === 'AsyncGenerator';188}189 190function isAsyncIterable(obj) {191 return typeof obj[Symbol.asyncIterator] === 'function';192}193 194function wrapAsync(asyncFn) {195 if (typeof asyncFn !== 'function') throw new Error('expected a function')196 return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;197}198 199// conditionally promisify a function.200// only return a promise if a callback is omitted201function awaitify (asyncFn, arity) {202 if (!arity) arity = asyncFn.length;203 if (!arity) throw new Error('arity is undefined')204 function awaitable (...args) {205 if (typeof args[arity - 1] === 'function') {206 return asyncFn.apply(this, args)207 }208 209 return new Promise((resolve, reject) => {210 args[arity - 1] = (err, ...cbArgs) => {211 if (err) return reject(err)212 resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);213 };214 asyncFn.apply(this, args);215 })216 }217 218 return awaitable219}220 221function applyEach$1 (eachfn) {222 return function applyEach(fns, ...callArgs) {223 const go = awaitify(function (callback) {224 var that = this;225 return eachfn(fns, (fn, cb) => {226 wrapAsync(fn).apply(that, callArgs.concat(cb));227 }, callback);228 });229 return go;230 };231}232 233function _asyncMap(eachfn, arr, iteratee, callback) {234 arr = arr || [];235 var results = [];236 var counter = 0;237 var _iteratee = wrapAsync(iteratee);238 239 return eachfn(arr, (value, _, iterCb) => {240 var index = counter++;241 _iteratee(value, (err, v) => {242 results[index] = v;243 iterCb(err);244 });245 }, err => {246 callback(err, results);247 });248}249 250function isArrayLike(value) {251 return value &&252 typeof value.length === 'number' &&253 value.length >= 0 &&254 value.length % 1 === 0;255}256 257// A temporary value used to identify if the loop should be broken.258// See #1064, #1293259const breakLoop = {};260 261function once(fn) {262 function wrapper (...args) {263 if (fn === null) return;264 var callFn = fn;265 fn = null;266 callFn.apply(this, args);267 }268 Object.assign(wrapper, fn);269 return wrapper270}271 272function getIterator (coll) {273 return coll[Symbol.iterator] && coll[Symbol.iterator]();274}275 276function createArrayIterator(coll) {277 var i = -1;278 var len = coll.length;279 return function next() {280 return ++i < len ? {value: coll[i], key: i} : null;281 }282}283 284function createES2015Iterator(iterator) {285 var i = -1;286 return function next() {287 var item = iterator.next();288 if (item.done)289 return null;290 i++;291 return {value: item.value, key: i};292 }293}294 295function createObjectIterator(obj) {296 var okeys = obj ? Object.keys(obj) : [];297 var i = -1;298 var len = okeys.length;299 return function next() {300 var key = okeys[++i];301 if (key === '__proto__') {302 return next();303 }304 return i < len ? {value: obj[key], key} : null;305 };306}307 308function createIterator(coll) {309 if (isArrayLike(coll)) {310 return createArrayIterator(coll);311 }312 313 var iterator = getIterator(coll);314 return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);315}316 317function onlyOnce(fn) {318 return function (...args) {319 if (fn === null) throw new Error("Callback was already called.");320 var callFn = fn;321 fn = null;322 callFn.apply(this, args);323 };324}325 326// for async generators327function asyncEachOfLimit(generator, limit, iteratee, callback) {328 let done = false;329 let canceled = false;330 let awaiting = false;331 let running = 0;332 let idx = 0;333 334 function replenish() {335 //console.log('replenish')336 if (running >= limit || awaiting || done) return337 //console.log('replenish awaiting')338 awaiting = true;339 generator.next().then(({value, done: iterDone}) => {340 //console.log('got value', value)341 if (canceled || done) return342 awaiting = false;343 if (iterDone) {344 done = true;345 if (running <= 0) {346 //console.log('done nextCb')347 callback(null);348 }349 return;350 }351 running++;352 iteratee(value, idx, iterateeCallback);353 idx++;354 replenish();355 }).catch(handleError);356 }357 358 function iterateeCallback(err, result) {359 //console.log('iterateeCallback')360 running -= 1;361 if (canceled) return362 if (err) return handleError(err)363 364 if (err === false) {365 done = true;366 canceled = true;367 return368 }369 370 if (result === breakLoop || (done && running <= 0)) {371 done = true;372 //console.log('done iterCb')373 return callback(null);374 }375 replenish();376 }377 378 function handleError(err) {379 if (canceled) return380 awaiting = false;381 done = true;382 callback(err);383 }384 385 replenish();386}387 388var eachOfLimit$2 = (limit) => {389 return (obj, iteratee, callback) => {390 callback = once(callback);391 if (limit <= 0) {392 throw new RangeError('concurrency limit cannot be less than 1')393 }394 if (!obj) {395 return callback(null);396 }397 if (isAsyncGenerator(obj)) {398 return asyncEachOfLimit(obj, limit, iteratee, callback)399 }400 if (isAsyncIterable(obj)) {401 return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback)402 }403 var nextElem = createIterator(obj);404 var done = false;405 var canceled = false;406 var running = 0;407 var looping = false;408 409 function iterateeCallback(err, value) {410 if (canceled) return411 running -= 1;412 if (err) {413 done = true;414 callback(err);415 }416 else if (err === false) {417 done = true;418 canceled = true;419 }420 else if (value === breakLoop || (done && running <= 0)) {421 done = true;422 return callback(null);423 }424 else if (!looping) {425 replenish();426 }427 }428 429 function replenish () {430 looping = true;431 while (running < limit && !done) {432 var elem = nextElem();433 if (elem === null) {434 done = true;435 if (running <= 0) {436 callback(null);437 }438 return;439 }440 running += 1;441 iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));442 }443 looping = false;444 }445 446 replenish();447 };448};449 450/**451 * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a452 * time.453 *454 * @name eachOfLimit455 * @static456 * @memberOf module:Collections457 * @method458 * @see [async.eachOf]{@link module:Collections.eachOf}459 * @alias forEachOfLimit460 * @category Collection461 * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.462 * @param {number} limit - The maximum number of async operations at a time.463 * @param {AsyncFunction} iteratee - An async function to apply to each464 * item in `coll`. The `key` is the item's key, or index in the case of an465 * array.466 * Invoked with (item, key, callback).467 * @param {Function} [callback] - A callback which is called when all468 * `iteratee` functions have finished, or an error occurs. Invoked with (err).469 * @returns {Promise} a promise, if a callback is omitted470 */471function eachOfLimit(coll, limit, iteratee, callback) {472 return eachOfLimit$2(limit)(coll, wrapAsync(iteratee), callback);473}474 475var eachOfLimit$1 = awaitify(eachOfLimit, 4);476 477// eachOf implementation optimized for array-likes478function eachOfArrayLike(coll, iteratee, callback) {479 callback = once(callback);480 var index = 0,481 completed = 0,482 {length} = coll,483 canceled = false;484 if (length === 0) {485 callback(null);486 }487 488 function iteratorCallback(err, value) {489 if (err === false) {490 canceled = true;491 }492 if (canceled === true) return493 if (err) {494 callback(err);495 } else if ((++completed === length) || value === breakLoop) {496 callback(null);497 }498 }499 500 for (; index < length; index++) {501 iteratee(coll[index], index, onlyOnce(iteratorCallback));502 }503}504 505// a generic version of eachOf which can handle array, object, and iterator cases.506function eachOfGeneric (coll, iteratee, callback) {507 return eachOfLimit$1(coll, Infinity, iteratee, callback);508}509 510/**511 * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument512 * to the iteratee.513 *514 * @name eachOf515 * @static516 * @memberOf module:Collections517 * @method518 * @alias forEachOf519 * @category Collection520 * @see [async.each]{@link module:Collections.each}521 * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.522 * @param {AsyncFunction} iteratee - A function to apply to each523 * item in `coll`.524 * The `key` is the item's key, or index in the case of an array.525 * Invoked with (item, key, callback).526 * @param {Function} [callback] - A callback which is called when all527 * `iteratee` functions have finished, or an error occurs. Invoked with (err).528 * @returns {Promise} a promise, if a callback is omitted529 * @example530 *531 * // dev.json is a file containing a valid json object config for dev environment532 * // dev.json is a file containing a valid json object config for test environment533 * // prod.json is a file containing a valid json object config for prod environment534 * // invalid.json is a file with a malformed json object535 *536 * let configs = {}; //global variable537 * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'};538 * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'};539 *540 * // asynchronous function that reads a json file and parses the contents as json object541 * function parseFile(file, key, callback) {542 * fs.readFile(file, "utf8", function(err, data) {543 * if (err) return calback(err);544 * try {545 * configs[key] = JSON.parse(data);546 * } catch (e) {547 * return callback(e);548 * }549 * callback();550 * });551 * }552 *553 * // Using callbacks554 * async.forEachOf(validConfigFileMap, parseFile, function (err) {555 * if (err) {556 * console.error(err);557 * } else {558 * console.log(configs);559 * // configs is now a map of JSON data, e.g.560 * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}561 * }562 * });563 *564 * //Error handing565 * async.forEachOf(invalidConfigFileMap, parseFile, function (err) {566 * if (err) {567 * console.error(err);568 * // JSON parse error exception569 * } else {570 * console.log(configs);571 * }572 * });573 *574 * // Using Promises575 * async.forEachOf(validConfigFileMap, parseFile)576 * .then( () => {577 * console.log(configs);578 * // configs is now a map of JSON data, e.g.579 * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}580 * }).catch( err => {581 * console.error(err);582 * });583 *584 * //Error handing585 * async.forEachOf(invalidConfigFileMap, parseFile)586 * .then( () => {587 * console.log(configs);588 * }).catch( err => {589 * console.error(err);590 * // JSON parse error exception591 * });592 *593 * // Using async/await594 * async () => {595 * try {596 * let result = await async.forEachOf(validConfigFileMap, parseFile);597 * console.log(configs);598 * // configs is now a map of JSON data, e.g.599 * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}600 * }601 * catch (err) {602 * console.log(err);603 * }604 * }605 *606 * //Error handing607 * async () => {608 * try {609 * let result = await async.forEachOf(invalidConfigFileMap, parseFile);610 * console.log(configs);611 * }612 * catch (err) {613 * console.log(err);614 * // JSON parse error exception615 * }616 * }617 *618 */619function eachOf(coll, iteratee, callback) {620 var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;621 return eachOfImplementation(coll, wrapAsync(iteratee), callback);622}623 624var eachOf$1 = awaitify(eachOf, 3);625 626/**627 * Produces a new collection of values by mapping each value in `coll` through628 * the `iteratee` function. The `iteratee` is called with an item from `coll`629 * and a callback for when it has finished processing. Each of these callbacks630 * takes 2 arguments: an `error`, and the transformed item from `coll`. If631 * `iteratee` passes an error to its callback, the main `callback` (for the632 * `map` function) is immediately called with the error.633 *634 * Note, that since this function applies the `iteratee` to each item in635 * parallel, there is no guarantee that the `iteratee` functions will complete636 * in order. However, the results array will be in the same order as the637 * original `coll`.638 *639 * If `map` is passed an Object, the results will be an Array. The results640 * will roughly be in the order of the original Objects' keys (but this can641 * vary across JavaScript engines).642 *643 * @name map644 * @static645 * @memberOf module:Collections646 * @method647 * @category Collection648 * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.649 * @param {AsyncFunction} iteratee - An async function to apply to each item in650 * `coll`.651 * The iteratee should complete with the transformed item.652 * Invoked with (item, callback).653 * @param {Function} [callback] - A callback which is called when all `iteratee`654 * functions have finished, or an error occurs. Results is an Array of the655 * transformed items from the `coll`. Invoked with (err, results).656 * @returns {Promise} a promise, if no callback is passed657 * @example658 *659 * // file1.txt is a file that is 1000 bytes in size660 * // file2.txt is a file that is 2000 bytes in size661 * // file3.txt is a file that is 3000 bytes in size662 * // file4.txt does not exist663 *664 * const fileList = ['file1.txt','file2.txt','file3.txt'];665 * const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];666 *667 * // asynchronous function that returns the file size in bytes668 * function getFileSizeInBytes(file, callback) {669 * fs.stat(file, function(err, stat) {670 * if (err) {671 * return callback(err);672 * }673 * callback(null, stat.size);674 * });675 * }676 *677 * // Using callbacks678 * async.map(fileList, getFileSizeInBytes, function(err, results) {679 * if (err) {680 * console.log(err);681 * } else {682 * console.log(results);683 * // results is now an array of the file size in bytes for each file, e.g.684 * // [ 1000, 2000, 3000]685 * }686 * });687 *688 * // Error Handling689 * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) {690 * if (err) {691 * console.log(err);692 * // [ Error: ENOENT: no such file or directory ]693 * } else {694 * console.log(results);695 * }696 * });697 *698 * // Using Promises699 * async.map(fileList, getFileSizeInBytes)700 * .then( results => {701 * console.log(results);702 * // results is now an array of the file size in bytes for each file, e.g.703 * // [ 1000, 2000, 3000]704 * }).catch( err => {705 * console.log(err);706 * });707 *708 * // Error Handling709 * async.map(withMissingFileList, getFileSizeInBytes)710 * .then( results => {711 * console.log(results);712 * }).catch( err => {713 * console.log(err);714 * // [ Error: ENOENT: no such file or directory ]715 * });716 *717 * // Using async/await718 * async () => {719 * try {720 * let results = await async.map(fileList, getFileSizeInBytes);721 * console.log(results);722 * // results is now an array of the file size in bytes for each file, e.g.723 * // [ 1000, 2000, 3000]724 * }725 * catch (err) {726 * console.log(err);727 * }728 * }729 *730 * // Error Handling731 * async () => {732 * try {733 * let results = await async.map(withMissingFileList, getFileSizeInBytes);734 * console.log(results);735 * }736 * catch (err) {737 * console.log(err);738 * // [ Error: ENOENT: no such file or directory ]739 * }740 * }741 *742 */743function map (coll, iteratee, callback) {744 return _asyncMap(eachOf$1, coll, iteratee, callback)745}746var map$1 = awaitify(map, 3);747 748/**749 * Applies the provided arguments to each function in the array, calling750 * `callback` after all functions have completed. If you only provide the first751 * argument, `fns`, then it will return a function which lets you pass in the752 * arguments as if it were a single function call. If more arguments are753 * provided, `callback` is required while `args` is still optional. The results754 * for each of the applied async functions are passed to the final callback755 * as an array.756 *757 * @name applyEach758 * @static759 * @memberOf module:ControlFlow760 * @method761 * @category Control Flow762 * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s763 * to all call with the same arguments764 * @param {...*} [args] - any number of separate arguments to pass to the765 * function.766 * @param {Function} [callback] - the final argument should be the callback,767 * called when all functions have completed processing.768 * @returns {AsyncFunction} - Returns a function that takes no args other than769 * an optional callback, that is the result of applying the `args` to each770 * of the functions.771 * @example772 *773 * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket')774 *775 * appliedFn((err, results) => {776 * // results[0] is the results for `enableSearch`777 * // results[1] is the results for `updateSchema`778 * });779 *780 * // partial application example:781 * async.each(782 * buckets,783 * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(),784 * callback785 * );786 */787var applyEach = applyEach$1(map$1);788 789/**790 * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.791 *792 * @name eachOfSeries793 * @static794 * @memberOf module:Collections795 * @method796 * @see [async.eachOf]{@link module:Collections.eachOf}797 * @alias forEachOfSeries798 * @category Collection799 * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.800 * @param {AsyncFunction} iteratee - An async function to apply to each item in801 * `coll`.802 * Invoked with (item, key, callback).803 * @param {Function} [callback] - A callback which is called when all `iteratee`804 * functions have finished, or an error occurs. Invoked with (err).805 * @returns {Promise} a promise, if a callback is omitted806 */807function eachOfSeries(coll, iteratee, callback) {808 return eachOfLimit$1(coll, 1, iteratee, callback)809}810var eachOfSeries$1 = awaitify(eachOfSeries, 3);811 812/**813 * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.814 *815 * @name mapSeries816 * @static817 * @memberOf module:Collections818 * @method819 * @see [async.map]{@link module:Collections.map}820 * @category Collection821 * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.822 * @param {AsyncFunction} iteratee - An async function to apply to each item in823 * `coll`.824 * The iteratee should complete with the transformed item.825 * Invoked with (item, callback).826 * @param {Function} [callback] - A callback which is called when all `iteratee`827 * functions have finished, or an error occurs. Results is an array of the828 * transformed items from the `coll`. Invoked with (err, results).829 * @returns {Promise} a promise, if no callback is passed830 */831function mapSeries (coll, iteratee, callback) {832 return _asyncMap(eachOfSeries$1, coll, iteratee, callback)833}834var mapSeries$1 = awaitify(mapSeries, 3);835 836/**837 * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.838 *839 * @name applyEachSeries840 * @static841 * @memberOf module:ControlFlow842 * @method843 * @see [async.applyEach]{@link module:ControlFlow.applyEach}844 * @category Control Flow845 * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all846 * call with the same arguments847 * @param {...*} [args] - any number of separate arguments to pass to the848 * function.849 * @param {Function} [callback] - the final argument should be the callback,850 * called when all functions have completed processing.851 * @returns {AsyncFunction} - A function, that when called, is the result of852 * appling the `args` to the list of functions. It takes no args, other than853 * a callback.854 */855var applyEachSeries = applyEach$1(mapSeries$1);856 857const PROMISE_SYMBOL = Symbol('promiseCallback');858 859function promiseCallback () {860 let resolve, reject;861 function callback (err, ...args) {862 if (err) return reject(err)863 resolve(args.length > 1 ? args : args[0]);864 }865 866 callback[PROMISE_SYMBOL] = new Promise((res, rej) => {867 resolve = res,868 reject = rej;869 });870 871 return callback872}873 874/**875 * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on876 * their requirements. Each function can optionally depend on other functions877 * being completed first, and each function is run as soon as its requirements878 * are satisfied.879 *880 * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence881 * will stop. Further tasks will not execute (so any other functions depending882 * on it will not run), and the main `callback` is immediately called with the883 * error.884 *885 * {@link AsyncFunction}s also receive an object containing the results of functions which886 * have completed so far as the first argument, if they have dependencies. If a887 * task function has no dependencies, it will only be passed a callback.888 *889 * @name auto890 * @static891 * @memberOf module:ControlFlow892 * @method893 * @category Control Flow894 * @param {Object} tasks - An object. Each of its properties is either a895 * function or an array of requirements, with the {@link AsyncFunction} itself the last item896 * in the array. The object's key of a property serves as the name of the task897 * defined by that property, i.e. can be used when specifying requirements for898 * other tasks. The function receives one or two arguments:899 * * a `results` object, containing the results of the previously executed900 * functions, only passed if the task has any dependencies,901 * * a `callback(err, result)` function, which must be called when finished,902 * passing an `error` (which can be `null`) and the result of the function's903 * execution.904 * @param {number} [concurrency=Infinity] - An optional `integer` for905 * determining the maximum number of tasks that can be run in parallel. By906 * default, as many as possible.907 * @param {Function} [callback] - An optional callback which is called when all908 * the tasks have been completed. It receives the `err` argument if any `tasks`909 * pass an error to their callback. Results are always returned; however, if an910 * error occurs, no further `tasks` will be performed, and the results object911 * will only contain partial results. Invoked with (err, results).912 * @returns {Promise} a promise, if a callback is not passed913 * @example914 *915 * //Using Callbacks916 * async.auto({917 * get_data: function(callback) {918 * // async code to get some data919 * callback(null, 'data', 'converted to array');920 * },921 * make_folder: function(callback) {922 * // async code to create a directory to store a file in923 * // this is run at the same time as getting the data924 * callback(null, 'folder');925 * },926 * write_file: ['get_data', 'make_folder', function(results, callback) {927 * // once there is some data and the directory exists,928 * // write the data to a file in the directory929 * callback(null, 'filename');930 * }],931 * email_link: ['write_file', function(results, callback) {932 * // once the file is written let's email a link to it...933 * callback(null, {'file':results.write_file, 'email':'user@example.com'});934 * }]935 * }, function(err, results) {936 * if (err) {937 * console.log('err = ', err);938 * }939 * console.log('results = ', results);940 * // results = {941 * // get_data: ['data', 'converted to array']942 * // make_folder; 'folder',943 * // write_file: 'filename'944 * // email_link: { file: 'filename', email: 'user@example.com' }945 * // }946 * });947 *948 * //Using Promises949 * async.auto({950 * get_data: function(callback) {951 * console.log('in get_data');952 * // async code to get some data953 * callback(null, 'data', 'converted to array');954 * },955 * make_folder: function(callback) {956 * console.log('in make_folder');957 * // async code to create a directory to store a file in958 * // this is run at the same time as getting the data959 * callback(null, 'folder');960 * },961 * write_file: ['get_data', 'make_folder', function(results, callback) {962 * // once there is some data and the directory exists,963 * // write the data to a file in the directory964 * callback(null, 'filename');965 * }],966 * email_link: ['write_file', function(results, callback) {967 * // once the file is written let's email a link to it...968 * callback(null, {'file':results.write_file, 'email':'user@example.com'});969 * }]970 * }).then(results => {971 * console.log('results = ', results);972 * // results = {973 * // get_data: ['data', 'converted to array']974 * // make_folder; 'folder',975 * // write_file: 'filename'976 * // email_link: { file: 'filename', email: 'user@example.com' }977 * // }978 * }).catch(err => {979 * console.log('err = ', err);980 * });981 *982 * //Using async/await983 * async () => {984 * try {985 * let results = await async.auto({986 * get_data: function(callback) {987 * // async code to get some data988 * callback(null, 'data', 'converted to array');989 * },990 * make_folder: function(callback) {991 * // async code to create a directory to store a file in992 * // this is run at the same time as getting the data993 * callback(null, 'folder');994 * },995 * write_file: ['get_data', 'make_folder', function(results, callback) {996 * // once there is some data and the directory exists,997 * // write the data to a file in the directory998 * callback(null, 'filename');999 * }],1000 * email_link: ['write_file', function(results, callback) {1001 * // once the file is written let's email a link to it...1002 * callback(null, {'file':results.write_file, 'email':'user@example.com'});1003 * }]1004 * });1005 * console.log('results = ', results);1006 * // results = {1007 * // get_data: ['data', 'converted to array']1008 * // make_folder; 'folder',1009 * // write_file: 'filename'1010 * // email_link: { file: 'filename', email: 'user@example.com' }1011 * // }1012 * }1013 * catch (err) {1014 * console.log(err);1015 * }1016 * }1017 *1018 */1019function auto(tasks, concurrency, callback) {1020 if (typeof concurrency !== 'number') {1021 // concurrency is optional, shift the args.1022 callback = concurrency;1023 concurrency = null;1024 }1025 callback = once(callback || promiseCallback());1026 var numTasks = Object.keys(tasks).length;1027 if (!numTasks) {1028 return callback(null);1029 }1030 if (!concurrency) {1031 concurrency = numTasks;1032 }1033 1034 var results = {};1035 var runningTasks = 0;1036 var canceled = false;1037 var hasError = false;1038 1039 var listeners = Object.create(null);1040 1041 var readyTasks = [];1042 1043 // for cycle detection:1044 var readyToCheck = []; // tasks that have been identified as reachable1045 // without the possibility of returning to an ancestor task1046 var uncheckedDependencies = {};1047 1048 Object.keys(tasks).forEach(key => {1049 var task = tasks[key];1050 if (!Array.isArray(task)) {1051 // no dependencies1052 enqueueTask(key, [task]);1053 readyToCheck.push(key);1054 return;1055 }1056 1057 var dependencies = task.slice(0, task.length - 1);1058 var remainingDependencies = dependencies.length;1059 if (remainingDependencies === 0) {1060 enqueueTask(key, task);1061 readyToCheck.push(key);1062 return;1063 }1064 uncheckedDependencies[key] = remainingDependencies;1065 1066 dependencies.forEach(dependencyName => {1067 if (!tasks[dependencyName]) {1068 throw new Error('async.auto task `' + key +1069 '` has a non-existent dependency `' +1070 dependencyName + '` in ' +1071 dependencies.join(', '));1072 }1073 addListener(dependencyName, () => {1074 remainingDependencies--;1075 if (remainingDependencies === 0) {1076 enqueueTask(key, task);1077 }1078 });1079 });1080 });1081 1082 checkForDeadlocks();1083 processQueue();1084 1085 function enqueueTask(key, task) {1086 readyTasks.push(() => runTask(key, task));1087 }1088 1089 function processQueue() {1090 if (canceled) return1091 if (readyTasks.length === 0 && runningTasks === 0) {1092 return callback(null, results);1093 }1094 while(readyTasks.length && runningTasks < concurrency) {1095 var run = readyTasks.shift();1096 run();1097 }1098 1099 }1100 1101 function addListener(taskName, fn) {1102 var taskListeners = listeners[taskName];1103 if (!taskListeners) {1104 taskListeners = listeners[taskName] = [];1105 }1106 1107 taskListeners.push(fn);1108 }1109 1110 function taskComplete(taskName) {1111 var taskListeners = listeners[taskName] || [];1112 taskListeners.forEach(fn => fn());1113 processQueue();1114 }1115 1116 1117 function runTask(key, task) {1118 if (hasError) return;1119 1120 var taskCallback = onlyOnce((err, ...result) => {1121 runningTasks--;1122 if (err === false) {1123 canceled = true;1124 return1125 }1126 if (result.length < 2) {1127 [result] = result;1128 }1129 if (err) {1130 var safeResults = {};1131 Object.keys(results).forEach(rkey => {1132 safeResults[rkey] = results[rkey];1133 });1134 safeResults[key] = result;1135 hasError = true;1136 listeners = Object.create(null);1137 if (canceled) return1138 callback(err, safeResults);1139 } else {1140 results[key] = result;1141 taskComplete(key);1142 }1143 });1144 1145 runningTasks++;1146 var taskFn = wrapAsync(task[task.length - 1]);1147 if (task.length > 1) {1148 taskFn(results, taskCallback);1149 } else {1150 taskFn(taskCallback);1151 }1152 }1153 1154 function checkForDeadlocks() {1155 // Kahn's algorithm1156 // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm1157 // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html1158 var currentTask;1159 var counter = 0;1160 while (readyToCheck.length) {1161 currentTask = readyToCheck.pop();1162 counter++;1163 getDependents(currentTask).forEach(dependent => {1164 if (--uncheckedDependencies[dependent] === 0) {1165 readyToCheck.push(dependent);1166 }1167 });1168 }1169 1170 if (counter !== numTasks) {1171 throw new Error(1172 'async.auto cannot execute tasks due to a recursive dependency'1173 );1174 }1175 }1176 1177 function getDependents(taskName) {1178 var result = [];1179 Object.keys(tasks).forEach(key => {1180 const task = tasks[key];1181 if (Array.isArray(task) && task.indexOf(taskName) >= 0) {1182 result.push(key);1183 }1184 });1185 return result;1186 }1187 1188 return callback[PROMISE_SYMBOL]1189}1190 1191var FN_ARGS = /^(?:async\s)?(?:function)?\s*(?:\w+\s*)?\(([^)]+)\)(?:\s*{)/;1192var ARROW_FN_ARGS = /^(?:async\s)?\s*(?:\(\s*)?((?:[^)=\s]\s*)*)(?:\)\s*)?=>/;1193var FN_ARG_SPLIT = /,/;1194var FN_ARG = /(=.+)?(\s*)$/;1195 1196function stripComments(string) {1197 let stripped = '';1198 let index = 0;1199 let endBlockComment = string.indexOf('*/');1200 while (index < string.length) {