Export the transfer protocol handler (express middleware) through a parameterizable function

@param {object} options configuration hash
@returns {function(*, *, *)} handler function
767232
function createMiddleware(options) {
  /**
   * Express middleware handling Git (Smart) Transfer Protocol requests
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://git-scm.com/book/en/v2/Git-Internals-Transfer-Protocols
   * @see https://github.com/git/git/blob/master/Documentation/technical/http-protocol.txt
   */
  return (req, res, next) => {
    const { owner, repo } = req.params;

    const repPath = resolveRepositoryPath(options, owner, repo);
    const reqStream = req.headers['content-encoding'] === 'gzip' ? req.pipe(zlib.createGunzip()) : req;
    reqStream.pipe(backend(req.originalUrl, (err, service) => {
      if (err) {
        logger.error(err);
        next(err);
        return;
      }

      res.setHeader('content-type', service.type);
      logger.info(service.action, repo, service.fields);

      const ps = spawn(service.cmd, service.args.concat(repPath));
      ps.stdout.pipe(service.createStream()).pipe(ps.stdin);
    })).pipe(res);
  };
}
571265
function createOutTransfer (dappId, transactionId, recipientId, amount, secret, secondSecret, timeOffset) {
	var now = new Date().getTime();
	var time = timeOffset ? now - timeOffset : now;
	var keys = crypto.getKeys(secret);

	var transaction = {
		type: 7,
		amount: amount,
		fee: constants.fees.send,
		recipientId: recipientId,
		senderPublicKey: keys.publicKey,
		timestamp: slots.getTime(time),
		asset: {
			outTransfer: {
				dappId: dappId,
				transactionId: transactionId,
			},
		},
	};

	crypto.sign(transaction, keys);

	if (secondSecret) {
		var secondKeys = crypto.getKeys(secondSecret);
		crypto.secondSign(transaction, secondKeys);
	}

	return transaction;
}
967063
function create (options) {
  const {
    xForwardedProto,
    redirectPort,
    redirectHost,
    statusCode,
    redirectUnknown,
    redirect,
    exclude
  } = Object.assign({}, defaults, options)
  const _port = redirectPort === 443 ? '' : (': ' + redirectPort)

  return function redirectSSL (req, res, next) {
    if (redirect && !isExcluded(req.url, exclude)) {
      const _isHttps = isHTTPS(req, xForwardedProto)
      const shouldRedirect = _isHttps === false || (redirectUnknown && _isHttps === null)
      if (shouldRedirect) {
        const ـredirectURL = 'https://' + (redirectHost || req.headers.host) + _port + req.url
        res.writeHead(statusCode, { Location: ـredirectURL })
        return res.end()
      }
    }

    return next()
  }
}
746981
async function transfer (nameId, account, options = {}) {
  const opt = R.merge(this.Ae.defaults, options)

  const nameTransferTx = await this.nameTransferTx(R.merge(opt, {
    nameId,
    accountId: await this.address(),
    recipientId: account
  }))

  return this.send(nameTransferTx, opt)
}
71072
function getServerHandler(basePath, adapter) {
    basePath = basePath || '/';
    if (basePath.length > 0 && basePath[basePath.length - 1] === '/') {
        basePath = basePath.substring(0, basePath.length - 2);
    }
    return function(req, res, next) {
        return teleport.Promise.resolve().then(function() {
            var params = req.params = req.params || {};
            var path = params.path || params['0'] || '';
            if (path[0] !== '/') {
                path = '/' + path;
            }
            path = basePath + path;
            var query = req.query || {};
            var headers = req.headers || {};
            var data = req.data || req.body || {};
            var overrideKey = 'X-HTTP-Method-Override';
            var method = //
            headers[overrideKey] || query[overrideKey] || //
            req.method || 'get';
            delete query[overrideKey];
            method = method.toLowerCase();
            var options = {
                path : path,
                method : method,
                params : params,
                query : query,
                headers : headers,
                data : data
            };
            return adapter.handle(options);
        }).then(function(result) {
            result = result || {};
            var headers = result.headers || {};
            res.set(headers);
            res.send(result.data || {});
        }, function(err) {
            res.status(500).send({
                error : err.stack,
                params : req.params
            });
        });
    }
}
390662
function(method, args, options) {
            var that = this, methodHandler;

            options = options || {};

            var handler = this.getHandler(method);
            if (!handler) return Q.reject(new Error("No handler found for method: "+method));

            // Is offline
            if (!Offline.isConnected()) {
                methodHandler = handler.fallback;
            }
            methodHandler = methodHandler || handler.execute || this.defaultHandler.execute;

            // No default
            if (!methodHandler) {
                return Q.reject(new Error("No handler found for this method in this backend"));
            }

            return Q(methodHandler(args, options, method)).then(function(results) {
                if (handler.after) {
                    return Q.all([
                        Q(handler.after(args, results, options, method)),
                        Q((that.defaultHandler.after || function() {})(args, results, options, method))
                    ]).then(function() {
                        return Q(results);
                    }, function() {
                        return Q(results);
                    });
                }
                return results;
            });
        }
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);
}
1342741
function createWebSocketTransport(ws) {
  // A transport object.
  var self = new events.EventEmitter();
  // Transport URI contains information like protocol header as query.
  self.uri = ws.upgradeReq.url;
  // Simply delegates WebSocket's events to transport and transport's behaviors to WebSocket.
  ws.onmessage = function(event) {
    // `event.data` is a message. It is string if text frame is sent and Buffer if binary frame
    // is sent.
    if (typeof event.data === "string") {
      self.emit("text", event.data);
    } else {
      self.emit("binary", event.data);
    }
  };
  ws.onerror = function(error) {
    self.emit("error", error);
  };
  // A flag to check the transport is opened.
  var opened = true;
  ws.onclose = function() {
    opened = false;
    self.emit("close");
  };
  self.send = function(data) {
    // Allows to send data only it is opened. If not, fires an error.
    if (opened) {
      // If `data` is string, a text frame is sent, and if it's Buffer, a binary frame is sent.
      ws.send(data);
    } else {
      self.emit("error", new Error("notopened"));
    }
    return this;
  };
  self.close = function() {
    ws.close();
    return this;
  };
  return self;
}
996097
function MSPassportStrategy(options) {
  Strategy.call(this);
  this.name = "mspassport";
  
  var default_options = {
        protocol : "querystring",
        protocolHandler : function() { self.fail("protocolHandler must be implemented if protocol === 'custom'") }        
  };
    
  this.options = _defaults(default_options, options);
}
198315
function(options){
  var _this = this;

  this.handlers = {};

  if(!options){
    options = {};
  }

  if(!options.redis){
    options.redis = {};
  }

  this.options = {
    id: options.id || shortId.generate(),
    autoConfig: options.autoConfig ||  false,
    dataExpiry: options.dataExpiry || 30,
    redis: {
      port: options.redis.port || 6379,
      host: options.redis.host || '127.0.0.1',
      redis: options.redis.options || {}
    }
  };

  //Create redis clients
  this.redisSub = redis.createClient(this.options.redis.port, this.options.redis.host, this.options.redis.options);
  this.redis = redis.createClient(this.options.redis.port, this.options.redis.host, this.options.redis.options);
  this.redisInstant = redis.createClient(this.options.redis.port, this.options.redis.host, this.options.redis.options);

  //Attempt auto config
  if(this.options.autoConfig){
    var config = '';
    this.redis.config("GET", "notify-keyspace-events", function(err, data){
      if(data){
        config = data[1];
      }
      if(config.indexOf('E') == -1){
        config += 'E'
      }
      if(config.indexOf('x') == -1){
        config += 'x'
      }
      _this.redis.config("SET", "notify-keyspace-events", config)
    });
  }

  //Listen to key expiry notifications and handle events
  var expiryListener = new RedisEvent(this.redisSub, 'expired', /redular:(.+):(.+):(.+)/);
  expiryListener.defineHandler(function(key){
    var clientId = key[1];
    var eventName = key[2];
    var eventId = key[3];

    _this.redis.get('redular-data:' + clientId + ':' + eventName + ':' + eventId, function(err, data){
      if(data){
        data = JSON.parse(data);
      }
      if(clientId == _this.options.id || clientId == 'global'){
        _this.handleEvent(eventName, data);
      }
    });
  });

  //Listen to instant events and handle them
  this.redisInstant.subscribe('redular:instant');
  this.redisInstant.on('message', function(channel, message){
    try{
      var parsedMessage = JSON.parse(message);
    } catch (e){
      throw e;
    }
    if(parsedMessage.client == _this.options.id || parsedMessage.client == 'global') {
      _this.handleEvent(parsedMessage.event, parsedMessage.data);
    }
  });

}
94268
function createMiddleware(options) {
  /**
   * Express middleware handling Git API Blob requests
   *
   * Only a small subset will be implemented
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://developer.github.com/v3/git/blobs/#get-a-blob
   */
  return (req, res, next) => {
    // GET /repos/:owner/:repo/git/blobs/:file_sha
    const { owner } = req.params;
    const repoName = req.params.repo;
    const sha = req.params.file_sha;
    const host = req.mappedSubDomain ? `localhost:${options.listen[req.protocol].port}` : req.headers.host;

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

    if (sha.match(/[0-9a-f]/g).length !== 40) {
      // invalid sha format
      res.status(422).json({
        message: 'The sha parameter must be exactly 40 characters and contain only [0-9a-f].',
        documentation_url: 'https://developer.github.com/v3/git/blobs/#get-a-blob',
      });
      return;
    }
    getObject(repPath, sha)
      .then(({ object: content }) => {
        res.json({
          sha,
          size: content.length,
          url: `${req.protocol}://${host}${req.path}`,
          content: `${content.toString('base64')}\n`,
          encoding: 'base64',
        });
      })
      .catch((err) => {
        // TODO: use generic errors
        if (err.code === 'ReadObjectFail') {
          options.logger.debug(`[blobHandler] resource not found: ${err.message}`);
          res.status(404).json({
            message: 'Not Found',
            documentation_url: 'https://developer.github.com/v3/git/blobs/#get-a-blob',
          });
        } else {
          options.logger.debug(`[blobHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
          next(err);
        }
      });
  };
}
418426
function attacher(destination, options) {
  var settings

  if (destination && !destination.process) {
    settings = destination
    destination = null
  }

  settings = settings || options || {}

  if (settings.document === undefined || settings.document === null) {
    settings.document = true
  }

  return destination ? bridge(destination, settings) : mutate(settings)
}
910030
function createServer(options) {
    var opt = new Options(options || {});

    var app = express();
    // Import configuration
    for (var o in opt) {
	app.set(o, opt[o]);
    }
    // Default middleware
    app.use(express.favicon())
	.use(express.query())
	.use(express.bodyParser())
	.use(express.cookieParser())
	.use(express.session( {secret: opt.secret } ))
	.use(opt.static_mount, express.static(opt.static_dir))
    // Template engines
    app.engine('mustache', cons.hogan)
	.engine('mu', cons.hogan)
	.set('view engine', 'mustache')
	.set('views', opt.template_dir);
    // Custom middleware
    app.use(exports.logger(opt.separator))
	.use(set_cookie)
	.use(exports.multi_render(app))
	.use(exports.fun_router(app));
    
    // Specify default page
    if (opt.default_route)
	app.get('/', function(req, res) { res.redirect(opt.default_route); });

    // Create http server
    app.http_server = http.createServer(app);
    if (app.get('socket_io')) {
	app.io = require('socket.io').listen(app.http_server);
    }

    app.listen = function() {
	app.http_server.listen.apply(app.http_server, arguments);
    };

    app.start = startServer;
    
    return app;
}
1094293
function init(options) {
    if (options === void 0) { options = {}; }
    if ('debug' in options) {
        diag.debug.enabled = options.debug;
        Q.longStackSupport = options.debug;
    }
    if ('serverUrl' in options) {
        var myURL = url.parse(options.serverUrl);
        if (!myURL.protocol && !myURL.host) {
            return Q.reject(new Error(options.serverUrl + " is not an accepted Url, please add a Host and a Protocol."));
        }
    }
    _.assignWith(exports.initOptions, cloneServerInitOptions(options), function (left, right) { return _.isUndefined(right) ? left : right; });
    if ('push' in options) {
        exports.initOptions.push = _.cloneDeep(options.push);
    }
    return device.ready;
}
1300241
function BartererServer(options) {
  options = options || {};
  var specifiedHttpPort = options.httpPort || HTTP_PORT;
  var httpPort = process.env.PORT || specifiedHttpPort;

  var app = express();

  var instance = new Barterer(options);
  options.app = app;
  instance.configureRoutes(options);

  app.listen(httpPort, function() {
    console.log('barterer is listening on port', httpPort);
  });

  return instance;
}
789346
function handler(req, next) {
  var conf = this.configure();
  var pkg = this.package();
  var copyright = conf.copyright || (pkg ? pkg.copyright : null);
  var opts = [this._version];
  var msg = this._name + ' %s';

  // NOTE: allows deferring to this handler from a custom handler
  if(arguments.length > 1 && typeof(next) !== 'function') {
    opts = opts.concat([].slice.call(arguments, 1));
  }
  opts.unshift(msg);
  // respect vanilla help setting
  if(conf.help.vanilla) {
    opts = [util.format.apply(util, opts)];
  }
  console.log.apply(console, opts);
  if(copyright) {
    console.log();
    copyright = '' + copyright;
    copyright = wrap(copyright, 0, conf.help.maximum);
    console.log(copyright);
  }
  if(conf.exit && req !== true) process.exit();
  return false;
}
856617
function () {
    return function (req, res, next) {
      var headers = req.header('Access-Control-Request-Headers');
      var origin = req.header('Origin');

      // TODO should this check if the request is via the API?
      if (req.method === 'OPTIONS' || (req.method === 'GET' && req.headers.origin)) {
        res.header({
          'Access-Control-Allow-Origin':  origin,
          'Access-Control-Allow-Headers': headers,
          'Access-Control-Allow-Credentials': 'true'
        });
        req.cors = true;
      }

      if (req.method === 'OPTIONS') {
        res.send(204);
      } else {
        next();
      }
    };
  }