UNPKG

@flex-development/pathe

Version:

Universal drop-in replacement for node:path

67 lines (66 loc) 2.1 kB
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 isSep from "#lib/is-sep"; import toPosix from "#lib/to-posix"; function root(input) { validateURLString(input, "input"); input = String(toPosix(input)); if (input.length) { let end = 0; let onlyRoot = false; if (isSep(input)) { onlyRoot = true; } else { let offset = 0; if (canParseURL(input)) { const { hostname, pathname, protocol } = new URL(input); if (hostname) { if (protocol === "file:") { offset = protocol.length; } else { end = protocol.length + hostname.length + 2; } } else if (input === protocol) { onlyRoot = true; offset = -1; } else { offset = input.lastIndexOf(pathname); if (DRIVE_PATH_REGEX.test(pathname.slice(1))) offset++; } } if (isSep(input[offset])) { end = offset + 1; if (isSep(input[end])) { let j = end + 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) end = j; else if (j !== last) end = j + 1; } } } } else if (DRIVE_PATH_REGEX.test(input.slice(offset))) { end = input.indexOf(delimiter, offset) + 1; if (input.length <= end) { onlyRoot = true; } else if (isSep(input[end])) { if (input.length === ++end) onlyRoot = true; } } } if (end || onlyRoot) return onlyRoot ? input : input.slice(0, end); } return ""; } var root_default = root; export { root_default as default };