From 7ae94c6241a6e6bb0a7f85b1deebe90b3223686e Mon Sep 17 00:00:00 2001 From: Joscha Feth Date: Mon, 16 Nov 2026 15:55:39 +0800 Subject: [PATCH 1/2] Upgrade postcss-values-parser to 8.x postcss-values-parser 8 is a rewrite on top of css-tree, which tokenizes unquoted url() as a single url token, so unquoted data: URLs no longer throw. - @import and @value params aren't plain values (media queries, layer(), 'name: value'), so only the relevant component is parsed, split with postcss's list.space() - url() is now a Word node; detect it via its source text - wrap values parser errors in MalformedCssError - add @types/css-tree, which the parser's type definitions need BREAKING CHANGE: requires Node.js >= 22.12.0 (postcss-values-parser 8 requires Node.js >= 22) Fixes #351 --- .github/workflows/node.js.yml | 2 +- package-lock.json | 42 ++++++++++--- package.json | 5 +- src/__tests__/issue.351.spec.ts | 50 +++++++++++++++ src/index.ts | 105 +++++++++++++++----------------- 5 files changed, 137 insertions(+), 67 deletions(-) create mode 100644 src/__tests__/issue.351.spec.ts diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml index b60116f..c1930f0 100644 --- a/.github/workflows/node.js.yml +++ b/.github/workflows/node.js.yml @@ -26,7 +26,7 @@ jobs: strategy: fail-fast: false matrix: - node-version: [20, 22, 24, 26] + node-version: [22, 24, 26] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/package-lock.json b/package-lock.json index f1de936..d2edf35 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,9 +10,10 @@ "license": "MIT", "dependencies": { "is-url-superb": "^4.0.0", - "postcss-values-parser": "^6.0.2" + "postcss-values-parser": "^8.0.0" }, "devDependencies": { + "@types/css-tree": "^3.2.0", "@types/node": "^20.19.43", "@vitest/coverage-v8": "^4.1.12", "lint-staged": "^17.6.0", @@ -23,7 +24,7 @@ "vitest": "^4.1.12" }, "engines": { - "node": ">=20.19.0 || >=22.12.0" + "node": ">=22.12.0" }, "peerDependencies": { "postcss": "^8.4.47" @@ -415,6 +416,13 @@ "assertion-error": "^2.0.1" } }, + "node_modules/@types/css-tree": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@types/css-tree/-/css-tree-3.2.0.tgz", + "integrity": "sha512-J5KXmk6BFIepOT7280FdFyNs4c5fh0Uee0otjKEvzchrRs38Ii9qminqc4ds0L19X8Zd/rT+brR9jkBthygjWw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/deep-eql": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", @@ -661,6 +669,19 @@ "dev": true, "license": "MIT" }, + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "license": "MIT", + "dependencies": { + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -1154,6 +1175,12 @@ "node": ">=10" } }, + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "license": "CC0-1.0" + }, "node_modules/minipass": { "version": "7.1.3", "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", @@ -1258,20 +1285,21 @@ } }, "node_modules/postcss-values-parser": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/postcss-values-parser/-/postcss-values-parser-6.0.2.tgz", - "integrity": "sha512-YLJpK0N1brcNJrs9WatuJFtHaV9q5aAOj+S4DI5S7jgHlRfm0PIbDCAFRYMQD5SHq7Fy6xsDhyutgS0QOAs0qw==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/postcss-values-parser/-/postcss-values-parser-8.0.0.tgz", + "integrity": "sha512-gPdtA/H7HgRThMg+QoXJ1EX0EX7zrVF7c3062jaHB4HijLg11QqC2hz9h/nUCZ6O/FljJ+qj2fUvAF2FWhVjFg==", "license": "MPL-2.0", "dependencies": { "color-name": "^1.1.4", + "css-tree": "^3.1.0", "is-url-superb": "^4.0.0", "quote-unquote": "^1.0.0" }, "engines": { - "node": ">=10" + "node": ">=22.0.0" }, "peerDependencies": { - "postcss": "^8.2.9" + "postcss": "^8.4.14" } }, "node_modules/prettier": { diff --git a/package.json b/package.json index 97b48b0..66c4697 100644 --- a/package.json +++ b/package.json @@ -25,16 +25,17 @@ "!**/__tests__/**" ], "engines": { - "node": ">=20.19.0 || >=22.12.0" + "node": ">=22.12.0" }, "peerDependencies": { "postcss": "^8.4.47" }, "dependencies": { "is-url-superb": "^4.0.0", - "postcss-values-parser": "^6.0.2" + "postcss-values-parser": "^8.0.0" }, "devDependencies": { + "@types/css-tree": "^3.2.0", "@types/node": "^20.19.43", "@vitest/coverage-v8": "^4.1.12", "lint-staged": "^17.6.0", diff --git a/src/__tests__/issue.351.spec.ts b/src/__tests__/issue.351.spec.ts new file mode 100644 index 0000000..207e0a5 --- /dev/null +++ b/src/__tests__/issue.351.spec.ts @@ -0,0 +1,50 @@ +import { describe, it, expect } from 'vitest'; +import detective from '../index.js'; + +describe('issue 351: unquoted data: URLs', () => { + describe('declaration ({ url: true })', () => { + const dataDecl = + '.icon { background: url(data:image/png;base64,iVBORw0KGgo=) no-repeat; }'; + const fileDecl = '.logo { background: url(logo.png); }'; + + it('ignores the data URL', () => { + expect(detective(dataDecl, { url: true })).toStrictEqual([]); + }); + + it('still finds the file URL next to a data URL', () => { + expect(detective(`${dataDecl} ${fileDecl}`, { url: true })).toStrictEqual( + ['logo.png'], + ); + }); + }); + + describe('@value (default)', () => { + const dataValue = '@value icon: url(data:image/png;base64,iVBORw0KGgo=);'; + const fileValue = '@value primary from "colors.css";'; + + it('ignores the data URL', () => { + expect(detective(dataValue)).toStrictEqual([]); + }); + + it('still finds the file import next to a data URL', () => { + expect(detective(`${dataValue}\n${fileValue}`)).toStrictEqual([ + 'colors.css', + ]); + }); + }); + + describe('@import (default)', () => { + const dataImport = '@import url(data:text/css;base64,LmF7fQ==);'; + const fileImport = '@import "b.css";'; + + it('ignores the data URL', () => { + expect(detective(dataImport)).toStrictEqual([]); + }); + + it('still finds the file import next to a data URL', () => { + expect(detective(`${dataImport}\n${fileImport}`)).toStrictEqual([ + 'b.css', + ]); + }); + }); +}); diff --git a/src/index.ts b/src/index.ts index 02bc7c1..bbb6b4d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,15 +1,11 @@ import { debuglog } from 'node:util'; import isUrl from 'is-url-superb'; -import { parse, type AtRule, type Root } from 'postcss'; +import { list, parse, type AtRule, type Root } from 'postcss'; import { parse as postCssParseValue, - type ChildNode, - type Func, - type Word, - type Numeric, - type Operator, - type Punctuation, - type Quoted, + Quoted, + Word, + type Node, } from 'postcss-values-parser'; const debug = debuglog('detective-postcss'); @@ -32,12 +28,15 @@ function detective(src: string, options: Options = {}): string[] { const references: string[] = []; root.walkAtRules((rule) => { - let file = null; + let file: string | undefined; if (isImportRule(rule)) { - const firstNode = postCssParseValue(rule.params).first; - if (firstNode) { - file = getValueOrUrl(firstNode); + // only the first component is the file; the rest are media queries, + // layer() or supports() conditions which aren't plain values + const [first] = list.space(rule.params); + const node = first ? parseValue(first)[0] : undefined; + if (node) { + file = getValueOrUrl(node); if (file) { debug('found %s of %s', '@import', file); } @@ -45,12 +44,14 @@ function detective(src: string, options: Options = {}): string[] { } if (isValueRule(rule)) { - const lastNode = postCssParseValue(rule.params).last; + // `@value name: value` isn't a plain value either, so only parse the + // last component (the source after `from`, or the value itself) + const parts = list.space(rule.params); + const last = parts.at(-1); + const lastNode = last ? parseValue(last).at(-1) : undefined; if (!lastNode) return; - const prevNode = lastNode.prev(); - - if (prevNode && isFrom(prevNode)) { + if (parts.at(-2) === 'from') { file = getValueOrUrl(lastNode); if (file) { debug('found %s of %s', '@value with import', file); @@ -71,8 +72,9 @@ function detective(src: string, options: Options = {}): string[] { if (!options.url) return references; root.walkDecls((decl) => { - const { nodes } = postCssParseValue(decl.value); - const files = nodes + if (!/url\(/i.test(decl.value)) return; + + const files = parseValue(decl.value) .filter((node) => isUrlNode(node)) .map((node) => getValueOrUrl(node)) .filter(Boolean) as string[]; @@ -87,48 +89,41 @@ function detective(src: string, options: Options = {}): string[] { return references; } -function getValueOrUrl(node: ChildNode): string | undefined { - const ret = isUrlNode(node) ? getUrlContent(node) : getValue(node); - - // is-url-superb uses new URL() which doesn't accept protocol-relative URLs; - // prepend http: so they get correctly identified and filtered out - return isUrl(ret.startsWith('//') ? `http:${ret}` : ret) ? undefined : ret; -} - -function getUrlContent(urlNode: Func): string { - const first = urlNode.nodes[0]; - - // Quoted: url('foo.css') or url("foo.css") - if (first && first.type === 'quoted') { - return first.contents; +function parseValue(value: string): Node[] { + try { + return postCssParseValue(value).nodes as unknown as Node[]; + } catch { + throw new MalformedCssError(); } - - // Unquoted: reconstruct the full string from all child nodes (handles - // absolute URLs like url(https://...) which parse as multiple tokens) - return urlNode.nodes - .filter((n) => isNodeWithValue(n)) - .map((n) => getValue(n)) - .join(''); } -function getValue(node: ChildNode) { - if (!isNodeWithValue(node)) { - throw new Error('Unexpectedly found a node without a value'); +function getValueOrUrl(node: Node): string | undefined { + // url() nodes are Word nodes holding the url's contents + let ret: string; + if (node instanceof Quoted) { + ret = node.contents; + } else if (node instanceof Word) { + ret = node.value; + } else { + return undefined; } - return node.type === 'quoted' ? node.contents : node.value; -} - -function isNodeWithValue( - node: ChildNode, -): node is Word | Numeric | Operator | Punctuation | Quoted { - return ['word', 'numeric', 'operator', 'punctuation', 'quoted'].includes( - node.type, - ); + // is-url-superb uses new URL() which doesn't accept protocol-relative URLs; + // prepend http: so they get correctly identified and filtered out + return isUrl(ret.startsWith('//') ? `http:${ret}` : ret) ? undefined : ret; } -function isUrlNode(node: ChildNode): node is Func { - return node.type === 'func' && node.name === 'url'; +/** + * postcss-values-parser turns url() into a Word node holding just the url's + * contents, so the only way to tell it apart from a plain word is to look at + * the source text it was parsed from. + */ +function isUrlNode(node: Node): boolean { + if (!(node instanceof Word) || !node.source?.input) return false; + + const { input, start, end } = node.source; + const sourceText = input.css.slice(start?.offset, end?.offset); + return /^url\(/i.test(sourceText); } function isValueRule(rule: AtRule) { @@ -139,10 +134,6 @@ function isImportRule(rule: AtRule) { return rule.name === 'import'; } -function isFrom(node: ChildNode): node is Word { - return node.type === 'word' && node.value === 'from'; -} - detective.MalformedCssError = MalformedCssError; export default detective; From 9a2fb41fab0e0331b866fa4cde81024eb5b401d3 Mon Sep 17 00:00:00 2001 From: Joscha Feth Date: Mon, 16 Nov 2026 15:59:14 +0800 Subject: [PATCH 2/2] refactor: consolidate @import and @value rule handling - Remove unused AtRule type import from postcss - Combine separate @import and @value rule walkers into single walkAtRules call using regex pattern - Unify logic for parsing rule params and extracting file references - Simplify node selection by using array indexing (first for @import, last for @value) - Remove isImportRule and isValueRule helper functions in favor of inline checks - Improve code clarity by consolidating duplicate reference detection logic - Reduce cyclomatic complexity while maintaining feature parity --- src/index.ts | 67 +++++++++++++++------------------------------------- 1 file changed, 19 insertions(+), 48 deletions(-) diff --git a/src/index.ts b/src/index.ts index bbb6b4d..99eeb76 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,6 @@ import { debuglog } from 'node:util'; import isUrl from 'is-url-superb'; -import { list, parse, type AtRule, type Root } from 'postcss'; +import { list, parse, type Root } from 'postcss'; import { parse as postCssParseValue, Quoted, @@ -27,46 +27,25 @@ function detective(src: string, options: Options = {}): string[] { const references: string[] = []; - root.walkAtRules((rule) => { - let file: string | undefined; - - if (isImportRule(rule)) { - // only the first component is the file; the rest are media queries, - // layer() or supports() conditions which aren't plain values - const [first] = list.space(rule.params); - const node = first ? parseValue(first)[0] : undefined; - if (node) { - file = getValueOrUrl(node); - if (file) { - debug('found %s of %s', '@import', file); - } - } + root.walkAtRules(/^(import|value)$/, (rule) => { + // at-rule params aren't plain values (media queries, layer(), + // `name: value`), so only parse the component holding the reference: + // the first one for @import, the last one for @value + const parts = list.space(rule.params); + const isImport = rule.name === 'import'; + const part = isImport ? parts[0] : parts.at(-1); + const nodes = part ? parseValue(part) : []; + const node = isImport ? nodes[0] : nodes.at(-1); + if (!node) return; + + const isReference = + isImport || parts.at(-2) === 'from' || (options.url && isUrlNode(node)); + const file = isReference ? getValueOrUrl(node) : undefined; + + if (file) { + debug('found %s of %s', `@${rule.name}`, file); + references.push(file); } - - if (isValueRule(rule)) { - // `@value name: value` isn't a plain value either, so only parse the - // last component (the source after `from`, or the value itself) - const parts = list.space(rule.params); - const last = parts.at(-1); - const lastNode = last ? parseValue(last).at(-1) : undefined; - if (!lastNode) return; - - if (parts.at(-2) === 'from') { - file = getValueOrUrl(lastNode); - if (file) { - debug('found %s of %s', '@value with import', file); - } - } - - if (options.url && isUrlNode(lastNode)) { - file = getValueOrUrl(lastNode); - if (file) { - debug('found %s of %s', 'url() in @value', file); - } - } - } - - if (file) references.push(file); }); if (!options.url) return references; @@ -126,14 +105,6 @@ function isUrlNode(node: Node): boolean { return /^url\(/i.test(sourceText); } -function isValueRule(rule: AtRule) { - return rule.name === 'value'; -} - -function isImportRule(rule: AtRule) { - return rule.name === 'import'; -} - detective.MalformedCssError = MalformedCssError; export default detective;