2025-09-05 14:59:21 +08:00

38 lines
1.5 KiB
JavaScript

'use strict';
const ufo = require('ufo');
function resolveSitePath(pathOrUrl, options) {
let path = pathOrUrl;
if (ufo.hasProtocol(pathOrUrl, { strict: false, acceptRelative: true })) {
const parsed = ufo.parseURL(pathOrUrl);
path = parsed.pathname;
}
const base = ufo.withLeadingSlash(options.base || "/");
if (base !== "/" && path.startsWith(base)) {
path = path.slice(base.length);
}
let origin = ufo.withoutTrailingSlash(options.absolute ? options.siteUrl : "");
if (base !== "/" && origin.endsWith(base)) {
origin = origin.slice(0, origin.indexOf(base));
}
const baseWithOrigin = options.withBase ? ufo.withBase(base, origin || "/") : origin;
const resolvedUrl = ufo.withBase(path, baseWithOrigin);
return path === "/" && !options.withBase ? ufo.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 = ufo.parseURL(pathOrUrl);
if (isPathFile($url.pathname))
return pathOrUrl;
const fixedPath = trailingSlash ? ufo.withTrailingSlash($url.pathname) : ufo.withoutTrailingSlash($url.pathname);
return `${$url.protocol ? `${$url.protocol}//` : ""}${$url.host || ""}${fixedPath}${$url.search || ""}${$url.hash || ""}`;
}
exports.fixSlashes = fixSlashes;
exports.isPathFile = isPathFile;
exports.resolveSitePath = resolveSitePath;