/*
@param {function} middleware - connect style, (req, res, next)
@return {function} middleware - dietjs style ($)
Proxies the signal object
439049
function compatible (middleware) {
	return function ($) {
		var req = $.request
		var res = $.response

		var $req = new Proxy(req, {
			defineProperty (target, prop, descriptor) {
				return Object.defineProperty(target, prop, descriptor) &&
					   Object.defineProperty($, prop, descriptor)
			},
			has (target, prop) {
				return prop in target || prop in $
			},
			get (target, prop) {
				return prop in target ? target[prop] : $[prop]
			},
			set (target, prop, value, receiver) {
				$[prop] = value
				target[prop] = value
				return true
			},
			deleteProperty (target, prop) {
				return (delete $[prop]) && (delete target[prop])
			}
		})

		middleware($req, res, function (err) {
			if (err)
				throw err
			$.return()
		})
	}
}
907701
function runMiddlewareStack(stack, req, res, callback) {
  let index = 0;
  // the middleware layer handover callback
  function next(err) {
    // get next middleware callback from stack
    const handle = stack[index++];
    // if no more layers in stack, invoke done callback and exit recursion
    if (!handle) {
      callback(err);
      return;
    }
    let error = err;
    // call the middleware handler
    try {
      if (err && handle.length === 4) {
        // there is an error and it's an error-handling middleware
        handle(err, req, res, next);
        return;
      } else if (!err && handle.length < 4) {
        // no error and it's a request-handling middleware
        handle(req, res, next);
        return;
      }
    } catch (e) {
      // if new error thrown, replace the error
      error = e;
    }
    // otherwise skip layer
    next(error);
  }
  // start going through middleware stack
  next();
}
1314966
function applyFetchMiddleware() {
  for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) {
    middlewares[_key] = arguments[_key];
  }

  var middlewaresWithOnResolve = middlewares.filter(function (m) {
    return typeof m.onResolve === 'function';
  });
  if (middlewaresWithOnResolve.length > 1) {
    console.warn('[fetch-middleware] Only one single `onResolve` handler is supported, but you provided %d', middlewaresWithOnResolve.length);
  }

  return {
    beforeFetch: function beforeFetch(_ref) {
      var action = _ref.action;

      return middlewares.reduce(function (chain, middleware) {
        if (typeof middleware.beforeFetch === 'function') {
          return chain.then(function (_ref2) {
            var action = _ref2.action;
            return middleware.beforeFetch({ action: action });
          });
        }
        return chain;
      }, Promise.resolve({ action: action }));
    },
    afterFetch: function afterFetch(_ref3) {
      var action = _ref3.action;
      var result = _ref3.result;

      return middlewares.reduce(function (chain, middleware) {
        if (typeof middleware.afterFetch === 'function') {
          return chain.then(function (_ref4) {
            var action = _ref4.action;
            var result = _ref4.result;
            return middleware.afterFetch({ action: action, result: result });
          });
        }
        return chain;
      }, Promise.resolve({ action: action, result: result }));
    },
    onReject: function onReject(_ref5) {
      var action = _ref5.action;
      var error = _ref5.error;

      return middlewares.reduce(function (chain, middleware) {
        if (typeof middleware.onReject === 'function') {
          return chain.catch(function (_ref6) {
            var action = _ref6.action;
            var error = _ref6.error;
            return middleware.onReject({ action: action, error: error });
          });
        }
        return chain;
      }, Promise.reject({ action: action, error: error }));
    },


    onResolve: middlewaresWithOnResolve[0] ? middlewaresWithOnResolve[0].onResolve : undefined
  };
}
405752
function (req, res, next) {
                // Delayed resolution of the isLoggedIn middleware.
                if (server.registry.has('localUserMiddleware')) {
                    const middleware = server.registry.get('localUserMiddleware');
                    middleware.isLoggedInMiddleware()(req, res, next);
                } else {
                    next(new restifyErrors.ForbiddenError(`Server configuration error, 'localUserMiddleware' not found.`));
                }
            }
14685
function middlewareStrategy(metadata, dataAdapter, opts) {
    opts.filter = opts.filter || defaultFilter;
    const { filter } = opts;
    return async function magic(ctx, next) {
        const { name, key } = opts.filter.call(null, ctx);
        const obj = metadata[name];
        const { routeSwitch = {} } = obj;

        let middleware;
        if (routeSwitch[key] === true) {
            const { pres, posts } = getHooks(obj, key);
            const route = routes[key];
            middleware = route.call(null, name, dataAdapter, opts, pres, posts);
        }

        try {
            if (typeof middleware === 'function') {
                await middleware.call(null, ctx, next);
            } else {
                await next();
            }
        } catch (err) {
            throw err;
        }
    }
}
14178
function authorize(ctx) {
  var fn = lookup(ctx.operation, 'middleware', 'authorize');
  var prefix = describe(ctx);

  if (fn) {
    return fn(ctx);
  } else {
    debug(prefix + 'authorize middleware disabled (not defined)');
  }
}
440781
function MiddlewareContext (router) {
  events.EventEmitter.call(this);

  /**
   * Express routing options (e.g. `caseSensitive`, `strict`).
   * If set to an Express Application or Router, then its routing settings will be used.
   * @type {express#Router}
   */
  this.router = router || {};

  /**
   * The parsed Swagger API
   * @type {SwaggerObject}
   */
  this.api = null;

  /**
   * The {@link SwaggerParser} instance that was used to parse the API.
   * @type {SwaggerParser}
   */
  this.parser = null;

  /**
   * If the Swagger API contains errors, this will be set
   * @type {Error}
   */
  this.error = null;
}
1105280
function makeServeMiddleware(/* config */) {
  return function handle(req, resp, next) {
    if (/^\/.*\.css$/.test(req.url)) {
      resp.end("");
    }
    else {
      next();
    }
  };
}
345357
function compose () {
  // the function required by the server
  function middlewareF (req, res, end) {
    var index = 0

    // inject stats middleware
    if (middlewareF.options && middlewareF.options.stats) {
      middlewareF.stack = middlewareF.stack.map(function (mw) {
        var fn
        if (typeof mw === 'object') {
          var key = Object.keys(mw)[0]
          if (!mw[key].stats) {
            fn = {}
            fn[key] = middlewareF.options.stats(mw[key])
          }
        } else {
          if (!mw.stats) {
            fn = middlewareF.options.stats(mw)
          }
        }
        return fn
      })
    }

    // looping over all middleware functions defined by stack
    ;(function next (err) {
      var arity
      var middleware = middlewareF.stack[index++] // obtain the current middleware from the stack

      if (!middleware) {
        // we are at the end of the stack
        end && end(err)
        return
      } else {
        // extract middleware from object
        if (typeof (middleware) === 'object') {
          var name = Object.keys(middleware)[0]
          if (typeof (middleware[name]) === 'function') {
            middleware = middleware[name]
          } else {
            middleware = function (req, res, next) {
              next(new Error('missing middleware'))
            }
          }
        }

        try {
          arity = middleware.length // number of arguments function middleware requires
          // handle errors
          if (err) {
            // If the middleware function contains 4 arguments than this will act as an "error trap"
            if (arity === 4) {
              middleware(err, req, res, function (err) {
                nextTick(next, err)
              })
            } else {
              // otherwise check the next middleware
              next(err)
            }
          } else if (arity < 4) {
            // process non "error trap" stack
            middleware(req, res, function (err) {
              nextTick(next, err)
            })
          } else {
            // loop over "error traps" if no error `err` is set.
            next()
          }
        } catch (e) {
          next(e)
        }
      }
    })()
  }

  middlewareF.stack = []
  middlewareF.options = compose.options || {}

  ;[].slice.call(arguments).forEach(function (a) {
    middlewareF.stack = middlewareF.stack.concat(compose.decompose(a))
  })

  // extends
  ;[ 'before', 'after', 'replace', 'remove', 'push', 'unshift', 'clone' ].forEach(function (p) {
    middlewareF[p] = compose[p]
  })

  // inject stats middleware
  if (compose.options.stats) {
    middlewareF.options = {}
    middlewareF.options.stats = compose.options.stats
  }

  return middlewareF
}
212098
function middleware3() {
	return function mw3(handler) {

		return async function mw3(ctx) {
			broker.logger.info(chalk.cyan("mw3 before", ctx.action.name));
			//return broker.Promise.resolve("data from mw3");
			const res = await handler(ctx);
			broker.logger.info(chalk.cyan("mw3 after", ctx.action.name));
			if (res) {
				if (ctx.action.name == "users.get")
					delete res.gravatar;
				if (ctx.action.name == "posts.get")
					delete res.content;
			}
			return res;
		};
	};
}
554393
def token_middleware(ctx, get_response):
    
    async def middleware(request):
        params = request.setdefault('params', {})
        if params.get("token") is None:
            params['token'] = ctx.token
        return await get_response(request)
    return middleware
901151
function mountMiddleware(middleware, context) {
				if (typeof context === 'string') {
					middleware = app.use(urljoin('/', options.contextpath, context), middleware);
				}
				middlewares.push(middleware);
			}
746619
function authenticate(ctx) {
  var fn = lookup(ctx.operation, 'middleware', 'authenticate');
  var prefix = describe(ctx);

  if (fn) {
    return fn(ctx);
  } else {
    debug(prefix + 'authenticate middleware disabled (not defined)');
  }
}
507643
function proxyRequest(data, next) {

        debug('proxying %s %s', data.clientRequest.method, data.url);

        var middlewareHandledRequest = _.some(config.requestMiddleware, function(middleware) {
            middleware(data);
            return data.clientResponse.headersSent; // if true, then _.some will stop processing middleware here because we can no longer
        });

        if (!middlewareHandledRequest) {
            var uri = URL.parse(data.url);

            var options = {
                host: uri.hostname,
                port: uri.port,
                path: uri.path,
                method: data.clientRequest.method,
                headers: data.headers
            };

            //set the agent for the request.
            if(uri.protocol == 'http:' && config.httpAgent) {
              options.agent =  config.httpAgent;
            }
            if(uri.protocol == 'https:' && config.httpsAgent) {
              options.agent =  config.httpsAgent;
            }

            // what protocol to use for outgoing connections.
            var proto = (uri.protocol == 'https:') ? https : http;

            debug('sending remote request: ', options);

            data.remoteRequest = proto.request(options, function(remoteResponse) {
                data.remoteResponse = remoteResponse;
                data.remoteResponse.on('error', next);
                proxyResponse(data);
            });

            data.remoteRequest.on('error', next);

            // pass along POST data & let the remote server know when we're done sending data
            data.stream.pipe(data.remoteRequest);
        }

    }
1121448
function callResponseMiddleware(err, res1, res2) {
        i -= 1;
        if (i >= 0) {
            var next = self.middlewares[i].response;
            if (typeof next === 'function') {
                next(req, err, res1, res2, callResponseMiddleware);
            } else {
                // skip this middleware if it doesn't implement response
                callResponseMiddleware(err, res1, res2);
            }
        } else {
            callback(req, err, res1, res2);
        }
    }
1007136
function getProxyMiddleware(context, uri) {
  const pathRewrite = {};
  pathRewrite[`^${context}`] = url.parse(uri).pathname;

  return proxy({
    target: getHost(uri),
    changeOrigin: true,
    logLevel: 'warn',
    pathRewrite: pathRewrite,
  });
}
1301141
function createMiddleware(options, urlType) {
  /**
   * Express middleware handling html requests
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   */
  return async (req, res, next) => {
    const { owner } = req.params;
    const repoName = req.params.repo;
    let refName = req.params.ref || 'master';
    let fpath = req.params[0] || '';

    const repPath = resolveRepositoryPath(options, owner, repoName);

    // issue: #53: handle branch names containing '/' (e.g. 'foo/bar')
    const parsed = await determineRefPathName(repPath, `${req.params.ref}/${req.params[0]}`);
    if (parsed) {
      refName = parsed.ref;
      fpath = parsed.pathName;
    }

    // issue #247: lenient handling of redundant leading slashes in path
    while (fpath.length && fpath[0] === '/') {
      // trim leading slash
      fpath = fpath.substr(1);
    }

    // set response content type
    res.header('Content-Type', 'text/html');

    resolveCommit(repPath, refName)
      .then(commitOid => git.readObject({ dir: repPath, oid: commitOid, filepath: fpath })
        .catch(() => null))
      .then((blobOrTree) => {
        if (!blobOrTree) {
          if (!fpath.length && urlType === 'tree') {
            // 'tree' view
            res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<p>tree view not implemented yet.</body></html>`);
          } else {
            res.status(404).send(`not found: ${escape(fpath)}`);
          }
          return;
        }

        const { type } = blobOrTree;
        if (!fpath.length && type === 'tree' && urlType === 'root') {
          // 'root' view
          res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<p>root view not implemented yet.</body></html>`);
        } else if (type === 'tree' && urlType === 'tree') {
          // directory view
          res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<br>path: ${escape(fpath)}<p>directory view not implemented yet.</body></html>`);
        } else if (type === 'blob' && urlType === 'blob') {
          // single file view
          res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<br>path: ${escape(fpath)}<p>file view not implemented yet.</body></html>`);
        } else {
          res.status(404).send(`not found: ${escape(fpath)}`);
        }
      })
      .catch((err) => {
        options.logger.debug(`[htmlHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
        next(err);
      });
  };
}