compose a new middleware function from multiple middlewares

@param {Function|Array|Object}
@return {Function} middleware function
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
}
743366
function Middleware(name) {
    if (!(this instanceof Middleware)) return new Middleware(name);
    this.name = name || '';

    Object.defineProperty(this, '_', {
        enumerable: false,
        configurable: false,
        value: {
            length: 0,
            ordered: null,
            weights: new Map()
        }
    });

    /**
     * Returns the length of the middleware.
     * @type {number}
     */
    Object.defineProperty(this, 'length', {
        get: () => this._.length
    });
}
1293356
function onInstance(Meanio,meanioinstance,defer){
  Meanio.prototype.serve = genericServe.bind(meanioinstance,Meanio);
  var middleware = {
    before: [],
    after: []
  };
  //so tangled up, much spaghetti...
  Meanio.prototype.chainware = {

    add: function(event, weight, func) {
      middleware[event].splice(weight, 0, {
        weight: weight,
        func: func
      });
      middleware[event].join();
      middleware[event].sort(function(a, b) {
        if (a.weight < b.weight) {
          a.next = b.func;
        } else {
          b.next = a.func;
        }
        return (a.weight - b.weight);
      });
    },

    before: function(req, res, next) {
      if (!middleware.before.length) return next();
      this.chain('before', 0, req, res, next);
    },

    after: function(req, res, next) {
      if (!middleware.after.length) return next();
      this.chain('after', 0, req, res, next);
    },

    chain: function(operator, index, req, res, next) {
      var args = [req, res,
        function() {
          if (middleware[operator][index + 1]) {
            this.chain('before', index + 1, req, res, next);
          } else {
            next();
          }
        }
      ];

      middleware[operator][index].func.apply(this, args);
    }
  };

  defer.resolve();
}
74883
function compose(patterns, options, matcher) {
  let matchers;

  return memoize('compose', String(patterns), options, function() {
    return function(file) {
      // delay composition until it's invoked the first time,
      // after that it won't be called again
      if (!matchers) {
        matchers = [];
        for (var i = 0; i < patterns.length; i++) {
          matchers.push(matcher(patterns[i], options));
        }
      }

      let len = matchers.length;
      while (len--) {
        if (matchers[len](file) === true) {
          return true;
        }
      }
      return false;
    };
  });
}
1113819
def middleware(func):
    
    @wraps(func)
    def parse(*args, **kwargs):
        """ get middleware from route, execute middleware in order """
        middleware = copy.deepcopy(kwargs['middleware'])
        kwargs.pop('middleware')
        if request.method == "OPTIONS":
            # return 200 json response for CORS
            return JsonResponse(200)
        if middleware is None:
            return func(*args, **kwargs)
        for mware in middleware:
            ware = mware()
            if ware.status is False:
                return ware.response
            return func(*args, **kwargs)
    return parse
851126
function getMiddlewareWrapper( middleware ) {
	return function ( req, res, next ) {
		try {
			middleware( req, res, next );
		}
		catch ( e ) {
			getResponder( req, res )( 500 );
		}
	};
}
836979
function promesso (handler) {
  const handleFn = isFunction(handler) ? [handler] : handler;
  const middlewares = [];
  let validations = 0;

  handleFn.forEach(h => {
    if (!isFunction(h)) throw new Error('Handler is expected to be a function or an Array of functions.');

    if (isObject(handleFn['@validation'])) {
      middlewares.push(validation(h['@validation']), validationMiddleware);
      if (++validations > 1) throw new Error('Every handler can have only one validator per chain.');
    }

    middlewares.push(h);
  });

  return middlewares.map(rawOrPromise);
}
215207
def compose(*funcs):
    """"""
    return lambda x: reduce(lambda v, f: f(v), reversed(funcs), x)
574217
public function compose() {
    $functions = self::_wrapArgs(func_get_args(), 1);
    
    return self::_wrap(function() use ($functions) {
      $args = func_get_args();
      foreach($functions as $function) {
        $args[0] = call_user_func_array($function, $args);
      }
      return $args[0];
    });
  }
433698
function middleware(filename, options, cb) {
  var self = this;
  var cache = self.cache;
  var handlebars = self.handlebars;

  self.async = async();

  // grab extension from filename
  // if we need a layout, we will look for one matching out extension
  var extension = path.extname(filename);

  // If passing the locals as data, create the handlebars options object now
  var handlebarsOpts = (self.__localsAsData) ? { data: options._locals } : undefined;

  // render the original file
  // cb(err, str)
  function render_file(locals, cb) {
    // cached?
    var template = cache[filename];
    if (template) {
      return cb(null, template(locals, handlebarsOpts));
    }

    fs.readFile(filename, 'utf8', function(err, str){
      if (err) {
        return cb(err);
      }

      var template = handlebars.compile(str);
      if (locals.cache) {
        cache[filename] = template;
      }

      try {
        var res = template(locals, handlebarsOpts);
        self.async.done(function(values) {
          Object.keys(values).forEach(function(id) {
            res = res.replace(id, values[id]);
          });

          cb(null, res);
        });
      } catch (err) {
        err.message = filename + ': ' + err.message;
        cb(err);
      }
    });
  }

  // render with a layout
  function render_with_layout(template, locals, cb) {
    render_file(locals, function(err, str) {
      if (err) {
        return cb(err);
      }

      locals.body = str;

      var res = template(locals, handlebarsOpts);
      self.async.done(function(values) {
        Object.keys(values).forEach(function(id) {
          res = res.replace(id, values[id]);
        });

        cb(null, res);
      });
    });
  }

  var layout = options.layout;

  // user did not specify a layout in the locals
  // check global layout state
  if (layout === undefined && options.settings && options.settings['view options']) {
    layout = options.settings['view options'].layout;
  }

  // user explicitly request no layout
  // either by specifying false for layout: false in locals
  // or by settings the false view options
  if (layout !== undefined && !layout) {
    return render_file(options, cb);
  }

  var view_dirs = options.settings.views;

  var layout_filename = [].concat(view_dirs).map(function (view_dir) {
    var view_path = path.join(view_dir, layout || 'layout');

    if (!path.extname(view_path)) {
      view_path += extension;
    }

    return view_path;
  });

  var layout_template = layout_filename.reduce(function (cached, filename) {
    if (cached) {
      return cached;
    }

    var cached_file = cache[filename];

    if (cached_file) {
      return cache[filename];
    }

    return undefined;
  }, undefined);

  if (layout_template) {
    return render_with_layout(layout_template, options, cb);
  }

  // TODO check if layout path has .hbs extension

  function cacheAndCompile(filename, str) {
    var layout_template = handlebars.compile(str);
    if (options.cache) {
      cache[filename] = layout_template;
    }

    render_with_layout(layout_template, options, cb);
  }

  function tryReadFileAndCache(templates) {
    var template = templates.shift();

    fs.readFile(template, 'utf8', function(err, str) {
      if (err) {
        if (layout && templates.length === 0) {
          // Only return error if user explicitly asked for layout.
          return cb(err);
        }

        if (templates.length > 0) {
          return tryReadFileAndCache(templates);
        }

        return render_file(options, cb);
      }

      cacheAndCompile(template, str);
    });
  }

  tryReadFileAndCache(layout_filename);
}
945773
function use(events, middleware)
{
  // if no middleware supplied assume it's single argument call
  if (!middleware)
  {
    middleware = events;
    events     = null;
  }

  // make it uniform
  events = normalizeEvents(events);

  // store middleware per event
  events.forEach(function(e)
  {
    // bind middleware to the current context
    (this._stack[e] = this._stack[e] || []).push(middleware.bind(this));

    // make mark in history
    this.logger.debug({message: 'Added middleware to the stack', event: e, middleware: middleware});
  }.bind(this));
}
376875
function Middleware(...middleware) {
    return (ctr) => {
        if (middleware != undefined) {
            let c = exports.globalKCState.getOrInsertController(ctr);
            c.middleware = middleware.concat(c.middleware);
        }
    };
}
1367494
function createMiddleware(options = {}) {
  const middlewareOptions = Object.assign({}, defaults, options);

  return ({ getState }) => next => action => {
    // Do not process actions without an [RSAA] property
    if (!isRSAA(action)) {
      return next(action);
    }

    return (async () => {
      // Try to dispatch an error request FSA for invalid RSAAs
      const validationErrors = validateRSAA(action);
      if (validationErrors.length) {
        const callAPI = action[RSAA];
        if (callAPI.types && Array.isArray(callAPI.types)) {
          let requestType = callAPI.types[0];
          if (requestType && requestType.type) {
            requestType = requestType.type;
          }
          next({
            type: requestType,
            payload: new InvalidRSAA(validationErrors),
            error: true
          });
        }
        return;
      }

      // Parse the validated RSAA action
      const callAPI = action[RSAA];
      var {
        endpoint,
        body,
        headers,
        options = {},
        fetch: doFetch = middlewareOptions.fetch,
        ok = middlewareOptions.ok
      } = callAPI;
      const { method, credentials, bailout, types } = callAPI;
      const [requestType, successType, failureType] = normalizeTypeDescriptors(
        types
      );

      // Should we bail out?
      try {
        if (
          (typeof bailout === 'boolean' && bailout) ||
          (typeof bailout === 'function' && bailout(getState()))
        ) {
          return;
        }
      } catch (e) {
        return next(
          await actionWith(
            {
              ...failureType,
              payload: new RequestError('[RSAA].bailout function failed'),
              error: true
            },
            [action, getState()]
          )
        );
      }

      // Process [RSAA].endpoint function
      if (typeof endpoint === 'function') {
        try {
          endpoint = endpoint(getState());
        } catch (e) {
          return next(
            await actionWith(
              {
                ...failureType,
                payload: new RequestError('[RSAA].endpoint function failed'),
                error: true
              },
              [action, getState()]
            )
          );
        }
      }

      // Process [RSAA].body function
      if (typeof body === 'function') {
        try {
          body = body(getState());
        } catch (e) {
          return next(
            await actionWith(
              {
                ...failureType,
                payload: new RequestError('[RSAA].body function failed'),
                error: true
              },
              [action, getState()]
            )
          );
        }
      }

      // Process [RSAA].headers function
      if (typeof headers === 'function') {
        try {
          headers = headers(getState());
        } catch (e) {
          return next(
            await actionWith(
              {
                ...failureType,
                payload: new RequestError('[RSAA].headers function failed'),
                error: true
              },
              [action, getState()]
            )
          );
        }
      }

      // Process [RSAA].options function
      if (typeof options === 'function') {
        try {
          options = options(getState());
        } catch (e) {
          return next(
            await actionWith(
              {
                ...failureType,
                payload: new RequestError('[RSAA].options function failed'),
                error: true
              },
              [action, getState()]
            )
          );
        }
      }

      // We can now dispatch the request FSA
      if (
        typeof requestType.payload === 'function' ||
        typeof requestType.meta === 'function'
      ) {
        next(await actionWith(requestType, [action, getState()]));
      } else {
        next(requestType);
      }

      let res;
      try {
        // Make the API call
        res = await doFetch(endpoint, {
          ...options,
          method,
          body: body || undefined,
          credentials,
          headers: headers || {}
        });
      } catch (e) {
        // The request was malformed, or there was a network error
        return next(
          await actionWith(
            {
              ...failureType,
              payload: new RequestError(e.message),
              error: true
            },
            [action, getState()]
          )
        );
      }

      let isOk;
      try {
        isOk = ok(res);
      } catch (e) {
        return next(
          await actionWith(
            {
              ...failureType,
              payload: new InternalError('[RSAA].ok function failed'),
              error: true
            },
            [action, getState(), res]
          )
        );
      }

      // Process the server response
      if (isOk) {
        return next(await actionWith(successType, [action, getState(), res]));
      } else {
        return next(
          await actionWith(
            {
              ...failureType,
              error: true
            },
            [action, getState(), res]
          )
        );
      }
    })();
  };
}
101286
function sanitize (fn) {
  return function (/* path, ...middleware */) {
    var middleware = []
    var startindex = 0
    var endindex = arguments.length
    var path
    var options

    if (typeof arguments[0] === 'string') {
      path = arguments[0]
      startindex = 1
    }

    if (typeof arguments[arguments.length - 1] === 'object') {
      endindex = arguments.length - 1
      options = arguments[endindex]
    }

    // Concat all the middleware functions.
    for (var i = startindex; i < endindex; i++) {
      middleware.push(arguments[i])
    }

    middleware = flatten(middleware)

    if (middleware.length === 0) {
      throw new TypeError('Expected a function but got no arguments')
    }

    if (middleware.length === 1) {
      middleware = middleware[0]
    } else {
      middleware = compose(middleware)
    }

    fn.call(this, path, middleware, extend({}, this._options, options))

    return this
  }
}
594634
function patch(Ware) {
  var AttachWare = unherit(Ware)
  var useFn = Ware.prototype.use

  AttachWare.prototype.use = use

  return wrap

  function wrap(fn) {
    return new AttachWare(fn)
  }

  /* Attach configurable middleware. */
  function use(attach) {
    var self = this
    var params = slice.call(arguments, 1)
    var index
    var length
    var fn

    /* Multiple attachers. */
    if ('length' in attach && typeof attach !== 'function') {
      index = -1
      length = attach.length

      /* So, `attach[0]` is a function, meaning its
       * either a list of `attachers` or its a `list`. */
      if (typeof attach[0] === 'function') {
        if (
          attach[1] !== null &&
          attach[1] !== undefined &&
          typeof attach[1] !== 'function'
        ) {
          self.use.apply(self, attach)
        } else {
          while (++index < length) {
            self.use.apply(self, [attach[index]].concat(params))
          }
        }
      } else {
        while (++index < length) {
          self.use(attach[index])
        }
      }

      return self
    }

    /* Single attacher. */
    fn = attach.apply(null, [self.context || self].concat(params))

    /* Store the attacher to not break `new Ware(otherWare)`
     * functionality. */
    if (!self.attachers) {
      self.attachers = []
    }

    self.attachers.push(attach)

    /* Pass `fn` to the original `Ware#use()`. */
    if (fn) {
      useFn.call(self, fn)
    }

    return self
  }
}
929798
function createMiddleware(options) {
  const conf = (options && options.subdomainMapping) || {};
  const enabled = conf.enable && conf.baseDomains && conf.baseDomains.length;
  return (req, res, next) => {
    if (!enabled) {
      return next();
    }

    let { host } = req.headers;
    const origUrl = host + req.url;

    // trim :<port>
    [host] = host.split(':');

    // match & remove base domain
    const i = _.findIndex(conf.baseDomains, dom => _.endsWith(host, dom));
    if (i === -1) {
      return next();
    }
    host = _.trimEnd(host.slice(0, -conf.baseDomains[i].length), '.');
    if (!host.length) {
      // no subdomains
      return next();
    }

    req.url = `/${host.split('.').join('/')}${req.url}`;
    req.mappedSubDomain = true;

    logger.debug(`${origUrl} => ${req.url}`);

    // pass on to next middleware
    return next();
  };
}
1093003
function compose(...fns) {
  return function(x) {
    return fns.reduceRight((result, val) => val(result), x);
  };
}