From 3015dff77d1dcdcb75b8b55858ba30b351336390 Mon Sep 17 00:00:00 2001 From: Terry <187264680+gennaroterry@users.noreply.github.com> Date: Mon, 11 Nov 2024 08:35:10 +0000 Subject: [PATCH] fix: Improve srcset rewriter to handle descriptors correctly. The previous implementation failed to properly rewrite srcset attributes when they contained descriptors (like 1.5x, 2x). Updated the parser to preserve descriptors while rewriting URLs. --- src/shared/rewriters/html.ts | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/shared/rewriters/html.ts b/src/shared/rewriters/html.ts index 6e6b8f4..7fddf3f 100644 --- a/src/shared/rewriters/html.ts +++ b/src/shared/rewriters/html.ts @@ -283,17 +283,20 @@ function traverseParsedHtml( } export function rewriteSrcset(srcset: string, meta: URLMeta) { - const urls = srcset.split(/ [0-9]+x,? ?/g); - if (!urls) return ""; - const sufixes = srcset.match(/ [0-9]+x,? ?/g); - if (!sufixes) return ""; - const rewrittenUrls = urls.map((url, i) => { - if (url && sufixes[i]) { - return rewriteUrl(url, meta) + sufixes[i]; - } + const sources = srcset.split(",").map((src) => src.trim()); + const rewrittenSources = sources.map((source) => { + // Split into URLs and descriptors (if any) + // e.g. url0, url1 1.5x, url2 2x + const [url, ...descriptors] = source.split(/\s+/); + + // Rewrite the URLs and keep the descriptors (if any) + const rewrittenUrl = rewriteUrl(url.trim(), meta); + return descriptors.length > 0 + ? `${rewrittenUrl} ${descriptors.join(" ")}` + : rewrittenUrl; }); - return rewrittenUrls.join(""); + return rewrittenSources.join(", "); } // function base64ToBytes(base64) {