@jsenv/href
Version:
url helpers not relying on URL constructor
97 lines (74 loc) • 3 kB
JavaScript
Object.defineProperty(exports, '__esModule', { value: true });
const hrefToScheme = href => {
const colonIndex = href.indexOf(":");
if (colonIndex === -1) return "";
return href.slice(0, colonIndex);
};
const hrefToOrigin = href => {
const scheme = hrefToScheme(href);
if (scheme === "file") {
return "file://";
}
if (scheme === "http" || scheme === "https") {
const secondProtocolSlashIndex = scheme.length + "://".length;
const pathnameSlashIndex = href.indexOf("/", secondProtocolSlashIndex);
if (pathnameSlashIndex === -1) return href;
return href.slice(0, pathnameSlashIndex);
}
return href.slice(0, scheme.length + 1);
};
const hrefToPathname = href => {
return ressourceToPathname(hrefToRessource(href));
};
const hrefToRessource = href => {
const scheme = hrefToScheme(href);
if (scheme === "file") {
return href.slice("file://".length);
}
if (scheme === "https" || scheme === "http") {
// remove origin
const afterProtocol = href.slice(scheme.length + "://".length);
const pathnameSlashIndex = afterProtocol.indexOf("/", "://".length);
return afterProtocol.slice(pathnameSlashIndex);
}
return href.slice(scheme.length + 1);
};
const ressourceToPathname = ressource => {
const searchSeparatorIndex = ressource.indexOf("?");
return searchSeparatorIndex === -1 ? ressource : ressource.slice(0, searchSeparatorIndex);
};
const pathnameIsInside = (pathname, otherPathname) => pathname.startsWith(`${otherPathname}/`);
const pathnameToDirname = pathname => {
const slashLastIndex = pathname.lastIndexOf("/");
if (slashLastIndex === -1) return "";
return pathname.slice(0, slashLastIndex);
};
const pathnameToExtension = pathname => {
const slashLastIndex = pathname.lastIndexOf("/");
if (slashLastIndex !== -1) {
pathname = pathname.slice(slashLastIndex + 1);
}
const dotLastIndex = pathname.lastIndexOf(".");
if (dotLastIndex === -1) return ""; // if (dotLastIndex === pathname.length - 1) return ""
return pathname.slice(dotLastIndex);
};
const pathnameToRelativePath = (pathname, otherPathname) => pathname.slice(otherPathname.length);
const ressourceToPathname$1 = ressource => {
const searchSeparatorIndex = ressource.indexOf("?");
return searchSeparatorIndex === -1 ? ressource : ressource.slice(0, searchSeparatorIndex);
};
const ressourceToSearch = ressource => {
const searchSeparatorIndex = ressource.indexOf("?");
return searchSeparatorIndex === -1 ? "?" : ressource.slice(searchSeparatorIndex);
};
exports.hrefToOrigin = hrefToOrigin;
exports.hrefToPathname = hrefToPathname;
exports.hrefToScheme = hrefToScheme;
exports.pathnameIsInside = pathnameIsInside;
exports.pathnameToDirname = pathnameToDirname;
exports.pathnameToExtension = pathnameToExtension;
exports.pathnameToRelativePath = pathnameToRelativePath;
exports.ressourceToPathname = ressourceToPathname$1;
exports.ressourceToSearch = ressourceToSearch;
//# sourceMappingURL=main.js.map
;