34 lines
1.4 KiB
JavaScript
34 lines
1.4 KiB
JavaScript
import { hasProtocol, parseURL, withLeadingSlash, withoutTrailingSlash, withBase, withTrailingSlash } from 'ufo';
|
|
|
|
function resolveSitePath(pathOrUrl, options) {
|
|
let path = pathOrUrl;
|
|
if (hasProtocol(pathOrUrl, { strict: false, acceptRelative: true })) {
|
|
const parsed = parseURL(pathOrUrl);
|
|
path = parsed.pathname;
|
|
}
|
|
const base = withLeadingSlash(options.base || "/");
|
|
if (base !== "/" && path.startsWith(base)) {
|
|
path = path.slice(base.length);
|
|
}
|
|
let origin = withoutTrailingSlash(options.absolute ? options.siteUrl : "");
|
|
if (base !== "/" && origin.endsWith(base)) {
|
|
origin = origin.slice(0, origin.indexOf(base));
|
|
}
|
|
const baseWithOrigin = options.withBase ? withBase(base, origin || "/") : origin;
|
|
const resolvedUrl = withBase(path, baseWithOrigin);
|
|
return path === "/" && !options.withBase ? withTrailingSlash(resolvedUrl) : fixSlashes(options.trailingSlash, resolvedUrl);
|
|
}
|
|
function isPathFile(path) {
|
|
const lastSegment = path.split("/").pop();
|
|
return !!(lastSegment || path).match(/\.[0-9a-z]+$/i)?.[0];
|
|
}
|
|
function fixSlashes(trailingSlash, pathOrUrl) {
|
|
const $url = parseURL(pathOrUrl);
|
|
if (isPathFile($url.pathname))
|
|
return pathOrUrl;
|
|
const fixedPath = trailingSlash ? withTrailingSlash($url.pathname) : withoutTrailingSlash($url.pathname);
|
|
return `${$url.protocol ? `${$url.protocol}//` : ""}${$url.host || ""}${fixedPath}${$url.search || ""}${$url.hash || ""}`;
|
|
}
|
|
|
|
export { fixSlashes, isPathFile, resolveSitePath };
|