diff --git a/lib/decode_url.js b/lib/decode_url.js index 74c76ea1..21583167 100644 --- a/lib/decode_url.js +++ b/lib/decode_url.js @@ -1,12 +1,16 @@ 'use strict'; -// To be refactored to WHATWG URL API -// after support for Node 8 is dropped. -// url.format(WHATWG URL object) in Node 8 doesn't support port number - -const { parse, format } = require('url'); +const { URL } = require('url'); const { toUnicode } = require('./punycode'); +const urlObj = (str) => { + try { + return new URL(str); + } catch (err) { + return str; + } +}; + const safeDecodeURI = (str) => { try { return decodeURI(str); @@ -16,24 +20,13 @@ const safeDecodeURI = (str) => { }; const decodeURL = (str) => { - const parsed = parse(str); - if (parsed.protocol) { - const obj = Object.assign({}, { - auth: parsed.auth, - protocol: parsed.protocol, - host: toUnicode(parsed.host), - pathname: safeDecodeURI(parsed.pathname) - }); - - if (parsed.hash) { - Object.assign(obj, { hash: safeDecodeURI(parsed.hash) }); - } - - if (parsed.search) { - Object.assign(obj, { search: safeDecodeURI(parsed.search) }); - } + const parsed = urlObj(str); + if (typeof parsed === 'object') { + if (parsed.origin === 'null') return str; - return format(obj); + // TODO: refactor to `url.format()` once Node 8 is dropped + const url = parsed.toString().replace(parsed.hostname, toUnicode(parsed.hostname)); + return safeDecodeURI(url); } return safeDecodeURI(str);