### servePublicFile Middleware Handles requests to robots.txt and favicon.ico (and caches them)
515605
function servePublicFile(file, type, maxAge) {
    const publicFileMiddleware = createPublicFileMiddleware(file, type, maxAge);

    return function servePublicFile(req, res, next) {
        if (req.path === '/' + file) {
            return publicFileMiddleware(req, res, next);
        } else {
            return next();
        }
    };
}
1273820
public function index()
    {
        $oUri      = Factory::service('Uri');
        $string    = $oUri->segment(2) ?: '';
        $width     = $oUri->segment(3) ?: null;
        $height    = $oUri->segment(4) ?: null;
        $cacheFile = 'BARCODE-' . $string. '-' . $width . 'x' . $height . '.png';

        // 

        /**
         * Check the request headers; avoid hitting the disk at all if possible. If
         * the Etag matches then send a Not-Modified header and terminate execution.
         */

        if ($this->serveNotModified($cacheFile)) {

            return;
        }

        // 

        /**
         * The browser does not have a local cache (or it's out of date) check the cache
         * to see if this image has been processed already; serve it up if it has.
         */

        if (file_exists($this->cacheDir . $cacheFile)) {

            $this->serveFromCache($cacheFile);

        } else {

            //  Generate and save to cache
            $oGenerator = Factory::service('Generator', 'nails/module-barcode');
            $result = $oGenerator->save($string, $this->cacheDir . $cacheFile, $width, $height);

            if ($result) {

                $this->serveFromCache($cacheFile);

            } else {

                header('Cache-Control: no-cache, must-revalidate', true);
                header('Expires: Mon, 26 Jul 1997 05:00:00 GMT', true);
                header('Content-Type: application/json', true);
                header($this->input->server('SERVER_PROTOCOL') . ' 400 Bad Request', true, 400);

                // 

                $out = array(
                    'status'  => 400,
                    'message' => 'Failed to generate barcode.',
                    'error'   => $oGenerator->lastError()
                );

                echo json_encode($out);

                // 

                /**
                 * Kill script, th, th, that's all folks.
                 * Stop the output class from hijacking our headers and
                 * setting an incorrect Content-Type
                 **/

                exit(0);
            }
        }
    }
115175
function serve(server, req, callback) {
		source.getTile(req.z, req.x, req.y, function(err, buffer) {
			if (err) return callback(err);
			var headers = {'Content-Type': 'application/x-protobuf'};
			if (options.compression === 'gzip') {
				headers['Content-Encoding'] = 'gzip';
			}
			callback(null, buffer, headers);
		});
	}
1108586
function createMiddleware(options) {
  /**
   * Express middleware handling raw content 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;
    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);
    }

    // project-helix/#187: serve modified content only if the requested ref is currently checked out
    isCheckedOut(repPath, refName)
      .then(serveUncommitted => resolveBlob(repPath, refName, fpath, serveUncommitted))
      .then((oid) => {
        const mimeType = mime.getType(fpath) || 'text/plain';
        res.writeHead(200, {
          'Content-Type': mimeType,
          ETag: oid,
          // TODO: review cache-control header
          'Cache-Control': 'max-age=0, private, must-revalidate',
        });
        createBlobReadStream(repPath, oid)
          .then(stream => stream.pipe(res));
      })
      .catch((err) => {
        // TODO: use generic errors
        if (err.code === 'TreeOrBlobNotFoundError' || err.code === 'ResolveRefError') {
          options.logger.debug(`[rawHandler] resource not found: ${err.message}`);
          res.status(404).send('not found.');
        } else {
          options.logger.debug(`[rawHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
          next(err);
        }
      });
  };
}
1357319
function serveSassFiles(magnet, outputDir) {
  if (!isServingSassFiles) {
    magnet.getServer()
      .getEngine()
      .use('/css', express.static(outputDir));
  }
  isServingSassFiles = true;
}
22980
function server() {
  // TODO: Show require express error
  var express = require('express')
    , app = express();

  app.configure(function() {
    app.use(express.static(siteBuilder.outputRoot));
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  });

  // Map missing trailing slashes for posts
  app.get('*', function(req, res) {
    var postPath = siteBuilder.outputRoot + req.url + '/';
    // TODO: Security
    if (req.url.match(/[^/]$/) && existsSync(postPath)) {
      res.redirect(req.url + '/');
    } else {
      res.send('404');
    }
  });

  app.listen(siteBuilder.config.port);
  log.info('Listening on port', siteBuilder.config.port);
}
717077
function addFavicons() {
  var stream = new Transform({objectMode: true, highWaterMark: 2});

  var hosts = {};
  var downloads = [];
  stream._transform = function (page, _, callback) {
    stream.push(page);
    var host = url.parse(page.url).host;
    if (!hosts[host]) {
      downloads.push(hosts[host] = download(url.resolve(page.url, '/favicon.ico')).then(function (result) {
        if (result.statusCode === 200 &&
            !(result.headers['content-type'] &&
              result.headers['content-type'].indexOf('html') !== -1)) {
          stream.push(result);
        }
      }, function () {
        //ignore errors downloading favicons
      }));
    }
    callback(null);
  };
  stream._flush = function (callback) {
    Promise.all(downloads).done(function () {
      callback();
    }, function (err) {
      stream.emit('error', err);
      callback();
    });
  };
  
  return stream;
}
543657
def _commandline(repositories,
                 port=8000, host="127.0.0.1", debug=False,
                 cache=None, cache_path="./cache", redis=None):
    

    if cache == "redis":
        nautilus_cache = RedisCache(redis)
        cache_type = "redis"
    elif cache == "filesystem":
        nautilus_cache = FileSystemCache(cache_path)
        cache_type = "simple"
    else:
        nautilus_cache = NullCache()
        cache_type = "simple"

    app = Flask("Nautilus")
    if debug:
        app.logger.setLevel(logging.INFO)

    resolver = NautilusCtsResolver(resource=repositories)
    nautilus = FlaskNautilus(
        app=app,
        resolver=resolver
        #parser_cache=WerkzeugCacheWrapper(nautilus_cache),
        #logger=None
    )
    nautilus.resolver.parse()
    app.run(debug=debug, port=port, host=host)
1000454
func FaviconHandler(h http.Handler, path string, maxAge time.Duration) http.HandlerFunc {
	var buf []byte
	var hash string

	return func(w http.ResponseWriter, r *http.Request) {
		var err error
		if r.URL.Path == "/favicon.ico" {
			if buf == nil {
				// Read from file and cache
				ghost.LogFn("ghost.favicon : serving from %s", path)
				buf, err = ioutil.ReadFile(path)
				if err != nil {
					ghost.LogFn("ghost.favicon : error reading file : %s", err)
					http.NotFound(w, r)
					return
				}
				hash = hashContent(buf)
			}
			writeHeaders(w.Header(), buf, maxAge, hash)
			writeBody(w, r, buf)
		} else {
			h.ServeHTTP(w, r)
		}
	}
}
353433
function HttpServer(options) {
  options = options || {};

  if (options.root) {
    this.root = options.root;
  }
  else {
    try {
      fs.lstatSync('./public');
      this.root = './public';
    }
    catch (err) {
      this.root = './';
    }
  }

  this.headers = options.headers || {};

  this.cache = (
    options.cache === undefined ? 3600 :
    // -1 is a special case to turn off caching.
    // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#Preventing_caching
    options.cache === -1 ? 'no-cache, no-store, must-revalidate' :
    options.cache // in seconds.
  );
  this.showDir = options.showDir !== 'false';
  this.autoIndex = options.autoIndex !== 'false';
  this.showDotfiles = options.showDotfiles;
  this.gzip = options.gzip === true;
  this.brotli = options.brotli === true;
  this.contentType = options.contentType || 'application/octet-stream';

  if (options.ext) {
    this.ext = options.ext === true
      ? 'html'
      : options.ext;
  }

  var before = options.before ? options.before.slice() : [];

  before.push(function (req, res) {
    if (options.logFn) {
      options.logFn(req, res);
    }

    res.emit('next');
  });

  if (options.username || options.password) {
    before.push(function (req, res) {
      var credentials = auth(req);

      // We perform these outside the if to avoid short-circuiting and giving
      // an attacker knowledge of whether the username is correct via a timing
      // attack.
      if (credentials) {
        var usernameEqual = secureCompare(options.username, credentials.name);
        var passwordEqual = secureCompare(options.password, credentials.pass);
        if (usernameEqual && passwordEqual) {
          return res.emit('next');
        }
      }

      res.statusCode = 401;
      res.setHeader('WWW-Authenticate', 'Basic realm=""');
      res.end('Access denied');
    });
  }

  if (options.cors) {
    this.headers['Access-Control-Allow-Origin'] = '*';
    this.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Range';
    if (options.corsHeaders) {
      options.corsHeaders.split(/\s*,\s*/)
          .forEach(function (h) { this.headers['Access-Control-Allow-Headers'] += ', ' + h; }, this);
    }
    before.push(corser.create(options.corsHeaders ? {
      requestHeaders: this.headers['Access-Control-Allow-Headers'].split(/\s*,\s*/)
    } : null));
  }

  if (options.robots) {
    before.push(function (req, res) {
      if (req.url === '/robots.txt') {
        res.setHeader('Content-Type', 'text/plain');
        var robots = options.robots === true
          ? 'User-agent: *\nDisallow: /'
          : options.robots.replace(/\\n/, '\n');

        return res.end(robots);
      }

      res.emit('next');
    });
  }

  before.push(ecstatic({
    root: this.root,
    cache: this.cache,
    showDir: this.showDir,
    showDotfiles: this.showDotfiles,
    autoIndex: this.autoIndex,
    defaultExt: this.ext,
    gzip: this.gzip,
    brotli: this.brotli,
    contentType: this.contentType,
    handleError: typeof options.proxy !== 'string'
  }));

  if (typeof options.proxy === 'string') {
    var proxy = httpProxy.createProxyServer({});
    before.push(function (req, res) {
      proxy.web(req, res, {
        target: options.proxy,
        changeOrigin: true
      }, function (err, req, res, target) {
        if (options.logFn) {
          options.logFn(req, res, {
            message: err.message,
            status: res.statusCode });
        }
        res.emit('next');
      });
    });
  }

  var serverOptions = {
    before: before,
    headers: this.headers,
    onError: function (err, req, res) {
      if (options.logFn) {
        options.logFn(req, res, err);
      }

      res.end();
    }
  };

  if (options.https) {
    serverOptions.https = options.https;
  }

  this.server = union.createServer(serverOptions);
}
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);
}
1315725
function serve(done) {
  gulp.watch(['src/**/*.css'], () => {
    reset();
    gulp.series('build-css', 'generate-preview', outputDevServerInfo);
  });

  gulp.watch(['previewer-src/**', 'patterns.yaml'], () => {
    reset();
    gulp.series('generate-preview-force', outputDevServerInfo)
  });

  browserSync.emitter.on('init', outputDevServerInfo);

  browserSync.init({
    logLevel: 'silent',
    ui: false,
    port: 4321,
    notify: false,
    server: {
      baseDir: __dirname + '/build',
      middleware: [historyApiFallback()],
    },
    startPath: '/',
    open: false
  });
}
750608
function request(
	host,
	method,
	path,
	params,
	query,
	headers,
	options,
	file,
	cb,
	debug
) {
	if (!options) options = {};

	// Remove leading/trailing slash from the path/host so that we can join
	// the two together no matter which way the user chose to provide them.
	if (path[0] === FSLASH) {
		path = path.slice(1);
	}
	if (host[host.length - 1] === FSLASH) {
		host = host.slice(0, host.length - 1);
	}

	var url = host + FSLASH + path;

	var req = superagent[method](url);

	var bar;
	var prev_loaded = 0;
	if (!options.withoutCredentials) req.withCredentials();

	if (!file) {
		// Clean up extra parameters that may have gotten in here
		// if the request came from the CLI module. This is hacky; move elsewhere
		if (params) {
			delete params._;
			delete params.$0;
			req.send(params);
		}
		if (query) {
			delete query._;
			delete query.$0;
			req.query(objectToQueryString(query));
		}
	} else {
		//for file upload params are sent as query params
		req.accept('application/json');
		req.timeout(600000);
		if (query.workspaceFileName && global.paperspace_cli && !query.json) {
			req.on('progress', function _progress(e) {
				if (!bar) bar = new ProgressBar('Uploading ' + node_path.basename(file) + ' [:bar] :rate/bps :percent :etas', {
					complete: '=',
					incomplete: ' ',
					width: 40,
					total: e.total,
				});
				var chunkSize = e.loaded - prev_loaded;
				prev_loaded = e.loaded;
				bar.tick(chunkSize);
			});
		}
		req.attach('file', file);
		delete query._;
		delete query.$0;
		if (query.json) delete query.json;
		req.query(objectToQueryString(query));
	}

	if (headers) {
		for (var headerKey in headers) {
			req.set(headerKey, headers[headerKey]);
		}
	}

	// TODO: Add nicer debug utils? Use the 'debug' module?
	if (debug) {
		console.log(method, url, params, query, headers);
	}

	return req.end(function _requestCallback(err, res) {
		// if content is gzipped, then body is empty object, and content is in 'text'
		var body;
		if (res && res.text) {
			try {
				body = JSON.parse(res.text);
			} catch (parseErr) {
				//console.error(res.text);
				//console.error(parseErr);
				//console.error('res: ' + res)
				//body = {};
				res.body = { message: res.text };
			}
		} else if (res && res.body) { // res.body is expected to be text/json
			body = res.body;
		} else body = {};

		// only return body in callback
		if (cb) return cb(err, body);

		// no callback provided; return the body
		return body;
	});
}
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
  };
}
741977
function serveStatic(options) {
    var opts = options || {};

    if (typeof opts.appendRequestPath === 'undefined') {
        opts.appendRequestPath = true;
    }

    assert.object(opts, 'options');
    assert.string(opts.directory, 'options.directory');
    assert.optionalNumber(opts.maxAge, 'options.maxAge');
    assert.optionalObject(opts.match, 'options.match');
    assert.optionalString(opts.charSet, 'options.charSet');
    assert.optionalString(opts.file, 'options.file');
    assert.bool(opts.appendRequestPath, 'options.appendRequestPath');

    var p = path.normalize(opts.directory).replace(/\\/g, '/');
    var re = new RegExp('^' + escapeRE(p) + '/?.*');

    function serveFileFromStats(file, err, stats, isGzip, req, res, next) {

        if (typeof req.connectionState === 'function' &&
            (req.connectionState() === 'close' ||
            req.connectionState() === 'aborted')) {
            next(false);
            return;
        }

        if (err) {
            next(new ResourceNotFoundError(err, '%s', req.path()));
            return;
        } else if (!stats.isFile()) {
            next(new ResourceNotFoundError('%s does not exist', req.path()));
            return;
        }

        if (res.handledGzip && isGzip) {
            res.handledGzip();
        }

        var fstream = fs.createReadStream(file + (isGzip ? '.gz' : ''));
        var maxAge = opts.maxAge === undefined ? 3600 : opts.maxAge;
        fstream.once('open', function (fd) {
            res.cache({maxAge: maxAge});
            res.set('Content-Length', stats.size);
            res.set('Content-Type', mime.lookup(file));
            res.set('Last-Modified', stats.mtime);

            if (opts.charSet) {
                var type = res.getHeader('Content-Type') +
                    '; charset=' + opts.charSet;
                res.setHeader('Content-Type', type);
            }

            if (opts.etag) {
                res.set('ETag', opts.etag(stats, opts));
            }
            res.writeHead(200);
            fstream.pipe(res);
            fstream.once('close', function () {
                next(false);
            });
        });

        res.once('close', function () {
            fstream.close();
        });
    }

    function serveNormal(file, req, res, next) {
        fs.stat(file, function (err, stats) {
            if (!err && stats.isDirectory() && opts.default) {
                // Serve an index.html page or similar
                var filePath = path.join(file, opts.default);
                fs.stat(filePath, function (dirErr, dirStats) {
                    serveFileFromStats(filePath,
                        dirErr,
                        dirStats,
                        false,
                        req,
                        res,
                        next);
                });
            } else {
                serveFileFromStats(file,
                    err,
                    stats,
                    false,
                    req,
                    res,
                    next);
            }
        });
    }

    function serve(req, res, next) {
        var file;

        if (opts.file) {
            //serves a direct file
            file = path.join(opts.directory,
                decodeURIComponent(opts.file));
        } else {
            if (opts.appendRequestPath) {
                file = path.join(opts.directory,
                    decodeURIComponent(req.path()));
            }
            else {
                var dirBasename = path.basename(opts.directory);
                var reqpathBasename = path.basename(req.path());

                if (path.extname(req.path()) === '' &&
                    dirBasename === reqpathBasename) {

                    file = opts.directory;
                }
                else {
                    file = path.join(opts.directory,
                        decodeURIComponent(path.basename(req.path())));
                }
            }
        }

        if (req.method !== 'GET' && req.method !== 'HEAD') {
            next(new MethodNotAllowedError(req.method));
            return;
        }

        if (!re.test(file.replace(/\\/g, '/'))) {
            next(new NotAuthorizedError('%s', req.path()));
            return;
        }

        if (opts.match && !opts.match.test(file)) {
            next(new NotAuthorizedError('%s', req.path()));
            return;
        }

        if (opts.gzip && req.acceptsEncoding('gzip')) {
            fs.stat(file + '.gz', function (err, stats) {
                if (!err) {
                    res.setHeader('Content-Encoding', 'gzip');
                    serveFileFromStats(file,
                        err,
                        stats,
                        true,
                        req,
                        res,
                        next);
                } else {
                    serveNormal(file, req, res, next);
                }
            });
        } else {
            serveNormal(file, req, res, next);
        }

    }

    return (serve);
}
1069713
function AssetHandler(req, res, next, local = false) {
            const parsedUrl = url.parse(req.url);
            // Check if we have an asset for that url defined.
            /** @type {Asset} */
            const asset = self.assetBundle.assetForUrlPath(parsedUrl.pathname);

            if (!asset) return next();

            const processors = () => (
                addSourceMapHeader(asset, res),
                addETagHeader(asset, res),
                addCacheHeader(asset, res, req.url)
            );

            if (local) {
                return createStreamProtocolResponse(asset.getFile(), res, processors);
            }
            return send(
                req,
                encodeURIComponent(asset.getFile()),
                { etag: false, cacheControl: false }
            )
                .on('file', processors)
                .pipe(res);
        }
599919
function Favicon_readFile() {
        var path = di.normalizePath(this.config.path);
        logger.info('Favicon.readFile:', {
            path: path
        });
        try {
            this.file = fs.readFileSync(path, {encoding: null});
        } catch (e) {
            throw new error.HttpError(500, {}, 'Cannot load favicon', e);
        }

    }