docs: function chainMiddleware(params) {
    var args = [params.wreq, params.wres];
    var cbs = [];
    var cause; // Backpropagated error.
    forward(0);
  
    function forward(pos) {
      var isDone = false;
      if (pos < params.fns.length) {
        params.fns[pos].apply(params.ctx, args.concat(function (err, cb) {
          if (isDone) {
            params.onError(toError('duplicate forward middleware call', err));
            return;
          }
          isDone = true;
          if (
            err || (
              params.wres && ( // Non one-way messages.
                params.wres.error !== undefined ||
                params.wres.response !== undefined
              )
            )
          ) {
            // Stop the forward phase, bypass the handler, and start the backward
            // phase. Note that we ignore any callback argument in this case.
            cause = err;
            backward();
            return;
          }
          if (cb) {
            cbs.push(cb);
          }
          forward(++pos);
        }));
      } else {
        // Done with the middleware forward functions, call the handler.
        params.onTransition.apply(params.ctx, args.concat(function (err) {
          if (isDone) {
            params.onError(toError('duplicate handler call', err));
            return;
          }
          isDone = true;
          cause = err;
          process.nextTick(backward);
        }));
      }
    }
  
    function backward() {
      var cb = cbs.pop();
      if (cb) {
        var isDone = false;
        cb.call(params.ctx, cause, function (err) {
          if (isDone) {
            params.onError(toError('duplicate backward middleware call', err));
            return;
          }
          // Substitute the error.
          cause = err;
          isDone = true;
          backward();
        });
      } else {
        // Done with all middleware calls.
        params.onCompletion.call(params.ctx, cause);
      }
    }
  }