From ad0ebc21aa694627fb8e50e850b44d983ebdee50 Mon Sep 17 00:00:00 2001 From: leoca Date: Sat, 14 Nov 2026 04:25:14 +0000 Subject: [PATCH] fix: sort query parameters without decoding their escapes Disabling sortQueryParameters left the parameters in their original order, so the same link written with a different order would no longer be recognized as a duplicate. The parameters are now sorted by name like URLSearchParams.sort() does, but each one is kept as written, so %26, %3D, %3F and %2B are not decoded. --- scripts/utils.ts | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/scripts/utils.ts b/scripts/utils.ts index e5a17110db..400b0b691e 100644 --- a/scripts/utils.ts +++ b/scripts/utils.ts @@ -38,10 +38,32 @@ export function isURI(string: string): boolean { } } +// Sorts the query parameters like URLSearchParams.sort(), but keeps each one as written, so +// escapes like %26, %3D and %2B are not decoded the way normalize-url's own sorting does +function sortQueryParameters(url: string): string { + const queryStart = url.indexOf('?') + if (queryStart === -1) return url + const hashStart = url.indexOf('#', queryStart) + const queryEnd = hashStart === -1 ? url.length : hashStart + const getName = (param: string) => new URLSearchParams(param).keys().next().value ?? '' + const params = url + .slice(queryStart + 1, queryEnd) + .split('&') + .filter(Boolean) + .map(param => ({ param, name: getName(param) })) + .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) + .map(({ param }) => param) + const query = params.length ? `?${params.join('&')}` : '' + + return url.slice(0, queryStart) + query + url.slice(queryEnd) +} + export function normalizeURL(url: string): string { let normalized: string try { - normalized = normalizeUrl(url, { stripWWW: false, sortQueryParameters: false }) + normalized = sortQueryParameters( + normalizeUrl(url, { stripWWW: false, sortQueryParameters: false }) + ) } catch { return url.replace(/\s/g, '+') }