Skip to content
Closed
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
14 changes: 14 additions & 0 deletions src/cases.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,20 @@ export const STRINGIFY_TESTS: StringifyTestSet[] = [
]),
expected: '/*"0"',
},
{
data: new TokenData([
{ type: "text", value: "/" },
{ type: "param", name: "a\tb" },
]),
expected: '/:"a\tb"',
},
{
data: new TokenData([
{ type: "text", value: "/" },
{ type: "param", name: 'a"b\\c' },
]),
expected: '/:"a\\"b\\\\c"',
},
{
data: new TokenData([
{ type: "text", value: "/users" },
Expand Down
5 changes: 5 additions & 0 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,11 @@ describe("path-to-regexp", () => {
const path = stringify(data);
expect(path).toEqual(expected);
});

it("should parse back to the original tokens", () => {
const { tokens } = parse(stringify(data));
expect(tokens).toEqual(data.tokens);
});
},
);

Expand Down
14 changes: 12 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -659,11 +659,21 @@ export function stringify(data: TokenData): string {
* Stringify a parameter name, escaping when it cannot be emitted directly.
*/
function stringifyName(name: string, next: Token | undefined): string {
if (!ID.test(name)) return JSON.stringify(name);
if (!ID.test(name)) return quoteName(name);

if (next?.type === "text" && ID_CONTINUE.test(next.value[0])) {
return JSON.stringify(name);
return quoteName(name);
}

return name;
}

/**
* Quote a parameter name using the escape rules understood by `parse`,
* which only recognizes a backslash as escaping the next character.
* `JSON.stringify` would emit escapes such as `\t` or `\uXXXX` that
* `parse` reads back as the literal characters `t` or `uXXXX`.
*/
function quoteName(name: string): string {
return `"${name.replace(/["\\]/g, "\\$&")}"`;
}