------------------------------------------ MIDDLEWARE ------------------------------------------
334865
function middleware (node, config) {
    let token = config.credentials.token;
    let now = Date.now();

    return wechat (token, function(req, res, next) {

        let data = botmgr.buildMessageFlow({ message : req.weixin }, {
            userId:     'message.FromUserName',
            convId:     'message.FromUserName',
            inputType:  'message.MsgType',
            source:     'wechat'
        });

        switch (req.weixin.MsgType) {
            case "text":
                data.payload = req.weixin.Content;
                break;
            case "image":
                data.payload = req.weixin.EventKey || "";
                data.message.attachments.push({
                    contentUrl: req.weixin.PicUrl, 
                    contentType: "image",
                    contentId: req.weixin.MediaId
                });
                break;
            case "voice":
                data.payload = req.weixin.EventKey || "";
                data.message.attachments.push({
                    contentType: "audio",
                    contentFormat: req.weixin.Format,
                    contentId: req.weixin.MediaId
                });
                break;
            case "video":
                data.payload = req.weixin.EventKey || "";
                data.message.attachments.push({
                    contentType: "video",
                    contentThumbId: req.weixin.ThumbMediaId,
                    contentId: req.weixin.MediaId
                });
                break;
            case "location":
                data.payload = req.weixin.EventKey || "";
                data.message.attachments.push({
                    contentType: "location",
                    contentLoc: {
                        label: req.weixin.Label,
                        latitude: req.weixin.Location_X,
                        longitude: req.weixin.Location_Y,
                        scale: req.weixin.Scale
                    }
                });
                break;
            case "link":
                data.payload = req.weixin.EventKey || "";
                data.message.attachments.push({
                    contentType: "link",
                    contentLink: {
                        title: req.weixin.Title,
                        description: req.weixin.Description,
                        url: req.weixin.Url
                    }
                });
                break;
            case "event":
                if (req.weixin.Event === "location_select") { res.status(200).end(); return; }
                else if (req.weixin.Event.match(/pic/)) WAIT_MESSAGES = req.weixin.SendPicsInfo.Count;
            
                data.payload = req.weixin.EventKey || "";
                let obj = { contentType: "event",
                            contentEvent: (req.weixin.ScanCodeInfo) ? req.weixin.ScanCodeInfo : {}};
                if (req.weixin.SendPicsInfo) obj.contentEvent = req.weixin.SendPicsInfo;
                data.message.attachments.push(obj);
                break;
            default:
                data.payload = "";
                break;
        }

        res.status(200).end();

        if (WAIT_MESSAGES > 0) {
            WAIT_QUEUE.push(data);
            WAIT_MESSAGES--;
            return;
        }

        if (WAIT_QUEUE.length > 0) {
            WAIT_QUEUE.push(data);

            if (WAIT_QUEUE[0].message.Event.match(/pic/)) {
                data = WAIT_QUEUE[0];
                data.message.attachments = [];
                for (let i = 1; i < WAIT_QUEUE.length; i++) {
                    data.message.attachments.push({
                        contentUrl: WAIT_QUEUE[i].message.PicUrl, 
                        contentType: "image",
                        contentId: WAIT_QUEUE[i].message.MediaId
                    });
                }
            } 
            else {    
                data = WAIT_QUEUE[1];
                data.payload = WAIT_QUEUE[0].payload;
            }
            WAIT_QUEUE = [];
        }

        // Handle Prompt
        let address = botmgr.getUserAddress(data)
        if (!address || address.carrier !== 'wechat') return false;

        let convId  = botmgr.getConvId(data)
        if (botmgr.hasDelayedCallback(convId, data.message)) return;

        api.getUser({openid: convId, lang:'en'}, 
            (err, result) => { 
                if (err) { node.error(err); return; }
                data.user.profile = result;
                return node.send(data);
            });  
    });
}
965296
protected function registerMiddleware($middleware)
    {
        /** @var Kernel $kernel */
        $kernel = $this->getContainer()->get(KernelInterface::class);
        $kernel->prependMiddleware($middleware);
    }
1029008
function toHaveMiddleware(middleware) {
    
    expect(this.actual).toExist('Route is undefined');
    toBeAnExpressRoute(this.actual.route);
    expect(this.actual.route.stack.length).toBeGreaterThan(1, 'No middleware found');
    if(expressGuards.isMiddleware(middleware)) {
        expect(this.actual.route.stack.find(l => l.handle.toString() === middleware.toString())).toExist(`middleware is not defined`);
    } else {
        const name = middleware || '<anonymous>';
        expect(this.actual.route.stack.find(l => l.name === name)).toExist(`${name} is not defined`);
    }
}
30172
function compose(middlewares, path) {
    if (!Array.isArray(middlewares)) {
        throw new Error(`middlewares ${JSON.stringify(middlewares)} should be an Array of functions.`);
    }
    if (middlewares.length) {
        for (const fn of middlewares) {
            if (typeof fn !== 'function') {
                throw new Error(`middleware ${path} - ${JSON.stringify(fn)} should be a function, ignored.`);
            }
        }
    }
    return (req, res, next) => {
        (function iterate(i, max) {
            if (i === max) {
                return next();
            }
            middlewares[i](req, res, iterate.bind(this, i + 1, max));
        })(0, middlewares.length);
    }
}
376875
function Middleware(...middleware) {
    return (ctr) => {
        if (middleware != undefined) {
            let c = exports.globalKCState.getOrInsertController(ctr);
            c.middleware = middleware.concat(c.middleware);
        }
    };
}
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;
}
268421
public function middleware( $middleware ) {
		$middleware = array_merge(
			(array) $this->getAttribute( 'middleware', [] ),
			(array) $middleware
		);

		return $this->attribute( 'middleware', $middleware );
	}
438556
public function initialize()
    {
        if ($this->hasMiddlewares()) {
            foreach ($this->middlewares as $middleware) {
                $middleware->initialize();
            }

            Strata::app()->log(sprintf("Loaded <info>%d</info> middlewares", count($this->middlewares)), "<info>Middleware</info>");
        }
    }
1255972
public static function register($middleware)
    {
        $config = Container::get('config')->get('middleware');

        if (isset($config[$middleware])) {
            if (in_array($middleware, array_values(self::$middlewares))) {
                throw new ConfigException('middleware has already registered');
            }

            array_push(self::$middlewares, $middleware);
            $middlewares = $config[$middleware];

            if (!is_array($middlewares)) {
                throw new ConfigException('middleware config must be an array');
            }

            foreach ($middlewares as $className) {
                if (!class_exists($className)) {
                    throw new NotFoundException('middleware class ' . $className . ' is not found');
                }

                $class = new $className;
                if (!method_exists($class, 'handle')) {
                    throw new NotFoundException('middleware class should implement a handle() method');
                }

                $class->handle(Container::get('request'), Container::get('response'));
            }
        }
    }
995750
private static function middleware()
    {
        $files = ['Filters', 'Middleware'];
        $folder = static::$root.'Http/Middleware'.'/';

        self::call($files, $folder);

        $files = ['MiddlewareNotFoundException', 'MiddlewareWallException'];
        $folder = static::$root.'Http/Middleware/Exceptions'.'/';

        self::call($files, $folder);
    }
554281
protected static function middleware()
    {
        foreach (self::fetch('http/middleware') as $file) {
            Bus::need($file);
        }

        Middleware::ini();
    }
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);
}
376128
function Router() {
  var self = this;
  this.arr = [];
  this.caseSensitive = true;
  this.strict = false;

  this.middleware = function router(msg, next) {
    self._dispatch(msg, next);
  };
}
843830
public function middleware(...$middlewares): void
    {
        foreach ($middlewares as $middleware) {
            if (!$middleware instanceof MiddlewareInterface && !\is_string($middleware)) {
                $type = \is_object($middleware) ? \get_class($middleware) : \gettype($middleware);
                
                throw new \InvalidArgumentException(\sprintf('Unsupported middleware type: %s', $type));
            }
            
            $this->middlewares[] = $middleware;
        }
    }
474129
public function append(MiddlewareInterface $middleware): MiddlewarePipe
    {
        $stack = new MiddlewarePipe();

        /** @noinspection PhpParamsInspection */
        return $stack
            ->append($this)
            ->append($middleware);
    }
979768
public function middleware( $middleware = null )
	{
		if ( is_null( $middleware ) )
			return (array) Arr::get( $this->action, 'middleware', [] );

		if ( is_string( $middleware ) )
			$middleware = [$middleware];

		$this->action['middleware'] = array_merge( (array) Arr::get( $this->action, 'middleware', [] ), $middleware );

		return $this;
	}
901151
function mountMiddleware(middleware, context) {
				if (typeof context === 'string') {
					middleware = app.use(urljoin('/', options.contextpath, context), middleware);
				}
				middlewares.push(middleware);
			}