UNPKG

@thi.ng/server

Version:

Minimal HTTP server with declarative routing, static file serving and freely extensible via pre/post interceptors

50 lines (49 loc) 1.59 kB
import { illegalArgs } from "@thi.ng/errors"; import { HEX } from "@thi.ng/strings"; const isMatchingHost = (test, expected) => { if (/^\[[0-9a-f:]{1,39}\]$/.test(test)) { try { return normalizeIPv6Address(test.substring(1, test.length - 1)) === expected; } catch (_) { return false; } } return test === expected; }; const parseIPv6Address = (addr) => { if (addr == "::") return [0, 0, 0, 0, 0, 0, 0, 0]; if (addr == "::1") return [0, 0, 0, 0, 0, 0, 0, 1]; const n = addr.length - 1; if (n > 38) invalidIPv6(addr); const parts = []; let curr = 0; let zeroes = -1; for (let i = 0; i <= n; i++) { const ch = addr[i]; if (i === n && ch == ":") illegalArgs(addr); if (i === n || ch === ":") { if (parts.length >= (zeroes >= 0 ? 6 : 8)) invalidIPv6(addr); const end = i === n ? n + 1 : i > curr ? i : invalidIPv6(addr); if (end - curr > 4) invalidIPv6(addr); parts.push(parseInt(addr.substring(curr, end), 16)); if (addr[i + 1] === ":") { if (zeroes >= 0) invalidIPv6(addr); zeroes = parts.length; i++; } curr = i + 1; } else if (!HEX[ch]) invalidIPv6(addr); } if (zeroes >= 0) { parts.splice(zeroes, 0, ...new Array(8 - parts.length).fill(0)); } if (parts.length !== 8) invalidIPv6(addr); return parts; }; const normalizeIPv6Address = (addr) => parseIPv6Address(addr).map((x) => x.toString(16)).join(":"); const invalidIPv6 = (addr) => illegalArgs("invalid IPv6 address: " + addr); export { isMatchingHost, normalizeIPv6Address, parseIPv6Address };