From 402856ea28a556626244a4b7141bc6b048bc0571 Mon Sep 17 00:00:00 2001 From: Soroush Baraouf Date: Thu, 19 Nov 2026 11:20:49 -0500 Subject: [PATCH 1/4] test(shared): cover theme CSS with escaped quotes and comment markers in strings Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/themeCss.test.ts | 17 ++ ...shes-css-with-quoted-comment-marker.e2e.ts | 170 ++++++++++++++++++ 2 files changed, 187 insertions(+) create mode 100644 scripts/scenarios/theme-publishes-css-with-quoted-comment-marker.e2e.ts diff --git a/packages/shared/src/themeCss.test.ts b/packages/shared/src/themeCss.test.ts index 9b63049b0e360..14ed259be7c15 100644 --- a/packages/shared/src/themeCss.test.ts +++ b/packages/shared/src/themeCss.test.ts @@ -32,7 +32,24 @@ describe("themeCssValueFetches", () => { describe("themeCssLoadsRemoteFiles", () => { it.each([ ['[data-chat-header]::after { content: "@import"; }', false], + ['.a::after { content: "say \\"@import\\""; }', false], + [".a::after { content: 'a\\' @import'; }", false], + ['.a::after { content: "a\\\r\n@import"; }', false], + ['.a::after { content: "\\22\r\n@import"; }', false], + ['.a::after { content: "/*"; } /* note */ .b::after { content: "@import"; }', false], + ['/* @import "x.css"; */ .a::after { content: "*/"; }', false], + [ + ".a { background-image: url(data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22%3E%3C!--/*@import*/--%3E%3C/svg%3E); }", + false, + ], + [ + ".a { background-image: url(data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22%3E%3C!--/*@import\\2e */--%3E%3C/svg%3E); }", + false, + ], ['@import "x.css";', true], + ['.a::after { content: "\\\\"; } @import "x.css";', true], + ['.a { background: url("https://example.invalid/x.png"); }', true], + [".a { background: url(https://example.invalid/x.png); }", true], ])("%s", (css, loads) => { expect(themeCssLoadsRemoteFiles(css)).toBe(loads); }); diff --git a/scripts/scenarios/theme-publishes-css-with-quoted-comment-marker.e2e.ts b/scripts/scenarios/theme-publishes-css-with-quoted-comment-marker.e2e.ts new file mode 100644 index 0000000000000..5e769a4f6510f --- /dev/null +++ b/scripts/scenarios/theme-publishes-css-with-quoted-comment-marker.e2e.ts @@ -0,0 +1,170 @@ +// @effect-diagnostics nodeBuiltinImport:off -- The scenario stages a local ACP executable. +import * as NodeFSP from "node:fs/promises"; +import * as NodePath from "node:path"; + +import { expect } from "e2e"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +const THEME = { + name: "Literal CSS", + appearance: "dark", + canvas: "#1a1b26", + accent: "#7aa2f7", + css: '[data-chat-header]::before { content: "/*"; } /* note */ [data-chat-header]::after { content: "@import"; }', +}; +const PUBLISHED = "Published Literal CSS."; +const REFUSED = + 'Theme not published: Theme "literal-css" has CSS that loads files. Remove @import, image-set(), and url() that is not data: or #id.'; +const ACP = ` +import { request as post } from "node:http"; +import { createInterface } from "node:readline"; + +const sessionId = "theme-publish-scenario"; +const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n"); +const respond = (id, result) => send({ id, result }); +const update = (update) => send({ method: "session/update", params: { sessionId, update } }); +let mcp = { endpoint: process.env.T3_ACP_MCP_ENDPOINT, authorization: process.env.T3_ACP_MCP_AUTHORIZATION }; +let mcpSession; +async function request(message) { + const body = await new Promise((resolve, reject) => { + const req = post(mcp.endpoint, { + method: "POST", + headers: { + "content-type": "application/json", + accept: "application/json, text/event-stream", + authorization: mcp.authorization, + ...(mcpSession ? { "mcp-session-id": mcpSession } : {}), + }, + }, (response) => { + mcpSession = response.headers["mcp-session-id"] ?? mcpSession; + let body = ""; + response.setEncoding("utf8"); + response.on("data", (chunk) => { body += chunk; }); + response.on("end", () => resolve(body)); + response.on("error", reject); + }); + req.on("error", reject); + req.end(JSON.stringify({ jsonrpc: "2.0", ...message })); + }); + if (message.id === undefined) return; + const payload = body.split("\\n").find((line) => line.startsWith("data: "))?.slice(6) ?? body; + const { result, error } = JSON.parse(payload); + if (error) throw new Error(JSON.stringify(error)); + return result; +} +async function setTheme() { + await request({ id: 1, method: "initialize", params: { + protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "theme-agent", version: "1" }, + } }); + await request({ method: "notifications/initialized" }); + const result = await request({ id: 2, method: "tools/call", params: { + name: "t3_theme_set", arguments: { themeId: "literal-css", theme: ${JSON.stringify(THEME)} }, + } }); + const { published, themeId } = result.structuredContent ?? {}; + if (result.isError !== true && published === true && themeId === "literal-css") { + return ${JSON.stringify(PUBLISHED)}; + } + const text = result.content.map(({ text }) => text).join(" "); + return "Theme not published: " + (text.startsWith("{") ? JSON.parse(text).message : text); +} +for await (const line of createInterface({ input: process.stdin })) { + const { id, method, params } = JSON.parse(line); + if (id === undefined) continue; + if (method === "initialize") { + respond(id, { protocolVersion: 2, info: { name: "theme-agent", version: "1.0.0" } }); + } else if (method === "session/new") { + const env = params.mcpServers?.find((server) => server.name === "t3-code")?.env ?? []; + const value = (name) => env.find((entry) => entry.name === name)?.value; + mcp = { + endpoint: value("T3_ACP_MCP_ENDPOINT") ?? mcp.endpoint, + authorization: value("T3_ACP_MCP_AUTHORIZATION") ?? mcp.authorization, + }; + respond(id, { sessionId }); + } else if (method === "session/prompt") { + const text = await setTheme().catch((error) => "Theme tool failed: " + error.message); + update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text } }); + update({ sessionUpdate: "state_update", state: "idle", stopReason: "end_turn" }); + respond(id, {}); + } else { + send({ id, error: { code: -32601, message: "Method not found" } }); + } +} +`; + +test( + "An agent can publish a theme with comment markers inside CSS strings", + WEB, + async ({ t3, app, screen }) => { + const project = await t3.project("demo"); + const script = NodePath.join(project, "theme-acp.mjs"); + const settingsPath = NodePath.join(T3_HOME, "userdata/settings.json"); + const originalSettings = await NodeFSP.readFile(settingsPath, "utf8"); + const settings = JSON.parse(originalSettings); + await NodeFSP.writeFile(script, ACP); + settings.defaultRuntimeMode = "full-access"; + settings.providerInstances["theme-agent"] = { + driver: "acpRegistry", + displayName: "Theme Agent", + enabled: true, + config: { source: "local", commandPath: process.execPath, commandArgs: [script] }, + }; + try { + await NodeFSP.writeFile(settingsPath, JSON.stringify(settings)); + const { cli } = makeState(T3_HOME); + let threadId: string | undefined; + let replyText = ""; + for (let attempt = 0; attempt < 8 && threadId === undefined; attempt++) { + const started = await runPromise( + cli( + [ + "thread", + "start", + project, + "Publish the Literal CSS theme.", + "--title", + "Publish theme", + "--provider", + "theme-agent", + "--model", + "default", + "--wait", + "--json", + ], + [0, 1], + ), + ); + if (!started.stdout.includes("threadId")) continue; + const result = JSON.parse(started.stdout) as { + threadId: string; + status: string; + reply: string | null; + }; + // Base reaches the tool and gets its CSS refusal; anything else is a broken setup. + if ( + result.status !== "completed" || + (result.reply !== PUBLISHED && result.reply !== REFUSED) + ) { + throw new Error( + `Theme turn did not reach the theme tool: ${started.stdout} ${started.stderr}`, + ); + } + threadId = result.threadId; + replyText = result.reply; + } + if (threadId === undefined) throw new Error("Could not start the theme publish turn."); + + await t3.open({ threadId }); + const reply = screen.getByText(replyText, { exact: true }); + await reply.waitFor({ timeout: 60_000 }); + try { + await expect(reply).toHaveText(PUBLISHED); + } finally { + await app.screenshot("theme-publish-reply"); + } + } finally { + await NodeFSP.writeFile(settingsPath, originalSettings); + } + }, +); From f653767d337641f76a660b0730b0b483fefe1c8a Mon Sep 17 00:00:00 2001 From: Soroush Baraouf Date: Thu, 19 Nov 2026 11:48:23 -0500 Subject: [PATCH 2/4] fix(shared): theme CSS saves with escaped quotes and quoted comment markers themeCssLoadsRemoteFiles removed /* ... */ comments with a regex before it found strings, and its string pattern ended a string at an escaped quote. So a /* inside a string, or a \" in one, put later string text such as @import in view of the check, and valid theme CSS was refused on save. Comments, strings and url() are now read in one left-to-right pass, as CSS reads them. In a string a backslash escapes a hex code point (with a line break after it), a line break, or any other character, matched one way only. In the stylesheet check an unquoted url() is judged by its address like a quoted one, so a data: URL whose data holds /* or @import text is not refused. themeCssValueFetches keeps its behaviour: it refuses any value with a backslash before the pattern runs, and keeps unquoted url() text as before. Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/themeCss.ts | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/packages/shared/src/themeCss.ts b/packages/shared/src/themeCss.ts index db0e86a61bc4b..dde71f246c3c1 100644 --- a/packages/shared/src/themeCss.ts +++ b/packages/shared/src/themeCss.ts @@ -3,16 +3,24 @@ import { THEME_COLOR_ROLES } from "./themePalettes.ts"; const FETCHES_BY_STRING = /image-set\(|\bsrc\(/i; // Only CSS whitespace may come first. \s also matches U+00A0, which makes the address relative. const URL_NOT_LOCAL = /url\((?![ \t\n\f\r]*["']?(?:data:|#))/i; -// Read tokens left to right, as CSS does: a url( inside a string loads nothing, and a quote in an -// unquoted url( is not a string. A quoted url() that is not data: or #id keeps `url(` for the check. -const URL_OR_STRING = - /url\((?![ \t\n\f\r]*["'])[^)]*|url\([ \t\n\f\r]*("[^"\n\r\f]*"|'[^'\n\r\f]*')|"[^"\n\r\f]*"|'[^'\n\r\f]*'/gi; +// Read tokens left to right, as CSS does: a url( or /* inside a string loads nothing, and a quote in +// an unquoted url( is not a string. A quoted url() that is not data: or #id keeps `url(` for the check. +const ESCAPE = String.raw`\\(?:(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{1,5}(?![0-9a-fA-F]))(?:\r\n|[\n\r\f])?|\r\n|[^0-9a-fA-F])`; +const STRING = String.raw`"(?:${ESCAPE}|[^"\\\n\r\f])*"|'(?:${ESCAPE}|[^'\\\n\r\f])*'`; +const URL_OR_STRING = String.raw`url\((?![ \t\n\f\r]*["'])([^)]*)|url\([ \t\n\f\r]*(${STRING})|${STRING}`; +const VALUE_TOKENS = new RegExp(URL_OR_STRING, "gi"); +const STYLESHEET_TOKENS = new RegExp(String.raw`\/\*[\s\S]*?\*\/|${URL_OR_STRING}`, "gi"); -/** The code with its strings removed, keeping `url(` where a quoted url() can load a file. */ -function withoutStrings(code: string): string { - return code.replace(URL_OR_STRING, (token, urlString: string | undefined) => { - if (urlString !== undefined) return /^["'](?:data:|#)/i.test(urlString) ? "" : "url("; - return token.startsWith('"') || token.startsWith("'") ? "" : token; +/** + * The code with its strings removed, keeping `url(` where a quoted url() can load a file. A + * stylesheet also loses its comments, and an unquoted url() there is judged by its address too. + */ +function withoutStrings(code: string, stylesheet: boolean): string { + const tokens = stylesheet ? STYLESHEET_TOKENS : VALUE_TOKENS; + return code.replace(tokens, (token, address?: string, urlString?: string) => { + const url = stylesheet ? (address ?? urlString) : urlString; + if (url !== undefined) return /^[ \t\n\f\r]*["']?(?:data:|#)/i.test(url) ? "" : "url("; + return /^["'/]/.test(token) ? "" : token; }); } @@ -26,12 +34,12 @@ function fetchesOutsideStrings(code: string): boolean { * so every value that still has a backslash is refused. */ export function themeCssValueFetches(value: string): boolean { - return value.includes("\\") || fetchesOutsideStrings(withoutStrings(value)); + return value.includes("\\") || fetchesOutsideStrings(withoutStrings(value, false)); } /** A text check for early feedback. CSS escapes can dodge it; the client check is the guard. */ export function themeCssLoadsRemoteFiles(css: string): boolean { - const code = withoutStrings(css.replace(/\/\*[\s\S]*?\*\//g, "")); + const code = withoutStrings(css, true); return /@import/i.test(code) || fetchesOutsideStrings(code); } From 4a89fa1df888cdef77bfaf860f67279483591261 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 17:14:42 +0000 Subject: [PATCH 3/4] test(shared): keep theme CSS cases that catch a regression Drop the browser scenario: the shared unit cases fail on main for the same reasons and run in milliseconds. Drop cases that repeat another row. Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/themeCss.test.ts | 6 - ...shes-css-with-quoted-comment-marker.e2e.ts | 170 ------------------ 2 files changed, 176 deletions(-) delete mode 100644 scripts/scenarios/theme-publishes-css-with-quoted-comment-marker.e2e.ts diff --git a/packages/shared/src/themeCss.test.ts b/packages/shared/src/themeCss.test.ts index 14ed259be7c15..bd4884f2b0260 100644 --- a/packages/shared/src/themeCss.test.ts +++ b/packages/shared/src/themeCss.test.ts @@ -33,7 +33,6 @@ describe("themeCssLoadsRemoteFiles", () => { it.each([ ['[data-chat-header]::after { content: "@import"; }', false], ['.a::after { content: "say \\"@import\\""; }', false], - [".a::after { content: 'a\\' @import'; }", false], ['.a::after { content: "a\\\r\n@import"; }', false], ['.a::after { content: "\\22\r\n@import"; }', false], ['.a::after { content: "/*"; } /* note */ .b::after { content: "@import"; }', false], @@ -42,13 +41,8 @@ describe("themeCssLoadsRemoteFiles", () => { ".a { background-image: url(data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22%3E%3C!--/*@import*/--%3E%3C/svg%3E); }", false, ], - [ - ".a { background-image: url(data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22%3E%3C!--/*@import\\2e */--%3E%3C/svg%3E); }", - false, - ], ['@import "x.css";', true], ['.a::after { content: "\\\\"; } @import "x.css";', true], - ['.a { background: url("https://example.invalid/x.png"); }', true], [".a { background: url(https://example.invalid/x.png); }", true], ])("%s", (css, loads) => { expect(themeCssLoadsRemoteFiles(css)).toBe(loads); diff --git a/scripts/scenarios/theme-publishes-css-with-quoted-comment-marker.e2e.ts b/scripts/scenarios/theme-publishes-css-with-quoted-comment-marker.e2e.ts deleted file mode 100644 index 5e769a4f6510f..0000000000000 --- a/scripts/scenarios/theme-publishes-css-with-quoted-comment-marker.e2e.ts +++ /dev/null @@ -1,170 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off -- The scenario stages a local ACP executable. -import * as NodeFSP from "node:fs/promises"; -import * as NodePath from "node:path"; - -import { expect } from "e2e"; - -import { T3_HOME } from "../e2e.config.ts"; -import { makeState, runPromise, test, WEB } from "./t3.ts"; - -const THEME = { - name: "Literal CSS", - appearance: "dark", - canvas: "#1a1b26", - accent: "#7aa2f7", - css: '[data-chat-header]::before { content: "/*"; } /* note */ [data-chat-header]::after { content: "@import"; }', -}; -const PUBLISHED = "Published Literal CSS."; -const REFUSED = - 'Theme not published: Theme "literal-css" has CSS that loads files. Remove @import, image-set(), and url() that is not data: or #id.'; -const ACP = ` -import { request as post } from "node:http"; -import { createInterface } from "node:readline"; - -const sessionId = "theme-publish-scenario"; -const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n"); -const respond = (id, result) => send({ id, result }); -const update = (update) => send({ method: "session/update", params: { sessionId, update } }); -let mcp = { endpoint: process.env.T3_ACP_MCP_ENDPOINT, authorization: process.env.T3_ACP_MCP_AUTHORIZATION }; -let mcpSession; -async function request(message) { - const body = await new Promise((resolve, reject) => { - const req = post(mcp.endpoint, { - method: "POST", - headers: { - "content-type": "application/json", - accept: "application/json, text/event-stream", - authorization: mcp.authorization, - ...(mcpSession ? { "mcp-session-id": mcpSession } : {}), - }, - }, (response) => { - mcpSession = response.headers["mcp-session-id"] ?? mcpSession; - let body = ""; - response.setEncoding("utf8"); - response.on("data", (chunk) => { body += chunk; }); - response.on("end", () => resolve(body)); - response.on("error", reject); - }); - req.on("error", reject); - req.end(JSON.stringify({ jsonrpc: "2.0", ...message })); - }); - if (message.id === undefined) return; - const payload = body.split("\\n").find((line) => line.startsWith("data: "))?.slice(6) ?? body; - const { result, error } = JSON.parse(payload); - if (error) throw new Error(JSON.stringify(error)); - return result; -} -async function setTheme() { - await request({ id: 1, method: "initialize", params: { - protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "theme-agent", version: "1" }, - } }); - await request({ method: "notifications/initialized" }); - const result = await request({ id: 2, method: "tools/call", params: { - name: "t3_theme_set", arguments: { themeId: "literal-css", theme: ${JSON.stringify(THEME)} }, - } }); - const { published, themeId } = result.structuredContent ?? {}; - if (result.isError !== true && published === true && themeId === "literal-css") { - return ${JSON.stringify(PUBLISHED)}; - } - const text = result.content.map(({ text }) => text).join(" "); - return "Theme not published: " + (text.startsWith("{") ? JSON.parse(text).message : text); -} -for await (const line of createInterface({ input: process.stdin })) { - const { id, method, params } = JSON.parse(line); - if (id === undefined) continue; - if (method === "initialize") { - respond(id, { protocolVersion: 2, info: { name: "theme-agent", version: "1.0.0" } }); - } else if (method === "session/new") { - const env = params.mcpServers?.find((server) => server.name === "t3-code")?.env ?? []; - const value = (name) => env.find((entry) => entry.name === name)?.value; - mcp = { - endpoint: value("T3_ACP_MCP_ENDPOINT") ?? mcp.endpoint, - authorization: value("T3_ACP_MCP_AUTHORIZATION") ?? mcp.authorization, - }; - respond(id, { sessionId }); - } else if (method === "session/prompt") { - const text = await setTheme().catch((error) => "Theme tool failed: " + error.message); - update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text } }); - update({ sessionUpdate: "state_update", state: "idle", stopReason: "end_turn" }); - respond(id, {}); - } else { - send({ id, error: { code: -32601, message: "Method not found" } }); - } -} -`; - -test( - "An agent can publish a theme with comment markers inside CSS strings", - WEB, - async ({ t3, app, screen }) => { - const project = await t3.project("demo"); - const script = NodePath.join(project, "theme-acp.mjs"); - const settingsPath = NodePath.join(T3_HOME, "userdata/settings.json"); - const originalSettings = await NodeFSP.readFile(settingsPath, "utf8"); - const settings = JSON.parse(originalSettings); - await NodeFSP.writeFile(script, ACP); - settings.defaultRuntimeMode = "full-access"; - settings.providerInstances["theme-agent"] = { - driver: "acpRegistry", - displayName: "Theme Agent", - enabled: true, - config: { source: "local", commandPath: process.execPath, commandArgs: [script] }, - }; - try { - await NodeFSP.writeFile(settingsPath, JSON.stringify(settings)); - const { cli } = makeState(T3_HOME); - let threadId: string | undefined; - let replyText = ""; - for (let attempt = 0; attempt < 8 && threadId === undefined; attempt++) { - const started = await runPromise( - cli( - [ - "thread", - "start", - project, - "Publish the Literal CSS theme.", - "--title", - "Publish theme", - "--provider", - "theme-agent", - "--model", - "default", - "--wait", - "--json", - ], - [0, 1], - ), - ); - if (!started.stdout.includes("threadId")) continue; - const result = JSON.parse(started.stdout) as { - threadId: string; - status: string; - reply: string | null; - }; - // Base reaches the tool and gets its CSS refusal; anything else is a broken setup. - if ( - result.status !== "completed" || - (result.reply !== PUBLISHED && result.reply !== REFUSED) - ) { - throw new Error( - `Theme turn did not reach the theme tool: ${started.stdout} ${started.stderr}`, - ); - } - threadId = result.threadId; - replyText = result.reply; - } - if (threadId === undefined) throw new Error("Could not start the theme publish turn."); - - await t3.open({ threadId }); - const reply = screen.getByText(replyText, { exact: true }); - await reply.waitFor({ timeout: 60_000 }); - try { - await expect(reply).toHaveText(PUBLISHED); - } finally { - await app.screenshot("theme-publish-reply"); - } - } finally { - await NodeFSP.writeFile(settingsPath, originalSettings); - } - }, -); From a79f1fa95e4f90fcdb837bc6659b87687fc2dcc7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 17:23:28 +0000 Subject: [PATCH 4/4] fix(shared): an escaped quote outside a string does not start one A run of escaped quotes made each quote scan the rest of the theme CSS, which blocked a publish for seconds, and a pair of them could hide an @import between them. Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/themeCss.test.ts | 1 + packages/shared/src/themeCss.ts | 7 ++++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/shared/src/themeCss.test.ts b/packages/shared/src/themeCss.test.ts index bd4884f2b0260..9aecb1c1f7931 100644 --- a/packages/shared/src/themeCss.test.ts +++ b/packages/shared/src/themeCss.test.ts @@ -42,6 +42,7 @@ describe("themeCssLoadsRemoteFiles", () => { false, ], ['@import "x.css";', true], + ['.a\\" {} @import "x.css"; .b\\" {}', true], ['.a::after { content: "\\\\"; } @import "x.css";', true], [".a { background: url(https://example.invalid/x.png); }", true], ])("%s", (css, loads) => { diff --git a/packages/shared/src/themeCss.ts b/packages/shared/src/themeCss.ts index dde71f246c3c1..6fa05e57336c9 100644 --- a/packages/shared/src/themeCss.ts +++ b/packages/shared/src/themeCss.ts @@ -3,11 +3,12 @@ import { THEME_COLOR_ROLES } from "./themePalettes.ts"; const FETCHES_BY_STRING = /image-set\(|\bsrc\(/i; // Only CSS whitespace may come first. \s also matches U+00A0, which makes the address relative. const URL_NOT_LOCAL = /url\((?![ \t\n\f\r]*["']?(?:data:|#))/i; -// Read tokens left to right, as CSS does: a url( or /* inside a string loads nothing, and a quote in -// an unquoted url( is not a string. A quoted url() that is not data: or #id keeps `url(` for the check. +// Read tokens left to right, as CSS does: a url( or /* inside a string loads nothing, and a quote +// in an unquoted url( or after a backslash is not a string. A quoted url() that is not data: or #id +// keeps `url(` for the check. const ESCAPE = String.raw`\\(?:(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{1,5}(?![0-9a-fA-F]))(?:\r\n|[\n\r\f])?|\r\n|[^0-9a-fA-F])`; const STRING = String.raw`"(?:${ESCAPE}|[^"\\\n\r\f])*"|'(?:${ESCAPE}|[^'\\\n\r\f])*'`; -const URL_OR_STRING = String.raw`url\((?![ \t\n\f\r]*["'])([^)]*)|url\([ \t\n\f\r]*(${STRING})|${STRING}`; +const URL_OR_STRING = String.raw`url\((?![ \t\n\f\r]*["'])([^)]*)|url\([ \t\n\f\r]*(${STRING})|${STRING}|${ESCAPE}`; const VALUE_TOKENS = new RegExp(URL_OR_STRING, "gi"); const STYLESHEET_TOKENS = new RegExp(String.raw`\/\*[\s\S]*?\*\/|${URL_OR_STRING}`, "gi");