search for a stub in a stream, return a promise
179034
function search(stream, needle) {

  var ss = new streamsearch(needle),
      push = ss.push.bind(ss);
  ss.maxMatches = 1;

  var defered = defer();
  stream.on("data", push);

  stream.once("finish", function(){
    defered.reject("No stub found in stream")
  });

  var pos = 0;

  ss.on("info", function(isMatch, data, start, end){
    if(data)
      pos += end - start;

    if(!isMatch)
      return;

    stream.removeListener("data", push);
    defered.resolve(pos);
  });
  return defered;
}
15109
function(options, filename){	    
	    Joi.assert(filename, Joi.string())
	    return new Promise(function(resolve, reject){

	        try{	            

	            var writestream = fs.createWriteStream(filename);
	            request(options).pipe(writestream);

	            writestream.on('finish', function(err){                 
	                if(err){
	                    reject({
	                        "path" : filename,
	                        "status" : false,
	                        "error": err
	                    });
	                }else{
	                    resolve({
	                        "path" : filename,
	                        "status" : true
	                    });
	                }
	            });

	        }catch(e){
	            reject(e);
	        }
	    });
	}
1347286
function (stream, destPath) {
    let data = '';
    return new Promise(function (resolve, reject) {
        stream.on('error', reject);
        stream.on('data', function (d) {
            data += d.toString();
        });
        stream.on('end', function () {
            fs.outputFile(destPath, data, function (err) {
                if (!err) {
                    resolve();
                } else {
                    reject(err);
                }
            });
        });
    });
}
391778
function eventPromiseCache(source, cacheProp, eventName, fn) {
  if (!source[cacheProp]) {
    source[cacheProp] = {}
  }

  const cache = source[cacheProp]
  if (!cache[eventName]) {
    cache[eventName] = new Promise((resolve, reject) => {
      function deleteAnd(fn) {
        // delete wrapper
        return result => {
          delete cache[eventName]
          fn(result)
        }
      }

      fn(deleteAnd(resolve), deleteAnd(reject))
    })
  }

  return cache[eventName]
}
182413
async function repeatablePromise (initialAssumptions, assumptionsFromResult, promiseGenerator) {
    let promise = promiseGenerator(initialAssumptions);
    let result = await promise;
    let finalAssumptions = assumptionsFromResult(result);
    if (JSON.stringify(initialAssumptions) === JSON.stringify(finalAssumptions)) {
        return promise;
    } else {
        return promiseGenerator(finalAssumptions);
    }
}
840226
function wrapWithDispatch(asyncItems) {
  return asyncItems.map((item) => {
    const { key } = item;
    if (!key) return item;

    return {
      ...item,
      promise: (options) => {
        const { store: { dispatch } } = options;
        const next = item.promise(options);

        // NOTE: possibly refactor this with a breaking change in mind for future versions
        // we can return result of processed promise/thunk if need be
        if (isPromise(next)) {
          dispatch(load(key));
          // add action dispatchers
          next
            .then(data => dispatch(loadSuccess(key, data)))
            .catch(err => dispatch(loadFail(key, err)));
        } else if (next) {
          dispatch(loadSuccess(key, next));
        }

        return next;
      },
    };
  });
}
306165
function fetch(filename) {
        var att = atts[filename];
        var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +
          '?rev=' + doc._rev;
        return ajaxPromise(opts, {
          method: 'GET',
          url: genDBUrl(host, path),
          binary: true
        }).then(function (blob) {
          if (opts.binary) {
            return blob;
          }
          return new Promise(function (resolve) {
            pouchdbBinaryUtils.blobOrBufferToBase64(blob, resolve);
          });
        }).then(function (data) {
          delete att.stub;
          delete att.length;
          att.data = data;
        });
      }
572945
function Promise(executor) {
  if (typeof executor !== 'function') {
    throw new TypeError();
  }

  if (!(this instanceof Promise)) {
    return new Promise(executor);
  }

  if (executor !== blessed.be) {
    blessed.be(this, executor, true);
  }
}
232720
function charybdis (iterator) {
  iterator = iterator || K
  const stream = new Writable({objectMode: true})
  const deferred = Promise.defer()

  const stats = stream.stats = {
    objects: 0,
    operations: 0,
    pending: 0,
    start: Date.now(),
    inEnd: 0,
    end: 0,
  }

  var sources = refcount()
  stream.on('pipe', onPipe)
  function onPipe (src) {
    sources.push()
    src.on('end', function () {
      sources.pop()
    })
    src.once('error', cleanup)
  }
  sources.on('clear', function () {
    stats.inEnd = Date.now()
    stream.emit('inEnd')
    tryResolve()
  })

  stream._write = function(obj, encoding, cb) {
    stats.objects++
    var op = iterator(obj)
    if (!op || !op.then) {
      tick()
      return cb()
    }

    stats.pending++
    stats.operations++

    tick()

    op.then(function () {
      stats.pending--
      tryResolve()
    },
    cleanup)

    cb()
  }

  function tryResolve() {
    // in streams ended and no operations pending?
    if (stats.inEnd && !stats.pending) { cleanup() }
    else tick()
  }

  function tick() {
    stream.emit('tick', stats)
  }

  function cleanup(err) {
    stream.removeListener('pipe', onPipe)
    sources.removeAllListeners()

    if (err) {
      deferred.reject(err)
    }
    stats.end = Date.now()

    deferred.resolve(stats)
  }

  stream.then = deferred.promise.then.bind(deferred.promise)

  return stream
}
785532
function globPromise (file) {
    return new Promise((resolve, reject) => {
      glob(file, (err, files) => {
        if (err) {
          reject(err)
        } else {
          resolve(files)
        }
      })
    })
  }
219067
function promiseReadFile(path, encoding = 'utf-8') {
  return new Promise((resolve, reject) => {
    fs.readFile(path, encoding, (err, content) => {
      if (err) reject(err);

      resolve({
        path,
        fileName: path.split('/').pop(),
        content
      });
    });
  });
}
815590
function getInputAsStream(input) {

    return new Promise(function(resolve, reject) {

        if (input.write) {

            // already a stream
            resolve(input);
        }
        else {

            // read from file
            fs.readFileAsync(input, 'utf-8').then(function(data) {

                // convert file string into stream and pipe into jsdoc-parse
                var stream = string2stream(data);

                // return stream
                resolve(stream);

            })
            .catch(function(err) {
                reject(err);
            });
        }

    });
}
446708
function stream (env) {
    let parseStream = parseFilter(env)

    let filter = through.obj((file, enc, cb) => cb(), function (cb) {
      parseStream.promise.then(data => {
        this.push(data)
        cb()
      }, cb)
    })

    return pipe(parseStream, filter)
  }
95793
async function readLogStream(file, instance) {
    return new Promise(resolve => {
        var stream = fs.createReadStream(file, { encoding: 'utf8', highWaterMark: instance.chunkSize });
        var hasStarted = false;
        // Split data into chunks so we dont stall the client
        stream.on('data', chunk => {
            if (!hasStarted) instance.emit("parsingStarted");
            hasStarted = true;
            var lines = chunk.toString().split("\n");
            // Pause stream until this chunk is completed to avoid spamming the thread
            stream.pause();
            async.each(lines, function (line, callback) {
                instance.registerMatch(line);
                callback();
            }, function (err) {
                setTimeout(() => {
                    stream.resume();
                }, instance.chunkInterval);
            });
        });
        stream.on('end', () => {
            instance.emit("parsingComplete");
            resolve();
            stream.close();
        });
    });
}
1291639
function fetchFile(address, filepath) {
    return get(address)
        .then(res => new Promise((fulfill, reject) => {
            const file = fs.createWriteStream(filepath);
            res.on('error', err => {
                // reading error
                file.close();
                fs.unlink(filepath, err => {   // best effort
                    if (err) console.error(err);
                });
                reject(err);
            });
            file.on('error', err => {
                // writing error
                fs.unlink(filepath, err => {   // best effort
                    if (err) console.error(err);
                });
                reject(err);
            });
            file.on('finish', () => {
                fulfill(filepath);
            });
            res.pipe(file);
        }));
}
1031224
function resolve(promiseLike) {

    // Return if already promised
    if (promiseLike instanceof Promise) {
        return promiseLike;
    }

    var promises = [];

    if (promiseLike instanceof Array) {
        promiseLike.forEach((promiseLikeEntry) => {
            promises.push(promisify(promiseLikeEntry));
        });
    }
    else if (promiseLike && (typeof promiseLike === "object")) {
        Object.keys(promiseLike).forEach((key) => {
            promises.push(promisify(promiseLike[key]));
        });
    }
    else {
        return promisify(promiseLike);
    }

    return Promise.all(promises).then((result) => {
        if (promiseLike instanceof Array) {
            return result;
        }

        var response = {};
        Object.keys(promiseLike).forEach((key, index) => {
            response[key] = result[index];
        });

        return response;
    });
}
676609
function promiseTry(callback) {
  try {
    const maybePromise = callback();

    if (isPromise(maybePromise)) {
      return maybePromise;
    } else {
      return Promise.resolve(maybePromise);
    }
  } catch (err) {
    return Promise.reject(err);
  }
}