Skip to content
Open
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
22 changes: 18 additions & 4 deletions src/encoding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,31 @@
/ "*" / "+" / "," / ";" / "="
*/

const excludeSubDelimiters = /[^!$'()*+,;|:]/g

export type URLParamsEncodingType =
| 'default'
| 'uri'
| 'uriComponent'
| 'none'
| 'legacy'

export const encodeURIComponentExcludingSubDelims = (segment: string): string =>
segment.replace(excludeSubDelimiters, match => encodeURIComponent(match))
export const encodeURIComponentExcludingSubDelims = (
segment: string
): string => {
// Define sub-delimiters to exclude from encoding
const subDelimiters = /[!$'()*+,;|:]/g

// Use Array.from to correctly handle characters represented by surrogate pairs
return Array.from(segment)
.map(char => {
// Check if the character is a sub-delimiter
if (subDelimiters.test(char)) {
return char // Return the character as is if it's a sub-delimiter
Comment on lines +33 to +34
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could probably be optimized a bit more, perhaps checking for character codes instead of matching against a regex. But maybe JS engines are so smart these days that it doesn't matter. Did you ever benchmark path-parser?

} else {
return encodeURIComponent(char) // Otherwise, encode it
}
})
.join('') // Join the array back into a string
}

const encodingMethods: Record<
URLParamsEncodingType,
Expand Down
11 changes: 11 additions & 0 deletions test/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,17 @@ describe('Path', () => {
)
})

it('should match and build paths with emojis in query parameters', () => {
const pathA = new Path('/home?emoji')

expect(pathA.build({ emoji: '🤗' })).toEqual('/home?emoji=%F0%9F%A4%97')

const path = new Path('/home?emoji')
expect(path.test('/home?emoji=%F0%9F%99%8C')).toEqual({
emoji: '🙌'
})
})

it('should match and build paths with query parameters', () => {
const path = new Path('/users?offset&limit', {
queryParams: { booleanFormat: 'string' }
Expand Down