diff --git a/src/utils.ts b/src/utils.ts index bf5bca6..6ec11c1 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -5,6 +5,8 @@ const pathSeparators = new Set(["/", "\\", undefined]); const normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias"); +const SLASH_RE = /[/\\]/; + /** * Normalises alias mappings, ensuring that more specific aliases are resolved before less specific ones. * This function also ensures that aliases do not resolve to themselves cyclically. @@ -72,8 +74,6 @@ export function resolveAlias(path: string, aliases: Record) { return _path; } -const FILENAME_RE = /(^|[/\\])([^/\\]+?)(?=(\.[^.]+)?$)/; - /** * Extracts the filename from a given path, excluding any directory paths and the file extension. * @@ -81,7 +81,19 @@ const FILENAME_RE = /(^|[/\\])([^/\\]+?)(?=(\.[^.]+)?$)/; * @returns the filename without the extension, or `undefined` if the filename cannot be extracted. */ export function filename(path: string) { - return path.match(FILENAME_RE)?.[2]; + const base = path.split(SLASH_RE).pop(); + + if (!base) { + return undefined; + } + + const separatorIndex = base.lastIndexOf("."); + + if (separatorIndex <= 0) { + return base; + } + + return base.slice(0, separatorIndex); } // --- internals --- diff --git a/test/utils.spec.ts b/test/utils.spec.ts index 71a9fd9..51ad676 100644 --- a/test/utils.spec.ts +++ b/test/utils.spec.ts @@ -64,12 +64,24 @@ describe("filename", () => { "test.html": "test", "/temp/myfile.html": "myfile", "./myfile.html": "myfile", + "/Users/john.doe/foo/myFile.js": "myFile", + "/Users/john.doe/foo/myFile": "myFile", + "./.hidden/myFile.ts": "myFile", + "./.hidden/myFile": "myFile", + "/temp/.gitignore": ".gitignore", + "./foo.bar.baz.js": "foo.bar.baz", // Windows "C:\\temp\\": undefined, "C:\\temp\\myfile.html": "myfile", "\\temp\\myfile.html": "myfile", ".\\myfile.html": "myfile", + ".\\john.doe\\myfile.js": "myfile", + ".\\john.doe\\myfile": "myfile", + ".\\.hidden\\myfile.js": "myfile", + ".\\.hidden\\myfile": "myfile", + "C:\\temp\\.gitignore": ".gitignore", + "C:\\temp\\foo.bar.baz.js": "foo.bar.baz", }; for (const file in files) { it(file, () => {