via https://github.com/expressjs/parseurl/blob/master/index.js
184567
function (str) {
        // Try fast path regexp
        // See: https://github.com/joyent/node/pull/7878
        var simplePath = typeof str === 'string' && simplePathRegExp.exec(str);

        // Construct simple URL
        if (simplePath) {
            var pathname = simplePath[1];
            var search = simplePath[2] || null;
            var url = urlModule.Url !== undefined ? new urlModule.Url() : {};
            url.path = str;
            url.href = str;
            url.pathname = pathname;
            url.search = search;
            url.query = search && search.substr(1);

            return url;
        }

        return urlModule.parse(str);
    }
614132
function parseUri(str) {
    // Adapted from parseuri package - http://blog.stevenlevithan.com/archives/parseuri
    // tslint:disable-next-line:max-line-length
    var URL_REGEX = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
    var m = URL_REGEX.exec(str);
    var uri = {
        source: '',
        protocol: '',
        authority: '',
        userInfo: '',
        user: '',
        password: '',
        host: '',
        port: '',
        relative: '',
        path: '',
        directory: '',
        file: '',
        query: '',
        anchor: ''
    };
    var keys = Object.keys(uri);
    var i = keys.length;
    while (i--) {
        uri[keys[i]] = m[i] || '';
    }
    return uri;
}
96271
function notfoundUnit (server) {
  var regexes = [];
  var callbacks = [];

  function notfound (paths, literalCall) {
    regexes.push(RegExp(paths));
    callbacks.push(literalCall);
  }

  server.notfound = notfound;

  return function notfoundLayer (req, res) {
    res.statusCode = 404;
    var matched = null;
    var cbindex = -1;
    for (var i = 0; i < regexes.length; i++) {
      matched = req.path.match (regexes[i]);
      if (matched !== null) { cbindex = i; break; }
    }
    if (cbindex >= 0) {
      catchpath(req, res, matched, callbacks[cbindex], server.templateReader);
    } else {
      res.end('Not Found\n');
    }
  };
}
1131523
function parse (string) {
  if (!string) {
    throw new TypeError('argument string is required')
  }

  // support req/res-like objects as argument
  var header = typeof string === 'object'
    ? getcontenttype(string)
    : string

  if (typeof header !== 'string') {
    throw new TypeError('argument string is required to be a string')
  }

  var index = header.indexOf(';')
  var type = index !== -1
    ? header.substr(0, index).trim()
    : header.trim()

  if (!TYPE_REGEXP.test(type)) {
    throw new TypeError('invalid media type')
  }

  var obj = new ContentType(type.toLowerCase())

  // parse parameters
  if (index !== -1) {
    var key
    var match
    var value

    PARAM_REGEXP.lastIndex = index

    while ((match = PARAM_REGEXP.exec(header))) {
      if (match.index !== index) {
        throw new TypeError('invalid parameter format')
      }

      index += match[0].length
      key = match[1].toLowerCase()
      value = match[2]

      if (value[0] === '"') {
        // remove quotes and escapes
        value = value
          .substr(1, value.length - 2)
          .replace(QESC_REGEXP, '$1')
      }

      obj.parameters[key] = value
    }

    if (index !== header.length) {
      throw new TypeError('invalid parameter format')
    }
  }

  return obj
}
1288192
function createMiddleware(options, archiveFormat) {
  /**
   * Express middleware handling GitHub API archive link requests
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://developer.github.com/v3/repos/contents/#get-archive-link
   */
  return (req, res) => {
    // GET /repos/:owner/:repo/:archive_format/:ref
    const { owner } = req.params;
    const repoName = req.params.repo;
    const refName = req.params.ref || 'master';

    const host = req.mappedSubDomain ? `localhost:${options.listen[req.protocol].port}` : req.headers.host;
    const location = `${req.protocol}://${host}/codeload/${owner}/${repoName}/${archiveFormat}/${refName}`;

    res.writeHead(302, {
      Location: location,
    });
    res.end();
  };
}
787703
function(moduleRegex) {
        var self = this;

        moduleRegex = moduleRegex || /^(.+)\.js$/;

        return function(req, res, next) {
            var match = req.url.match(moduleRegex);
            if(!match) return next();

            var module= match[1];

            self.bundle(module, function(err, src) {
                res.setHeader('Content-Type', 'text/javascript; charset=utf-8');
                res.setHeader('Cache-Control', 'no-cache');

                // expose event to allow for custom headers
                self.emit('pre-response', err, res, module, src);

                res.send(src);
            });
        };
    }
257294
function initExpress(app) {
  var env = app.get('env');
  var publicDir = path.join(config.root, config.publicDir);

  app.set('ip', config.ip);
  app.set('port', config.port);

  app.set('views', config.root + '/server/views');
  app.engine('html', require('ejs').renderFile);
  app.set('view engine', 'html');

  app.use(compression());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
  app.use(methodOverride());
  app.use(cookieParser());
  app.use(passport.initialize());
  app.use(favicon(path.join(publicDir, 'favicon.ico')));

  if ('production' === env) {
    app.use(express.static(publicDir));
    app.set('appPath', publicDir);
    app.use(morgan('tiny'));
  }

  if ('development' === env || 'test' === env) {
    app.use(express.static(path.join(config.root, '.tmp')));
    app.use(express.static(publicDir));
    app.set('appPath', publicDir);
    app.use(morgan('dev'));
    // Error handler - has to be last
    app.use(errorHandler());
  }
}
385780
function parseURL(s) {
  var url = null;
  try {
    url = new URL(s);
  } catch (error) {
    console.error(error);
  }
  return url;
}
6943
function parse (string) {
  if (!string || typeof string !== 'string') {
    throw new TypeError('argument string is required')
  }

  var match = DISPOSITION_TYPE_REGEXP.exec(string)

  if (!match) {
    throw new TypeError('invalid type format')
  }

  // normalize type
  var index = match[0].length
  var type = match[1].toLowerCase()

  var key
  var names = []
  var params = {}
  var value

  // calculate index to start at
  index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';'
    ? index - 1
    : index

  // match parameters
  while ((match = PARAM_REGEXP.exec(string))) {
    if (match.index !== index) {
      throw new TypeError('invalid parameter format')
    }

    index += match[0].length
    key = match[1].toLowerCase()
    value = match[2]

    if (names.indexOf(key) !== -1) {
      throw new TypeError('invalid duplicate parameter')
    }

    names.push(key)

    if (key.indexOf('*') + 1 === key.length) {
      // decode extended value
      key = key.slice(0, -1)
      value = decodefield(value)

      // overwrite existing value
      params[key] = value
      continue
    }

    if (typeof params[key] === 'string') {
      continue
    }

    if (value[0] === '"') {
      // remove quotes and escapes
      value = value
        .substr(1, value.length - 2)
        .replace(QESC_REGEXP, '$1')
    }

    params[key] = value
  }

  if (index !== -1 && index !== string.length) {
    throw new TypeError('invalid parameter format')
  }

  return new ContentDisposition(type, params)
}
240502
function uriToBlob(uri, done) {
  const xhr = new XMLHttpRequest();
  xhr.responseType = "blob";
  xhr.onload = () => {
    const blob = xhr.response;
    done(null, blob);
  };
  xhr.onerror = (err) => {
    done(err);
  };
  xhr.open("GET", uri);
  xhr.send();
}
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);
        }
      });
  };
}
1301141
function createMiddleware(options, urlType) {
  /**
   * Express middleware handling html 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 || 'master';
    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);
    }

    // set response content type
    res.header('Content-Type', 'text/html');

    resolveCommit(repPath, refName)
      .then(commitOid => git.readObject({ dir: repPath, oid: commitOid, filepath: fpath })
        .catch(() => null))
      .then((blobOrTree) => {
        if (!blobOrTree) {
          if (!fpath.length && urlType === 'tree') {
            // 'tree' view
            res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<p>tree view not implemented yet.</body></html>`);
          } else {
            res.status(404).send(`not found: ${escape(fpath)}`);
          }
          return;
        }

        const { type } = blobOrTree;
        if (!fpath.length && type === 'tree' && urlType === 'root') {
          // 'root' view
          res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<p>root view not implemented yet.</body></html>`);
        } else if (type === 'tree' && urlType === 'tree') {
          // directory view
          res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<br>path: ${escape(fpath)}<p>directory view not implemented yet.</body></html>`);
        } else if (type === 'blob' && urlType === 'blob') {
          // single file view
          res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<br>path: ${escape(fpath)}<p>file view not implemented yet.</body></html>`);
        } else {
          res.status(404).send(`not found: ${escape(fpath)}`);
        }
      })
      .catch((err) => {
        options.logger.debug(`[htmlHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
        next(err);
      });
  };
}
1278320
function(buffer, req, res, next) {
          var moduleDir = _.find(options.moduleDirs, function(dir) {
            return req.url.indexOf(options.root + dir) === 0;
          });

          // Only process JavaScript that are required modules, this means
          // bailing out early if not in the module path.
          if (!moduleDir || req.url.indexOf(options.root + "vendor") > 0) {
            return next();
          }

          // The module name is just the JavaScript file stripped of the
          // host and location.
          var moduleName = req.url.split(moduleDir)[1];
          moduleName = moduleName.slice(1);

          // I'd rather work with strings here, since buffers aren't widely
          // supported.
          buffer = String(buffer);

          // If ES6 modules are enabled in the configuration, convert by
          // default.
          if (options.es6) {
            buffer = new Compiler(buffer, moduleName.slice(-2, 0)).toAMD();
          }

          // This method allows hooking into the RequireJS toolchain.
          requirejs.tools.useLib(function(require) {
            // Convert to AMD if using CommonJS, by default the conversion
            // will ignore modules that already contain a define.
            require(["commonJs"], function(commonJs) {
              var wrapped = commonJs.convert(moduleName, buffer);
              var noDefine = wrapped.indexOf("define(") === -1;
              var noConfig = wrapped.indexOf("require.config") === -1;

              if (noDefine && noConfig) {
                wrapped = [
                  "define(function(require, exports, module) {",
                    wrapped,
                  "});"
                ].join("\n");
              }

              res.header("Content-type", "application/javascript");
              res.end(wrapped);
            });
          });
        }
998614
function parseUrl(url) {
        if (Core.isBlank(url)) {
            return null;
        }
        var matches = url.match(httpRegex);
        if (matches === null) {
            return null;
        }
        //log.debug("matches: ", matches);
        var scheme = matches[1];
        var host = matches[3];
        var port = matches[4];
        var parts = null;
        if (!Core.isBlank(port)) {
            parts = url.split(port);
        }
        else {
            parts = url.split(host);
        }
        // make sure we use port as a number
        var portNum = Core.parseIntValue(port);
        var path = parts[1];
        if (path && _.startsWith(path, '/')) {
            path = path.slice(1, path.length);
        }
        //log.debug("parts: ", parts);
        return {
            scheme: scheme,
            host: host,
            port: portNum,
            path: path
        };
    }
933904
function _resolveUrl(base, url) {
    var /** @type {?} */ parts = _split(encodeURI(url));
    var /** @type {?} */ baseParts = _split(base);
    if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__facade_lang__["c" /* isPresent */])(parts[_ComponentIndex.Scheme])) {
        return _joinAndCanonicalizePath(parts);
    }
    else {
        parts[_ComponentIndex.Scheme] = baseParts[_ComponentIndex.Scheme];
    }
    for (var /** @type {?} */ i = _ComponentIndex.Scheme; i <= _ComponentIndex.Port; i++) {
        if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__facade_lang__["d" /* isBlank */])(parts[i])) {
            parts[i] = baseParts[i];
        }
    }
    if (parts[_ComponentIndex.Path][0] == '/') {
        return _joinAndCanonicalizePath(parts);
    }
    var /** @type {?} */ path = baseParts[_ComponentIndex.Path];
    if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__facade_lang__["d" /* isBlank */])(path))
        path = '/';
    var /** @type {?} */ index = path.lastIndexOf('/');
    path = path.substring(0, index + 1) + parts[_ComponentIndex.Path];
    parts[_ComponentIndex.Path] = path;
    return _joinAndCanonicalizePath(parts);
}
1129638
function parseUri(str) {
    var parser = re.uri_parser;
    var parserKeys = ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "isColonUri", "relative", "path", "directory", "file", "query", "anchor"];
    var m = parser.exec(str || '');
    var parts = {};

    parserKeys.forEach(function(key, i) {
      parts[key] = m[i] || '';
    });

    return parts;
  }
615526
function parseArguments() {
        var args = [];

        expect('(');

        if (!match(')')) {
            while (index < length) {
                args.push(parseExpression());
                if (match(')')) {
                    break;
                }
                expect(',');
            }
        }

        expect(')');

        return args;
    }