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
7 changes: 7 additions & 0 deletions src/cases.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,13 @@ export const STRINGIFY_TESTS: StringifyTestSet[] = [
]),
expected: "\\\\:test",
},
{
data: new TokenData([
{ type: "text", value: "/" },
{ type: "param", name: "a\nb" },
]),
expected: '/:"a\nb"',
},
{
data: {
tokens: [
Expand Down
15 changes: 13 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -655,14 +655,25 @@ export function stringify(data: TokenData): string {
return stringifyTokens(data.tokens, 0);
}

/**
* Wrap a parameter name in quotes, escaping only the characters the parser
* treats specially inside a quoted name (`"` and `\`). `JSON.stringify` can't
* be used here because it emits escapes like `\n` that the parser reads back as
* the literal character `n`, so names with control characters wouldn't survive
* a `parse` -> `stringify` -> `parse` round trip.
*/
function quoteName(name: string): string {
return `"${name.replace(/["\\]/g, "\\$&")}"`;
}

/**
* 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;
Expand Down