From d5c64791ef496ca5459ae7f2176a31ea53b127e5 Mon Sep 17 00:00:00 2001 From: Luigi Pinca Date: Fri, 18 Feb 2022 22:26:18 +0100 Subject: [PATCH] [fix] Handle the case where the port is specified but empty --- index.js | 13 ++++++++++--- test/test.js | 22 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index d808b13..c5a2a11 100644 --- a/index.js +++ b/index.js @@ -39,7 +39,7 @@ var rules = [ ['/', 'pathname'], // Extract from the back. ['@', 'auth', 1], // Extract from the front. [NaN, 'host', undefined, 1, 1], // Set left over value. - [/:(\d+)$/, 'port', undefined, 1], // RegExp the back. + [/:(\d*)$/, 'port', undefined, 1], // RegExp the back. [NaN, 'hostname', undefined, 1, 1] // Set left over. ]; @@ -524,6 +524,7 @@ function toString(stringify) { var query , url = this + , host = url.host , protocol = url.protocol; if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':'; @@ -542,7 +543,7 @@ function toString(stringify) { } else if ( url.protocol !== 'file:' && isSpecial(url.protocol) && - !url.host && + !host && url.pathname !== '/' ) { // @@ -552,7 +553,13 @@ function toString(stringify) { result += '@'; } - result += url.host + url.pathname; + // + // Trailing colon is removed from `url.host` when it is parsed. If it still + // ends with a colon, then add back the trailing colon that was removed. This + // prevents an invalid URL from being transformed into a valid one. + // + if (host[host.length - 1] === ':') host += ':'; + result += host + url.pathname; query = 'object' === typeof url.query ? stringify(url.query) : url.query; if (query) result += '?' !== query.charAt(0) ? '?'+ query : query; diff --git a/test/test.js b/test/test.js index 98880b3..ab2c6c3 100644 --- a/test/test.js +++ b/test/test.js @@ -442,6 +442,28 @@ describe('url-parse', function () { assume(parsed.href).equals('sip:alice@atlanta.com'); }); + it('handles the case where the port is specified but empty', function () { + var parsed = parse('http://example.com:'); + + assume(parsed.protocol).equals('http:'); + assume(parsed.port).equals(''); + assume(parsed.host).equals('example.com'); + assume(parsed.hostname).equals('example.com'); + assume(parsed.pathname).equals('/'); + assume(parsed.origin).equals('http://example.com'); + assume(parsed.href).equals('http://example.com/'); + + parsed = parse('http://example.com::'); + + assume(parsed.protocol).equals('http:'); + assume(parsed.port).equals(''); + assume(parsed.host).equals('example.com:'); + assume(parsed.hostname).equals('example.com:'); + assume(parsed.pathname).equals('/'); + assume(parsed.origin).equals('http://example.com:'); + assume(parsed.href).equals('http://example.com::/'); + }); + describe('origin', function () { it('generates an origin property', function () { var url = 'http://google.com:80/pathname'