end FUNCTION next() 
FUNCTION: onResponse( repo, idx )
Returns a response callback.

@private
@param {String} repo - repository
@param {Number} idx - request index
@returns {Function} response callback
543420
function onResponse( repo, idx ) {
		/**
		* FUNCTION: onResponse( error, response, body )
		*	Callback invoked upon receiving a request response.
		*
		* @private
		* @param {Error|Null} error - error object
		* @param {Object} response - HTTP response object
		* @param {String} body - response body
		* @returns {Void}
		*/
		return function onResponse( error, response, body ) {
			if ( eFLG ) {
				return;
			}
			debug( 'Response received for repository `%s` (%d).', repo, idx );
			if ( arguments.length === 1 ) {
				eFLG = true;
				debug( 'Encountered an application-level error for repository `%s` (%d): %s', repo, idx, error.message );
				return clbk( error );
			}
			if ( error ) {
				debug( 'Failed to resolve file for repository `%s` (%d): %s', repo, idx, error.message );
				out.failures[ repo ] = error.message;
				fcount += 1;
			} else {
				debug( 'Successfully resolved file for repository `%s` (%d).', repo, idx );
				out.data[ repo ] = body;
				scount += 1;
			}
			count += 1;
			debug( 'Request %d of %d complete.', count, len );
			next();
		}; // end FUNCTION onResponse()
	}
508387
def success_response(self, method_resp, **kw):
        
        resp = {
            'status': True,
            'indexing': config.is_indexing(self.working_dir),
            'lastblock': virtualchain_hooks.get_last_block(self.working_dir),
        }

        resp.update(kw)
        resp.update(method_resp)
        
        if self.is_stale():
            # our state is stale
            resp['stale'] = True
            resp['warning'] = 'Daemon has not reindexed since {}'.format(self.last_indexing_time)

        return resp
344848
function transformResponse(transform) {

  assert.ok(transform);
  assert.ok(transform instanceof Function);

  var originalStatus, originalJson, reqClosure;

  return function (req, res, next) {
    originalStatus = res.status;
    originalJson = res.json;
    reqClosure = req;
    res.status = setStatus;
    res.json = sendJson;
    return next();
  }

  function setStatus(status) {
    this.__status = status;
    return this;
  }

  function sendJson(body) {
    this.__body = body;
    var B = new Bundle(transform, reqClosure, this);
    originalStatus.call(this, B.status);
    return originalJson.call(this, B.body);
  }

}
231022
function(request, response, next) {
		var apptkn;
		if (!utils.Misc.isNullOrUndefined(request.get(X_BOLT_APP_TOKEN))) {
			apptkn = request.get(X_BOLT_APP_TOKEN);
		}
		else {
			var error = new Error(errors['110']);
			response.end(utils.Misc.createResponse(null, error, 110));
			return;
		}

		var name = __getAppFromAppToken(apptkn, request);
		if (utils.Misc.isNullOrUndefined(name)) {
			var error = new Error(errors['113']);
			response.end(utils.Misc.createResponse(null, error, 113));
			return;
		}
		var appnm = utils.String.trim(name.toLowerCase());
		var dbOwner = request.body.db || request.body.app || appnm;

		models.collection.findOne({ name: request.params.collection, app: dbOwner }, function(collError, collection){
			if (!utils.Misc.isNullOrUndefined(collError)){
				response.end(utils.Misc.createResponse(null, collError));
			}
			else if(utils.Misc.isNullOrUndefined(collection)){
				var errColl = new Error(errors['703']);
				response.end(utils.Misc.createResponse(null, errColl, 703));
			}
			else {
				//allow the owner to pass
				if (appnm == collection.app.toLowerCase()) {
					next();
					return;
				}

				if (!utils.Misc.isNullOrUndefined(collection.tenants)) { //tenants allowed
					if ("*" == collection.tenants) { //every body is allowed
						next();
						return;
					}
					//there is a tenant list; are u listed?
					else if (collection.tenants.map(function(value){ return value.toLowerCase(); }).indexOf(appnm) > -1) {
						next();
						return;
					}
				}

				//no guests allowed

				var error = new Error(errors['704']);
				response.end(utils.Misc.createResponse(null, error, 704));
			}
		});
	}
986067
async function initRepo({
  repository,
  token,
  endpoint,
  forkMode,
  forkToken,
  gitPrivateKey,
  gitFs,
  localDir,
  includeForks,
}) {
  logger.debug(`initRepo("${repository}")`);
  const opts = hostRules.find({ platform: 'github' }, { token, endpoint });
  if (!opts.token) {
    throw new Error(`No token found for GitHub repository ${repository}`);
  }
  hostRules.update({ ...opts, platform: 'github', default: true });
  logger.info('Authenticated as user: ' + (await getRenovateUsername()));
  logger.info('Using renovate version: ' + global.renovateVersion);
  // config is used by the platform api itself, not necessary for the app layer to know
  cleanRepo();
  config.isGhe = endpoint && !endpoint.startsWith('https://api.github.com');
  config.localDir = localDir;
  config.platform = 'github';
  config.repository = repository;
  [config.repositoryOwner, config.repositoryName] = repository.split('/');
  config.gitPrivateKey = gitPrivateKey;
  // platformConfig is passed back to the app layer and contains info about the platform they require
  const platformConfig = {};
  let res;
  try {
    res = await get(`repos/${repository}`);
    logger.trace({ repositoryDetails: res.body }, 'Repository details');
    // istanbul ignore if
    if (res.body.fork && gitFs && !includeForks) {
      try {
        const renovateConfig = JSON.parse(
          Buffer.from(
            (await get(
              `repos/${config.repository}/contents/${defaultConfigFile}`
            )).body.content,
            'base64'
          ).toString()
        );
        if (!renovateConfig.includeForks) {
          throw new Error();
        }
      } catch (err) {
        throw new Error('fork');
      }
    }
    // istanbul ignore if
    if (res.body.full_name && res.body.full_name !== repository) {
      logger.info(
        { repository, this_repository: res.body.full_name },
        'Repository has been renamed'
      );
      throw new Error('renamed');
    }
    if (res.body.archived) {
      logger.info(
        'Repository is archived - throwing error to abort renovation'
      );
      throw new Error('archived');
    }
    platformConfig.privateRepo = res.body.private === true;
    platformConfig.isFork = res.body.fork === true;
    const owner = res.body.owner.login;
    logger.debug(`${repository} owner = ${owner}`);
    // Use default branch as PR target unless later overridden.
    config.defaultBranch = res.body.default_branch;
    // Base branch may be configured but defaultBranch is always fixed
    config.baseBranch = config.defaultBranch;
    logger.debug(`${repository} default branch = ${config.baseBranch}`);
    // GitHub allows administrators to block certain types of merge, so we need to check it
    if (res.body.allow_rebase_merge) {
      config.mergeMethod = 'rebase';
    } else if (res.body.allow_squash_merge) {
      config.mergeMethod = 'squash';
    } else if (res.body.allow_merge_commit) {
      config.mergeMethod = 'merge';
    } else {
      // This happens if we don't have Administrator read access, it is not a critical error
      logger.info('Could not find allowed merge methods for repo');
    }
  } catch (err) /* istanbul ignore next */ {
    logger.debug('Caught initRepo error');
    if (err.message === 'archived' || err.message === 'renamed') {
      throw err;
    }
    if (err.statusCode === 403) {
      throw new Error('forbidden');
    }
    if (err.statusCode === 404) {
      throw new Error('not-found');
    }
    if (err.message.startsWith('Repository access blocked')) {
      throw new Error('blocked');
    }
    if (err.message === 'fork') {
      throw err;
    }
    logger.info({ err }, 'Unknown GitHub initRepo error');
    throw err;
  }
  // This shouldn't be necessary, but occasional strange errors happened until it was added
  config.issueList = null;
  config.prList = null;
  config.openPrList = null;
  config.closedPrList = null;
  config.storage = new Storage();
  await config.storage.initRepo(config);
  if (forkMode) {
    logger.info('Bot is in forkMode');
    config.forkToken = forkToken;
    // Save parent SHA then delete
    const parentSha = await getBaseCommitSHA();
    config.baseCommitSHA = null;
    // save parent name then delete
    config.parentRepo = config.repository;
    config.repository = null;
    // Get list of existing repos
    const existingRepos = (await get('user/repos?per_page=100', {
      token: forkToken || opts.token,
      paginate: true,
    })).body.map(r => r.full_name);
    try {
      config.repository = (await get.post(`repos/${repository}/forks`, {
        token: forkToken || opts.token,
      })).body.full_name;
    } catch (err) /* istanbul ignore next */ {
      logger.info({ err }, 'Error forking repository');
      throw new Error('cannot-fork');
    }
    if (existingRepos.includes(config.repository)) {
      logger.info(
        { repository_fork: config.repository },
        'Found existing fork'
      );
      // Need to update base branch
      logger.debug(
        { baseBranch: config.baseBranch, parentSha },
        'Setting baseBranch ref in fork'
      );
      // This is a lovely "hack" by GitHub that lets us force update our fork's master
      // with the base commit from the parent repository
      try {
        await get.patch(
          `repos/${config.repository}/git/refs/heads/${config.baseBranch}`,
          {
            body: {
              sha: parentSha,
              force: true,
            },
            token: forkToken || opts.token,
          }
        );
      } catch (err) /* istanbul ignore next */ {
        if (
          err.statusCode === 422 &&
          err.message.startsWith('Object does not exist')
        ) {
          throw new Error('repository-changed');
        }
      }
    } else {
      logger.info({ repository_fork: config.repository }, 'Created fork');
      // Wait an arbitrary 30s to hopefully give GitHub enough time for forking to complete
      await delay(30000);
    }
    await config.storage.initRepo(config);
  }

  // istanbul ignore if
  if (gitFs) {
    logger.debug('Enabling Git FS');
    let { host } = URL.parse(opts.endpoint);
    if (host === 'api.github.com') {
      host = null;
    }
    host = host || 'github.com';
    const url = GitStorage.getUrl({
      gitFs,
      auth:
        config.forkToken ||
        (global.appMode ? `x-access-token:${opts.token}` : opts.token),
      hostname: host,
      repository: config.repository,
    });
    config.storage = new GitStorage();
    await config.storage.initRepo({
      ...config,
      url,
    });
  }

  return platformConfig;
}
838012
function Response(json) {
		// PRIVATE MEMBERS //

		var checkBounds = function (idx) {
			// Ensures that an index is within the number of candidates
			if (idx >= json.length || idx < 0) {
				if (json.length == 0)
					throw new Error("Candidate index is out of bounds (no candidates returned; requested " + idx + ")");
				else
					throw new Error("Candidate index is out of bounds (" + json.length + " candidates; indicies 0 through " +
						(json.length - 1) + " available; requested " + idx + ")");
			}
		};

		var maybeDefault = function (idx) {
			// Assigns index to 0, the default value, if no value is passed in
			return typeof idx === "undefined" ? 0 : idx;
		};

		// PUBLIC-FACING MEMBERS //

		this.raw = json;
		this.length = json.length;

		this.isValid = function () {
			return (this.length === 1 &&
				(this.raw[0].analysis.verification_status === "Verified" ||
					this.raw[0].analysis.verification_status === "Partial" ||
					(typeof this.raw[0].analysis.dpv_match_code !== "undefined" && this.raw[0].analysis.dpv_match_code !== "N")));
		};

		this.isInvalid = function () {
			return (this.length === 0 ||
				(this.length === 1 &&
					(this.raw[0].analysis.verification_status === "None" ||
						this.raw[0].analysis.address_precision === "None" ||
						this.raw[0].analysis.address_precision === "AdministrativeArea" ||
						this.raw[0].analysis.address_precision === "Locality" ||
						this.raw[0].analysis.address_precision === "Thoroughfare" ||
						this.raw[0].analysis.dpv_match_code === "N" ||
						(typeof this.raw[0].analysis.verification_status === "undefined" &&
							typeof this.raw[0].analysis.dpv_match_code === "undefined"))));
		};

		this.isAmbiguous = function () {
			return this.length > 1;
		};

		this.isMissingSecondary = function (idx) {
			idx = maybeDefault(idx);
			checkBounds(idx);
			return (this.raw[idx].analysis.dpv_footnotes && this.raw[idx].analysis.dpv_footnotes.indexOf("N1") > -1) ||
				(this.raw[idx].analysis.dpv_footnotes && this.raw[idx].analysis.dpv_footnotes.indexOf("R1") > -1) ||
				(this.raw[idx].analysis.footnotes && this.raw[idx].analysis.footnotes.indexOf("H#") > -1);
		};
	}
1109974
function (responseObject, next) {
    responseObject.fileResult = new FileResult(share, directory, file);
    if (!responseObject.error) {
      responseObject.fileResult.exists = true;
      responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers);
      
    } else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) {
      responseObject.error = null;
      responseObject.fileResult.exists = false;
      responseObject.response.isSuccessful = true;
    }

    var finalCallback = function (returnObject) {
      callback(returnObject.error, returnObject.fileResult, returnObject.response);
    };

    next(responseObject, finalCallback);
  }
1236550
function IndexHandler(req, res, next, local = false) {
            const parsedUrl = url.parse(req.url);
            if (!parsedUrl.pathname.startsWith(self.localFilesystemUrl) &&
                parsedUrl.pathname !== '/favicon.ico'
            ) {
                /** @type {Asset} */
                const indexFile = self.assetBundle.getIndexFile();
                if (local) {
                    createStreamProtocolResponse(indexFile.getFile(), res, () => {
                    });
                } else {
                    send(req, encodeURIComponent(indexFile.getFile())).pipe(res);
                }
            } else {
                next();
            }
        }
740171
function callEntityMethod(req, res, next) {
  var payload = req.payload;
  var method = req.serversideMethod;

  if (req.hasCallback) {

    debug('Transforming callback function');
    payload[req.clientCallbackIndex] = function(err) {
      if (err) {
        return next(err);
      }

      var values = Array.prototype.slice.call(arguments).slice(1);

      debug('Callback function called. Values are:', values);

      res.entityResponse = values;

      next();
    };
  }

  debug('Calling ' + req.path + ' with arguments:', payload);

  var context = {
    req: req,
    xhr: true,
    setCookie: res.cookie.bind(res),
    clearCookie: res.clearCookie.bind(res)
  };

  var ret;

  // Calls the requested serverside method.
  // Applies the payload, and provides a context for validation purposes.
  // Caches errors in the method's scope, and sends it to the next error handler.
  try {
    ret = method.apply(context, payload);
  } catch(err) {
    return next(err);
  }

  if (util.isPromise(ret)) {
    ret.then(function(resolved) {
      res.entityResponse = [resolved];
      next();
    })
    .catch(function(err) {
      next(err);
    });
  }

  // If the request is not expecting the response from the entity,
  // send a generic 'Ok' response.
  else if (!req.hasCallback) {
    res.entityResponse = [ret];
    debug('Not asynchronous. Returning value: ', res.entityResponse);
    next();
  }
}
340202
function(request, response, next){
		var apptkn;
		if (!utils.Misc.isNullOrUndefined(request.get(X_BOLT_APP_TOKEN))) {
			apptkn = request.get(X_BOLT_APP_TOKEN);
		}
		else {
			var error = new Error(errors['110']);
			response.end(utils.Misc.createResponse(null, error, 110));
			return;
		}

		var name = __getAppFromAppToken(apptkn, request);
		if (utils.Misc.isNullOrUndefined(name)) {
			var error = new Error(errors['113']);
			response.end(utils.Misc.createResponse(null, error, 113));
			return;
		}
		var appnm = utils.String.trim(name.toLowerCase());
		request.appName = appnm;

		next();
	}
269684
function (req, res, next) {
      if (req.query.return) {
        req.session.oauth2return = req.query.return;
      }
      next();
    }
305792
function(req, res, next) {
    return function(modelOrCollection) {
      this.prepareResponse(modelOrCollection, req, res, next);
    }.bind(this);
  }
1317600
function getNextResponse(){
    if (_waitingForInput !== null){
        throw new Error('concurreny error - receive listener already in-queue');
    }

    return new Promise(function(resolve){
        // data received ?
        if (_inputbuffer.length > 0){
            resolve(_inputbuffer.shift());
        }else{
            // add as waiting instance (no concurrent!)
            _waitingForInput = resolve;
        }
    });
}
1268007
function (err, data) {
      debug(' => service response:', err, data);
      if (err) return next(err.cause || err);

      res.data = data;

      if (!data) {
        debug(`No content returned for '${req.url}'`);
        res.status(statusCodes.noContent);
      } else if (method === 'post') {
        res.status(statusCodes.created);
      }

      return next();
    }
1002147
function (next) {

            var reqOpts = {
                method: 'GET',
                url: helpers.makeAliasUri(options)
            }

            if(options.auth) {
                reqOpts.auth = {
                    user: options.auth.user,
                    pass: options.auth.password,
                    sendImmediately: false
                };
            }

            helpers.backOffRequest(reqOpts, function (err, res, body) {
                if (err) {
                    return next(err)
                }

                var existingIndices = Object.keys(body)

                // console.log('\nexistingIndices', body)

                var aliasName = helpers.makeIndexName(options)

                // get all aliases pertaining to this collection & are not the index we just created
                // we will remove all of them
                indicesToRemove = existingIndices.filter(function (indexName) {
                    return (indexName.indexOf(aliasName) === 0 && indexName !== versionedIndexName)
                })

                // console.log('\nindicesToRemove', indicesToRemove)

                // generate elasticsearch request body to atomically remove old indices and add the new one
                var requestBody = {
                    actions: [
                        {
                            add: {
                                alias: aliasName,
                                index: versionedIndexName
                            }
                        }
                    ]
                }

                indicesToRemove.forEach(function (indexToRemove) {
                    var removeObj = {
                        remove: {
                            alias: aliasName,
                            index: indexToRemove
                        }
                    }

                    requestBody.actions.unshift(removeObj)
                })

                var reqOpts = {
                    method: 'POST',
                    url: helpers.makeAliasUri(options),
                    body: JSON.stringify(requestBody)
                }

                if(options.auth) {
                    reqOpts.auth = {
                        user: options.auth.user,
                        pass: options.auth.password,
                        sendImmediately: false
                    };
                }

                helpers.backOffRequest(reqOpts, function (err, res, body) {
                    if (err) {
                        return next(err)
                    }

                    if (!helpers.elasticsearchBodyOk(body)) {
                        var error = new Error('Alias deletion error. Elasticsearch reply:'+util.inspect(body, true, 10, true))
                        error.elasticsearchReply = body
                        error.elasticsearchRequestBody = requestBody
                        return next(error)
                    }

                    return next()
                })
            })
        }
1006513
function sendResponse (req, res, next, dataStore) {
  return function (err, resources) {
    if (!err) {
      util.debug("%s successfully updated", res.swagger.location);

      if (resources.length > 0) {
        // Determine the max "modifiedOn" date of the resources
        res.swagger.lastModified = _.max(resources, "modifiedOn").modifiedOn;
      }
      else {
        // There is no data, so use the current date/time as the "last-modified" header
        res.swagger.lastModified = new Date();
      }

      // Extract the "data" of each Resource
      resources = _.map(resources, "data");
    }

    // Set the response body (unless it's already been set by other middleware)
    if (err || res.body) {
      next(err);
    }
    else if (!res.swagger.isCollection) {
      // Response body is a single value, so only return the first item that was edited
      res.body = _.first(resources);
      next();
    }
    else {
      // Response body is the entire collection (new, edited, and old)
      dataStore.getCollection(req.path, (err, collection) => {
        res.body = _.map(collection, "data");
        next(err);
      });
    }
  };
}
1123737
function parseResource (err, responseSpec, next) {
      var resource = responseSpec ? responseSpec.body : undefined;
      this.invokeNext(err, resource, next);
    }