UNPKG

@cloudcome/utils-core

Version:
82 lines (81 loc) 1.97 kB
import { arrayEach } from "./array.mjs"; function _isCurrentSlice(slice) { return slice === "."; } function _isParentSlice(slice) { return slice === ".."; } function isAbsolutePath(path) { return path.startsWith("/"); } function isRelativePath(path) { return !isAbsolutePath(path); } function pathNormalize(path) { const slices = path.replace(/\\/g, "/").replace(/\/{2,}/g, "/").replace(/\.{3,}/g, "..").replace(/\/\.\//g, "/").split("/").map((point) => point.trim()); const points = []; const isAbs = slices[0] === ""; const push = (point) => { points.push(point); }; const back = () => { if (points.length === 1 && isAbs) return; if (points.length === 0 || points.at(-1) === "..") { points.push(".."); } else { points.pop(); } }; for (const slice of slices) { const isCurrent = _isCurrentSlice(slice); const isParent = _isParentSlice(slice); if (isCurrent) { continue; } if (isParent) { back(); continue; } push(slice); } return points.join("/") || (isAbs ? "/" : "."); } function pathJoin(from, ...to) { return pathNormalize([from, ...to].join("/")); } function pathResolve(from, ...to) { const paths = [from, ...to].map(pathNormalize); let lastStartPath = from; let lastStartIndex = 0; arrayEach( paths, (path, index) => { if (isAbsolutePath(path)) { lastStartPath = path; lastStartIndex = index; return false; } }, true ); return pathJoin(lastStartPath, ...paths.slice(lastStartIndex + 1)); } function pathRelativize(path) { if (isAbsolutePath(path)) return path; if (path.startsWith("./")) return path; if (path.startsWith("../")) return path; return `./${path}`; } function pathDirname(path) { return pathJoin(path, ".."); } export { isAbsolutePath, isRelativePath, pathDirname, pathJoin, pathNormalize, pathRelativize, pathResolve }; //# sourceMappingURL=path.mjs.map