UNPKG

vhost-ts

Version:

vhost fork made with typescript

108 lines (81 loc) 2.24 kB
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } const ASTERISK_REGEXP = /\*/g; const ASTERISK_REPLACE = "([^.]+)"; const END_ANCHORED_REGEXP = /(?:^|[^\\])(?:\\\\)*\$$/; const ESCAPE_REGEXP = /([.+?^=!:${}()|[\]/\\])/g; const ESCAPE_REPLACE = "\\$1"; var index = ((hostname, handle) => { if (!hostname) { throw new TypeError("argument hostname is required"); } if (!handle) { throw new TypeError("argument handle is required"); } if (typeof handle !== "function") { throw new TypeError("argument handle must be a function"); } const regexp = hostregexp(hostname); const vhost = (req, res, next) => { const vhostdata = vhostof(req, regexp); if (!vhostdata) { return next(); } req.vhost = vhostdata; handle(req, res, next); }; return vhost; }); function hostnameof(req) { const host = req.hostname || req.host || req.headers.host; if (!host) { return; } const offset = host[0] === "[" ? host.indexOf("]") + 1 : 0; const index = host.indexOf(":", offset); return index !== -1 ? host.substring(0, index) : host; } function hostregexp(val) { let source = val instanceof RegExp ? val.source : String(val).replace(ESCAPE_REGEXP, ESCAPE_REPLACE).replace(ASTERISK_REGEXP, ASTERISK_REPLACE); if (source[0] !== "^") { source = "^" + source; } if (!END_ANCHORED_REGEXP.test(source)) { source += "$"; } return new RegExp(source, "i"); } function vhostof(req, regexp) { const host = req.headers.host; const hostname = hostnameof(req); if (!host || !hostname) { return; } const match = regexp.exec(hostname); if (!match) { return; } const matches = {}; for (let i = 1; i < match.length; i++) { matches[i - 1] = match[i]; } return _extends({ host, hostname, length: match.length - 1 }, matches); } module.exports = index; //# sourceMappingURL=index.js.map