diff --git a/lib/src/utils.test.ts b/lib/src/utils.test.ts new file mode 100644 index 00000000..0e7f29c7 --- /dev/null +++ b/lib/src/utils.test.ts @@ -0,0 +1,37 @@ +import {pathToFileURL} from 'url'; +import {pathToUrlString} from './utils'; + +describe('utils', () => { + describe('pathToUrlString', () => { + it('encode relative path like `pathToFileURL`', () => { + const baseURL = pathToFileURL('').toString(); + for (let i = 0; i < 128; i++) { + const char = String.fromCharCode(i); + const filename = `${i}-${char}`; + expect(pathToUrlString(filename)).toEqual( + pathToFileURL(filename) + .toString() + .slice(baseURL.length + 1) + ); + } + }); + + it('encode percent encoded string like `pathToFileURL`', () => { + const baseURL = pathToFileURL('').toString(); + for (let i = 0; i < 128; i++) { + const lowercase = `%${i < 10 ? '0' : ''}${i.toString(16)}`; + expect(pathToUrlString(lowercase)).toEqual( + pathToFileURL(lowercase) + .toString() + .slice(baseURL.length + 1) + ); + const uppercase = lowercase.toUpperCase(); + expect(pathToUrlString(uppercase)).toEqual( + pathToFileURL(uppercase) + .toString() + .slice(baseURL.length + 1) + ); + } + }); + }); +}); diff --git a/lib/src/utils.ts b/lib/src/utils.ts index 56c02dfa..ef108bf9 100644 --- a/lib/src/utils.ts +++ b/lib/src/utils.ts @@ -90,8 +90,14 @@ export function valueError(message: string, name?: string): Error { export function pathToUrlString(path: string): string { if (p.isAbsolute(path)) return url.pathToFileURL(path).toString(); - const components = p.sep === '\\' ? path.split(/[/\\]/) : path.split('/'); - return components.map(encodeURIComponent).join('/'); + // percent encode relative path like `pathToFileURL` + return encodeURI(path) + .replace(/[#?]/g, encodeURIComponent) + .replace( + process.platform === 'win32' ? /%(5B|5C|5D|5E|7C)/g : /%(5B|5D|5E|7C)/g, + decodeURIComponent + ) + .replace(/\\/g, '/'); } /**