@har-sdk/core
Version:
The base package can be used to import specification files (i.e. HAR, OAS and Postman Collection) and detect their type.
47 lines • 1.61 kB
JavaScript
export const removeTrailingSlash = (path) => path.replace(/\/$/, '');
export const removeLeadingSlash = (path) => path.replace(/^\//, '');
const normalizePathName = (pathname) => pathname.replace(/((?!:).|^)\/{2,}/g, (_, p1) => /^(?!\/)/g.test(p1) ? `${p1}/` : '/');
const DEFAULT_PROTOCOL = 'https';
const prependProtocolIfNecessary = (url) => {
const hasRelativeProtocol = /^\/{2}/.test(url);
const isRelativeUrl = !hasRelativeProtocol && /^\.+\//.test(url);
if (!isRelativeUrl) {
url = url.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, `${DEFAULT_PROTOCOL}://`);
}
return url;
};
export const parseUrl = (value) => {
const url = new URL(value);
if (!validateUrl(url)) {
throw new TypeError(`Invalid URL: ${url}`);
}
return url;
};
export const validateUrl = (value) => {
let url;
try {
url = typeof value === 'string' ? parseUrl(value) : value;
}
catch {
// noop
}
// verify an opaque origin https://html.spec.whatwg.org/#ascii-serialisation-of-an-origin
return !!(url && url.hostname && url.origin && url.origin !== 'null');
};
export const normalizeUrl = (value) => {
const url = parseUrl(prependProtocolIfNecessary(value));
try {
url.pathname = normalizePathName(url.pathname);
}
catch {
// noop
}
url.searchParams.sort();
url.hostname = url.hostname.replace(/\.$/, '');
let urlString = url.toString();
if (url.pathname === '/' && url.hash === '') {
urlString = removeTrailingSlash(urlString);
}
return urlString;
};
//# sourceMappingURL=url.js.map