Skip to content

Commit

Permalink
fix: fix single quote encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
asmyshlyaev177 committed Nov 10, 2024
1 parent f38637c commit 8e768b6
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 5 deletions.
5 changes: 5 additions & 0 deletions packages/urlstate/encoder/encoder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ describe('encoder', () => {
const str = '"test #?\t=\n[]{}()%.';
expect(decode(encode(str))).toStrictEqual(str);
});

it('single quote', () => {
const str = "'";
expect(decode(encode(str))).toStrictEqual(str);
});
});

describe('number', () => {
Expand Down
9 changes: 7 additions & 2 deletions packages/urlstate/encoder/encoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ export function encode(payload: unknown): string {
case "undefined":
return SYMBOLS.undefined;
default:
return JSON.stringify(payload).replaceAll('"', "'");
return JSON.stringify(payload)
.replaceAll("'", "%27")
.replaceAll('"', "'");
}
}

Expand All @@ -46,7 +48,10 @@ export type Primitive = Exclude<
* * Docs {@link https://github.com/asmyshlyaev177/state-in-url/tree/master/packages/urlstate/encoder#decode}
*/
export function decode<T>(payload: string, fallback?: T) {
return parseJSON(payload.replaceAll("'", '"'), fallback as JSONCompatible);
return parseJSON(
payload.replaceAll("'", '"').replaceAll("%27", "'"),
fallback as JSONCompatible,
);
}

export const decodePrimitive = (str: string) => {
Expand Down
6 changes: 3 additions & 3 deletions tests/useUrlState/main.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ const delay = 1

test.describe('main tests', () => {
const expectedUrl =
'?name=%27My+Name%27&age=33&agree_to_terms=true&tags=%5B%7B%27id%27%3A%271%27%2C%27value%27%3A%7B%27text%27%3A%27React.js%27%2C%27time%27%3A%272024-07-17T04%3A53%3A17.000Z%27%7D%7D%5D';
'?name=%27My+Name%2527%27&age=33&agree_to_terms=true&tags=%5B%7B%27id%27%3A%271%27%2C%27value%27%3A%7B%27text%27%3A%27React.js%27%2C%27time%27%3A%272024-07-17T04%3A53%3A17.000Z%27%7D%7D%5D';
const expectedText = `{
"name": "My Name",
"name": "My Name'",
"age": 33,
"agree_to_terms": true,
"tags": [
Expand All @@ -31,7 +31,7 @@ test.describe('main tests', () => {
}
]
}`;
const values = { name: 'My Name', age: '33' };
const values = { name: "My Name'", age: '33' };

for (const url of urls) {
test(`fast concurent URL updates ${url}`, async ({ page }) => {
Expand Down

0 comments on commit 8e768b6

Please sign in to comment.