UNPKG

@stryke/path

Version:

A package containing various utilities that expand the functionality of NodeJs's built-in `path` module

64 lines (63 loc) 1.93 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.joinPaths = void 0; const g = /^[A-Z]:\//i; function u(e = "") { return e && e.replace(/\\/g, "/").replace(g, t => t.toUpperCase()); } const E = /^[/\\]{2}/, _ = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Z]:[/\\]/i, a = /^[A-Z]:$/i, c = function (e) { return _.test(e); }, h = function (e) { if (!e || e.length === 0) return "."; e = u(e); const t = e.match(E), n = c(e), s = e[e.length - 1] === "/"; return e = R(e, !n), e.length === 0 ? n ? "/" : s ? "./" : "." : (s && (e += "/"), a.test(e) && (e += "/"), t ? n ? `//${e}` : `//./${e}` : n && !c(e) ? `/${e}` : e); }; const joinPaths = function (...e) { let t = ""; for (const n of e) if (n) if (t.length > 0) { const s = t[t.length - 1] === "/", i = n[0] === "/"; s && i ? t += n.slice(1) : t += s || i ? n : `/${n}`; } else t += n; return h(t); }; exports.joinPaths = joinPaths; function R(e, t) { let n = "", s = 0, i = -1, o = 0, r = null; for (let l = 0; l <= e.length; ++l) { if (l < e.length) r = e[l];else { if (r === "/") break; r = "/"; } if (r === "/") { if (!(i === l - 1 || o === 1)) if (o === 2) { if (n.length < 2 || s !== 2 || n[n.length - 1] !== "." || n[n.length - 2] !== ".") { if (n.length > 2) { const f = n.lastIndexOf("/"); f === -1 ? (n = "", s = 0) : (n = n.slice(0, f), s = n.length - 1 - n.lastIndexOf("/")), i = l, o = 0; continue; } else if (n.length > 0) { n = "", s = 0, i = l, o = 0; continue; } } t && (n += n.length > 0 ? "/.." : "..", s = 2); } else n.length > 0 ? n += `/${e.slice(i + 1, l)}` : n = e.slice(i + 1, l), s = l - i - 1; i = l, o = 0; } else r === "." && o !== -1 ? ++o : o = -1; } return n; }