Skip to content

Commit

Permalink
Update relative pathToFileURL to match node
Browse files Browse the repository at this point in the history
  • Loading branch information
ntkme committed Dec 10, 2024
1 parent ebeb169 commit d63f98e
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions lib/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,18 +86,29 @@ export function valueError(message: string, name?: string): Error {
return Error(name ? `$${name}: ${message}.` : `${message}.`);
}

// Node changed its implementation of pathToFileURL:
// https://github.com/nodejs/node/pull/54545
const unsafePathToFileURL = url.pathToFileURL('~').pathname.endsWith('~');

/** Converts a (possibly relative) path on the local filesystem to a URL. */
export function pathToUrlString(path: string): string {
if (p.isAbsolute(path)) return url.pathToFileURL(path).toString();

// 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, '/');
return unsafePathToFileURL
? encodeURI(path)
.replace(/[#?]/g, encodeURIComponent)
.replace(
process.platform === 'win32'
? /%(5B|5C|5D|5E|7C)/g
: /%(5B|5D|5E|7C)/g,
decodeURIComponent,
)
.replace(/\\/g, '/')
: encodeURI(path)
.replace(/[#?]/g, encodeURIComponent)
.replace(/~/g, '%7E')
.replace(/\\/g, '/');
}

/**
Expand Down

0 comments on commit d63f98e

Please sign in to comment.