Skip to content

Commit 2fc75fb

Browse files
committed
Refactor CSS value parsing and improve URL handling
- Improve getValueOrUrl() to correctly filter protocol-relative URLs by normalizing them before validation. - Filter out falsey URL values when collecting references from declarations. - Update debug messages for clearer context ("url() in @value" -> "url() in declaration").
1 parent 7de4fa4 commit 2fc75fb

1 file changed

Lines changed: 11 additions & 12 deletions

File tree

src/index.ts

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ function detective(src, options: detective.Options = { url: false }) {
4747
if (options.url && isUrlNode(lastNode)) {
4848
file = getValueOrUrl(lastNode);
4949
if (file) {
50-
debug('found %s of %s', 'url() with import', file);
50+
debug('found %s of %s', 'url() in @value', file);
5151
}
5252
}
5353
}
@@ -61,26 +61,25 @@ function detective(src, options: detective.Options = { url: false }) {
6161
const { nodes } = postCssParseValue(decl.value);
6262
const files = nodes
6363
.filter((node) => isUrlNode(node))
64-
.map((node) => getValueOrUrl(node));
64+
.map((node) => getValueOrUrl(node))
65+
.filter((file): file is string => Boolean(file));
6566

66-
if (files) {
67-
for (const file of files) {
68-
debug('found %s of %s', 'url() with import', file);
69-
}
70-
71-
references = references.concat(files);
67+
for (const file of files) {
68+
debug('found %s of %s', 'url() in declaration', file);
7269
}
70+
71+
references = references.concat(files);
7372
});
7473

7574
return references;
7675
}
7776

78-
function getValueOrUrl(node: ChildNode) {
79-
// ['file']
77+
function getValueOrUrl(node: ChildNode): string | false {
8078
const ret = isUrlNode(node) ? getValue(node.nodes[0]) : getValue(node);
8179

82-
// is-url sometimes gets data: URLs wrong
83-
return !isUrl(ret) && !ret.startsWith('data:') && ret;
80+
// is-url-superb uses new URL() which doesn't accept protocol-relative URLs;
81+
// prepend http: so they get correctly identified and filtered out
82+
return !isUrl(ret.startsWith('//') ? `http:${ret}` : ret) && ret;
8483
}
8584

8685
function getValue(node: ChildNode) {

0 commit comments

Comments
 (0)