@flex-development/pathe
Version:
Universal drop-in replacement for node:path
60 lines (59 loc) • 2.03 kB
JavaScript
import canParseURL from "#internal/can-parse-url";
import { DRIVE_PATH_REGEX } from "#internal/constants";
import validateURLString from "#internal/validate-url-string";
import delimiter from "#lib/delimiter";
import dot from "#lib/dot";
import isSep from "#lib/is-sep";
import sep from "#lib/sep";
import toPosix from "#lib/to-posix";
function dirname(input) {
validateURLString(input, "input");
input = String(toPosix(input));
let end = -1;
let rootEnd = -1;
if (input.length > 1) {
let offset = 0;
if (canParseURL(input)) {
rootEnd = offset = input.lastIndexOf(new URL(input).pathname);
if (offset === -1) rootEnd = offset = input.length;
if (DRIVE_PATH_REGEX.test(input.slice(offset + 1))) offset++;
}
if (isSep(input[offset])) {
rootEnd = ++offset;
if (isSep(input[offset])) {
let j = offset + 1;
let last = j;
while (j < input.length && !isSep(input[j])) j++;
if (j < input.length && j !== last) {
last = j;
while (j < input.length && isSep(input[j])) j++;
if (j < input.length && j !== last) {
last = j;
while (j < input.length && !isSep(input[j])) j++;
if (j === input.length) return input;
if (j !== last) rootEnd = offset = j + 1;
}
}
}
} else if (DRIVE_PATH_REGEX.test(input.slice(offset))) {
rootEnd = offset = input.indexOf(delimiter, offset) + 1;
if (input.length > 2 && isSep(input[offset])) rootEnd = ++offset;
}
let separator = true;
for (let i = input.length - 1; i >= offset; --i) {
if (isSep(input[i])) {
if (!separator) {
end = i;
break;
}
} else {
separator = false;
}
}
}
return end === -1 && rootEnd === end ? input.length === 1 && isSep(input) ? sep : dot : isSep(input[0]) && end === 1 ? sep + sep : input.slice(0, end === -1 ? rootEnd : end);
}
var dirname_default = dirname;
export {
dirname_default as default
};