Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion src/util/path.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,28 @@
*/
var path = exports;

var urlRe = /^[a-zA-Z][a-zA-Z0-9+.-]+:\/\//;

function normalizeUrl(path) {
if (typeof URL === "undefined" || !urlRe.test(path))
return null;
try {
return new URL(path).href;
} catch (e) {
return null;
}
}

function resolveUrl(originPath, includePath) {
if (typeof URL === "undefined" || !urlRe.test(originPath) || urlRe.test(includePath))
return null;
try {
return new URL(includePath, originPath).href;
} catch (e) {
return null;
}
}

var isAbsolute =
/**
* Tests if the specified path is absolute.
Expand All @@ -24,6 +46,9 @@ var normalize =
* @returns {string} Normalized path
*/
path.normalize = function normalize(path) {
var normalizedUrl = normalizeUrl(path);
if (normalizedUrl)
return normalizedUrl;
var firstTwoCharacters = path.substring(0,2);
var uncPrefix = "";
if (firstTwoCharacters === "\\\\") {
Expand Down Expand Up @@ -62,8 +87,11 @@ path.normalize = function normalize(path) {
* @returns {string} Path to the include file
*/
path.resolve = function resolve(originPath, includePath, alreadyNormalized) {
var resolvedUrl = resolveUrl(originPath, includePath);
if (resolvedUrl)
return resolvedUrl;
if (!alreadyNormalized)
includePath = normalize(includePath);
includePath = normalize(includePath); // path or absolute url
if (isAbsolute(includePath))
return includePath;
if (!alreadyNormalized)
Expand Down
4 changes: 4 additions & 0 deletions tests/util_path.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,5 +72,9 @@ tape.test("path", function(test) {
}
});

test.equal(path.normalize("http://example.com/protos/../file.proto"), "http://example.com/file.proto", "should normalize http urls");
test.equal(path.resolve("https://example.com/protos/origin.proto", "file.proto"), "https://example.com/protos/file.proto", "should resolve relative paths against urls");
test.equal(path.resolve("https://example.com/protos/origin.proto", "/file.proto"), "https://example.com/file.proto", "should resolve root-relative paths against urls");

test.end();
});