chore(v2): normalize url properly (#1105)

* refactor(v2): normalize url properly

* nits
This commit is contained in:
Endilie Yacop Sucipto 2018-11-12 00:25:13 +08:00 committed by GitHub
parent 34dcc0c22e
commit b84754dde8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 128 additions and 11 deletions

View file

@ -77,6 +77,67 @@ function parse(fileString) {
return {metadata, content};
}
function normalizeUrl(rawUrls) {
const urls = rawUrls;
const resultArray = [];
// If the first part is a plain protocol, we combine it with the next part.
if (urls[0].match(/^[^/:]+:\/*$/) && urls.length > 1) {
const first = urls.shift();
urls[0] = first + urls[0];
}
// There must be two or three slashes in the file protocol, two slashes in anything else.
if (urls[0].match(/^file:\/\/\//)) {
urls[0] = urls[0].replace(/^([^/:]+):\/*/, '$1:///');
} else {
urls[0] = urls[0].replace(/^([^/:]+):\/*/, '$1://');
}
// eslint-disable-next-line
for (let i = 0; i < urls.length; i++) {
let component = urls[i];
if (typeof component !== 'string') {
throw new TypeError(`Url must be a string. Received ${component}`);
}
if (component === '') {
// eslint-disable-next-line
continue;
}
if (i > 0) {
// Removing the starting slashes for each component but the first.
component = component.replace(/^[/]+/, '');
}
if (i < urls.length - 1) {
// Removing the ending slashes for each component but the last.
component = component.replace(/[/]+$/, '');
} else {
// For the last component we will combine multiple slashes to a single one.
component = component.replace(/[/]+$/, '/');
}
resultArray.push(component);
}
let str = resultArray.join('/');
// Each input component is now separated by a single slash except the possible first plain protocol part.
// remove trailing slash before parameters or hash
str = str.replace(/\/(\?|&|#[^!])/g, '$1');
// replace ? in parameters with &
const parts = str.split('?');
str = parts.shift() + (parts.length > 0 ? '?' : '') + parts.join('&');
// dedupe forward slashes
str = str.replace(/^\/+/, '/');
return str;
}
module.exports = {
encodePath,
generate,
@ -84,5 +145,6 @@ module.exports = {
fileToComponentName,
getSubFolder,
idx,
normalizeUrl,
parse,
};