Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Percent encode relative path like url.pathToFileURL #134

Merged
merged 3 commits into from
Apr 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions lib/src/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import {pathToFileURL} from 'url';
import {pathToUrlString} from './utils';

describe('utils', () => {
describe('pathToUrlString', () => {
it('encode relative path like `pathToFileURL`', () => {
ntkme marked this conversation as resolved.
Show resolved Hide resolved
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)
);
}
});
});
});
10 changes: 8 additions & 2 deletions lib/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
ntkme marked this conversation as resolved.
Show resolved Hide resolved
.replace(/\\/g, '/');
}

/**
Expand Down