From 016b41552e9736cedfefb2890ecdabb07dabc908 Mon Sep 17 00:00:00 2001 From: Percs <83934299+Percslol@users.noreply.github.com> Date: Sat, 13 Jul 2024 00:44:54 -0500 Subject: [PATCH] fix css rewriting --- src/bundle/rewriters/css.ts | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/src/bundle/rewriters/css.ts b/src/bundle/rewriters/css.ts index c74b882..381394b 100644 --- a/src/bundle/rewriters/css.ts +++ b/src/bundle/rewriters/css.ts @@ -1,11 +1,32 @@ import { encodeUrl } from "./url"; export function rewriteCss(css: string, origin?: URL) { - css = css.replace(/(?<=url\("?'?)[^"'][\S]*[^"'](?="?'?\);?)/gm, (match) => encodeUrl(match, origin)); - //painful regex simulator - css = css.replace(/@import\s+(['"])?([^'");]+)\1?\s*(?:;|$)/gm, (_, quote, url) => { - return `@import ${quote || ""}${encodeUrl(url.trim(), origin)}${quote || ""};`; - }); + const regex = + /(@import\s+(?!url\())?\s*url\(\s*(['"]?)([^'")]+)\2\s*\)|@import\s+(['"])([^'"]+)\4/g + + return css.replace( + regex, + ( + match, + importStatement, + urlQuote, + urlContent, + importQuote, + importContent + ) => { + const url = urlContent || importContent + const encodedUrl = encodeUrl(url.trim(), origin) + + if (importStatement) { + return `@import url(${urlQuote}${encodedUrl}${urlQuote})` + } + + if (importQuote) { + return `@import ${importQuote}${encodedUrl}${importQuote}` + } + + return `url(${urlQuote}${encodedUrl}${urlQuote})` + } + ) - return css; }