diff --git a/.eslintrc.yml b/.eslintrc.yml
index 136cae3..fee5d9f 100644
--- a/.eslintrc.yml
+++ b/.eslintrc.yml
@@ -1,6 +1,6 @@
extends: "eslint:recommended"
parserOptions:
- ecmaVersion: 6
+ ecmaVersion: 2018
env:
node: true
es6: true
@@ -32,4 +32,10 @@ rules:
no-spaced-func: "warn"
keyword-spacing: "error"
space-before-blocks: "error"
- no-console: "error"
\ No newline at end of file
+ no-console: "error"
+overrides:
+ - files: ["test/**/*.js"]
+ env:
+ mocha: true
+ rules:
+ func-names: "off"
diff --git a/lib/css-parser.js b/lib/css-parser.js
index fe06bc4..d28cbcc 100644
--- a/lib/css-parser.js
+++ b/lib/css-parser.js
@@ -1,6 +1,65 @@
-var embeddedRegexp = /^data:(.*?),(.*?)/;
-var commentRegexp = /\/\*([\s\S]*?)\*\//g;
-var urlsRegexp = /(?:@import\s+)?url\s*\(\s*(("(.*?)")|('(.*?)')|(.*?))\s*\)|(?:@import\s+)(("(.*?)")|('(.*?)')|(.*?))[\s;]/ig;
+var embeddedRegexp = /^data:/i;
+
+// The text is scanned in a single pass by one regexp which works as a tokenizer: at every position it matches either
+// a token with url (url(...), @import ...) or a token which has to be skipped as a whole (comment, string, identifier).
+// Every character class in a repetition excludes the characters which can follow it, so the regexp cannot backtrack
+// catastrophically (ReDoS).
+// Loops are unrolled, e.g. [^"\\]*(?:\\.[^"\\]*)* instead of (?:\\.|[^"\\])*, so a long run of plain characters is
+// consumed by a single character class: an alternation inside a loop costs a backtrack frame per character and
+// overflows the regexp stack on tokens of several megabytes (e.g. embedded fonts).
+// Unrolled parts must never match an empty string and must not nest a quantified class in a quantified group
+
+// As in CSS spec, unterminated comment ends at the end of input
+var comment = /\/\*[\s\S]*?(?:\*\/|$)/.source;
+// Terminated comment without lazy quantifier, safe to use inside repetition
+var closedComment = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//.source;
+// Optional and required whitespace with comments
+var whitespaceOpt = '\\s*(?:' + closedComment + '\\s*)*';
+var whitespaceReq = '(?:\\s+(?:' + closedComment + '\\s*)*|(?:' + closedComment + '\\s*)+)';
+
+// Escaped character; \r\n is a single newline (line continuation in a string). Alternatives are mutually exclusive,
+// so \ followed by \r\n can be matched in one way only
+var escaped = /\\(?:\r\n|[^\r]|\r(?!\n))/.source;
+// As in CSS spec, string cannot contain unescaped newline (\n, \r or \f)
+var doubleQuotedBody = '[^"\\\\\\n\\r\\f]*(?:' + escaped + '[^"\\\\\\n\\r\\f]*)*';
+var singleQuotedBody = '[^\'\\\\\\n\\r\\f]*(?:' + escaped + '[^\'\\\\\\n\\r\\f]*)*';
+var doubleQuoted = '"(' + doubleQuotedBody + ')"';
+var singleQuoted = '\'(' + singleQuotedBody + ')\'';
+// One or more characters or escapes without whitespace
+var unquotedChunk = '(?:[^"\'()\\\\\\s]+(?:' + escaped + '[^"\'()\\\\\\s]*)*|(?:' + escaped + '[^"\'()\\\\\\s]*)+)';
+// Neither the value nor its part after whitespace starts with a comment, and the value ends only at whitespace or
+// closing parenthesis: comments around the value are matched as whitespace only and have to be separated from it
+// by whitespace (/* glued to the value is a part of it). Otherwise comments could be matched in two ways and rescanned
+var unquoted = '((?!\\/\\*)' + unquotedChunk + '(?:\\s+(?!\\/\\*)' + unquotedChunk + ')*)(?=[\\s)])';
+
+var closedString = '"' + doubleQuotedBody + '"|\'' + singleQuotedBody + '\'';
+// As in CSS spec, unterminated string ends at newline or end of input
+var skippedString = '"' + doubleQuotedBody + '\\\\?(?:"|[\\n\\r\\f]|$)|\'' + singleQuotedBody + '\\\\?(?:\'|[\\n\\r\\f]|$)';
+// Identifier with escapes, so url is found only at the start of a name (not in my-url(...)) and escaped quotes
+// do not start a string
+var skippedIdentifier = '(?:[\\w\\u0080-\\uFFFF-]+(?:' + escaped + '[\\w\\u0080-\\uFFFF-]*)*|(?:' + escaped + '[\\w\\u0080-\\uFFFF-]*)+)';
+
+// Prelude of at-rule where url(...) is not a resource to load: @namespace url(...), @document url(...).
+// Skipped till ; or { which are not inside closed strings. Escapes are skipped as a whole, so escaped quote
+// does not start a string
+var skippedAtRule = '@(?:namespace|(?:-moz-)?document)(?![\\w-])[^;{"\'\\\\]*(?:(?:' + closedString + '|' + escaped + '|["\'])[^;{"\'\\\\]*)*';
+
+var urlsRegexp = new RegExp([
+ comment,
+ skippedAtRule,
+ // url("path"), url('path'), url(path), with optional comments around the path
+ 'url\\s*\\(' + whitespaceOpt + '(?:(?:' + doubleQuoted + '|' + singleQuoted + '|' + unquoted + ')' + whitespaceOpt + ')?\\)',
+ // Invalid url(...), e.g. unquoted with quotes inside: skipped till the closing parenthesis as in CSS spec.
+ // Parentheses inside closed strings and comments do not end it. Unterminated comment is skipped till the end of
+ // input here as well, otherwise the rest of the text would be rescanned for the end of comment from every url(/*
+ 'url\\s*\\([^)\\\\"\'/]*(?:(?:' + closedString + '|' + escaped + '|' + comment + '|["\'/])[^)\\\\"\'/]*)*\\)?',
+ // @import "path", @import 'path'
+ '@import' + whitespaceOpt + '(?:' + doubleQuoted + '|' + singleQuoted + ')',
+ // @import path; @ is excluded so the path cannot run over following @import rules and be rescanned from each of them
+ '@import' + whitespaceReq + '(?!url\\s*\\(|\\/\\*)([^\\s;@"\'()]+)(?=[\\s;]|$)',
+ skippedString,
+ skippedIdentifier
+].join('|'), 'ig');
function isEmbedded (src) {
return embeddedRegexp.test(src.trim());
@@ -8,15 +67,20 @@ function isEmbedded (src) {
function getUrls (text) {
var urls = [];
+ var found = Object.create(null);
var urlMatch, url;
- text = text.replace(commentRegexp, '');
+ if (typeof text !== 'string') {
+ throw new TypeError('css text must be a string, got ' + typeof text);
+ }
+ urlsRegexp.lastIndex = 0;
while ((urlMatch = urlsRegexp.exec(text))) {
- // Match 3, 5, 6 group if '[@import] url(path)', match 9, 11, 12 group if '@import path'
- url = urlMatch[3] || urlMatch[5] || urlMatch[6] || urlMatch[9] || urlMatch[11] || urlMatch[12];
+ // Groups 1-3 for url(...), 4-5 for @import "...", 6 for @import path
+ url = urlMatch[1] || urlMatch[2] || urlMatch[3] || urlMatch[4] || urlMatch[5] || urlMatch[6];
- if (url && !isEmbedded(url) && urls.indexOf(url) === -1) {
+ if (url && !isEmbedded(url) && !found[url]) {
+ found[url] = true;
urls.push(url);
}
}
diff --git a/package.json b/package.json
index f7b2133..7787d34 100644
--- a/package.json
+++ b/package.json
@@ -6,7 +6,7 @@
"main": "index.js",
"scripts": {
"test": "c8 --all --reporter=text --reporter=lcov mocha --recursive",
- "eslint": "eslint lib/** index.js"
+ "eslint": "eslint lib test index.js"
},
"keywords": [
"parser",
diff --git a/test/css-parser-test.js b/test/css-parser-test.js
index 2599f72..87094a9 100644
--- a/test/css-parser-test.js
+++ b/test/css-parser-test.js
@@ -1,8 +1,8 @@
var parseCssUrls = require('../index');
-var should = require('should');
+require('should');
-describe('Parse css urls', function(){
- it('should return array of entries from url(...), @import url(...) and @import ...', function(){
+describe('Parse css urls', function () {
+ it('should return array of entries from url(...), @import url(...) and @import ...', function () {
var text = '\
@import url("a.css"); \
@import url(\'b.css\') tv; \
@@ -30,7 +30,7 @@ describe('Parse css urls', function(){
urls.should.containEql('i.css');
});
- it('should exclude duplicated urls', function(){
+ it('should exclude duplicated urls', function () {
var text = '\
@import url("a.css"); \
@import a.css; \
@@ -42,7 +42,7 @@ describe('Parse css urls', function(){
urls.should.containEql('a.css');
});
- it('should ignore empty urls', function(){
+ it('should ignore empty urls', function () {
var text = 'div.image { background-image: url(""); } ';
var urls = parseCssUrls(text);
@@ -50,7 +50,7 @@ describe('Parse css urls', function(){
urls.should.have.length(0);
});
- it('should return empty array if no urls were found', function(){
+ it('should return empty array if no urls were found', function () {
var text = 'no css urls should be found in this text';
var urls = parseCssUrls(text);
@@ -69,63 +69,63 @@ describe('Parse css urls', function(){
urls2.should.be.instanceof(Array).and.have.lengthOf(1);
urls2.should.containEql('2.css');
- var text3 = ".image { background: url('3.css' ); } ";
+ var text3 = '.image { background: url(\'3.css\' ); } ';
var urls3 = parseCssUrls(text3);
urls3.should.be.instanceof(Array).and.have.lengthOf(1);
urls3.should.containEql('3.css');
});
- it('should handle urls with spaces inside quotes', function() {
+ it('should handle urls with spaces inside quotes', function () {
var text = '.image { background: url(" a.css"); } ';
var urls = parseCssUrls(text);
urls.should.be.instanceof(Array).and.have.lengthOf(1);
urls.should.containEql(' a.css');
});
- it('should handle urls without extension', function() {
+ it('should handle urls without extension', function () {
var text = '.image { background: url("image-without-ext"); } ';
var urls = parseCssUrls(text);
urls.should.be.instanceof(Array).and.have.lengthOf(1);
urls.should.containEql('image-without-ext');
});
- describe('quotes', function() {
- it('should find url without quotes', function() {
+ describe('quotes', function () {
+ it('should find url without quotes', function () {
var text = '.image { background: url(bg.jpg); } ';
var urls = parseCssUrls(text);
urls.should.be.instanceof(Array).and.have.lengthOf(1);
urls.should.containEql('bg.jpg');
});
- it('should find url containing single quotes inside double quotes', function() {
+ it('should find url containing single quotes inside double quotes', function () {
var text = '.image { background: url("bg\'1.jpg"); }';
var urls = parseCssUrls(text);
urls.should.be.instanceof(Array).and.have.lengthOf(1);
urls.should.containEql('bg\'1.jpg');
});
- it('should find url containing double quotes inside single quotes', function() {
+ it('should find url containing double quotes inside single quotes', function () {
var text = '.image { background: url(\'bg" 23\'); }';
var urls = parseCssUrls(text);
urls.should.be.instanceof(Array).and.have.lengthOf(1);
urls.should.containEql('bg" 23');
});
- it('should find import without quotes', function() {
+ it('should find import without quotes', function () {
var text = '@import new.css;';
var urls = parseCssUrls(text);
urls.should.be.instanceof(Array).and.have.lengthOf(1);
urls.should.containEql('new.css');
});
- it('should find import containing single quotes inside double quotes', function() {
+ it('should find import containing single quotes inside double quotes', function () {
var text = '@import "new\'11\'.css";';
var urls = parseCssUrls(text);
urls.should.be.instanceof(Array).and.have.lengthOf(1);
urls.should.containEql('new\'11\'.css');
});
- it('should find import containing double quotes inside single quotes', function() {
+ it('should find import containing double quotes inside single quotes', function () {
var text = '@import \'new" _2_".css\';';
var urls = parseCssUrls(text);
urls.should.be.instanceof(Array).and.have.lengthOf(1);
@@ -133,22 +133,22 @@ describe('Parse css urls', function(){
});
});
- describe('parentheses', function() {
- it('should handle parentheses inside url in filename', function() {
+ describe('parentheses', function () {
+ it('should handle parentheses inside url in filename', function () {
var text = '.image { background: url("test (2).png"); } ';
var urls = parseCssUrls(text);
urls.should.be.instanceof(Array).and.have.lengthOf(1);
urls.should.containEql('test (2).png');
});
- it('should handle parentheses inside url in extension', function() {
+ it('should handle parentheses inside url in extension', function () {
var text = '.image { background: url(\'test.png (2)\'); } ';
var urls = parseCssUrls(text);
urls.should.be.instanceof(Array).and.have.lengthOf(1);
urls.should.containEql('test.png (2)');
});
- it('should handle parentheses inside @import', function() {
+ it('should handle parentheses inside @import', function () {
var text = '@import "import)).css" ';
var urls = parseCssUrls(text);
urls.should.be.instanceof(Array).and.have.lengthOf(1);
@@ -156,8 +156,8 @@ describe('Parse css urls', function(){
});
});
- describe('comments', function() {
- it('should ignore comments and return empty array if there are only comments in text', function(){
+ describe('comments', function () {
+ it('should ignore comments and return empty array if there are only comments in text', function () {
var text = '\
/* @import url("a.css"); \
@import url("b.css"); \
@@ -170,7 +170,7 @@ describe('Parse css urls', function(){
urls.should.have.length(0);
});
- it('should ignore comments and return only urls from rules', function(){
+ it('should ignore comments and return only urls from rules', function () {
var text = '\
/* @import url("a.css"); */ \
@import url("b.css"); \
@@ -182,7 +182,7 @@ describe('Parse css urls', function(){
urls.should.containEql('b.css');
});
- it('should ignore comments because they may be tricky', function(){
+ it('should ignore comments because they may be tricky', function () {
var text = '\
/* @import hahahaha */\
@import url("a.css"); \
@@ -195,8 +195,8 @@ describe('Parse css urls', function(){
});
});
- describe('Data URI', function() {
- it('should ignore base64 encoded images', function(){
+ describe('Data URI', function () {
+ it('should ignore base64 encoded images', function () {
var text = '\
div.image { \
background-image: url(\'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAEFkb2JlIEltYWdlUmVhZHlxyWU8AAACXklEQVQ4T82TX0hTYRjGZ8Oryp2j5f5l/iHKdVOjZabzSm1MnNuB0sSI1BiNLqoLt93UVTejSJ1L19of0Qs1aNG6CELmhcacZRmZkIUWhUZBF92EFc/pe7/IdEbXffDy8j7P7zy8nPMdheK/Obn7Tur1Vl9/kaMnWSIFkrubQklDczS5tyXGO82kk6+z+gYFY1vhuuXzzJ7hgqYhuahxQN7VMiwbWuOyoT0hF564yzvNpJNPXF6VN742QJlb5X2kl8LYKQVR0hhFyfEBHHLFcTE6zTvNpJNPHPEsQPk7JFusdE+uDdhmC+NSdAp0qNO8NoB49nD2nwCzJ6WTbqLA0Yfio2FopQjGnrzHnfFFPHy+DK0jguJjYe4TJzI+I6AjpbOHsMPeC40tiCMX4ph78xnG9hG8/fAFNedvQ9MQ5D5xorkjI6CiI6VlgL4hgC013egamcbQ6EsoyjuRmFhAJ5tJJ584kfHrN2CC2tYHbb0fuRY/nr3+iHNdY1DbbsAbnMDswieIlm7uaxi3MYCtpK7vhar6Ciqdg/i68h3pF0uYnF3C1NwyVr79QIVzgPlXQdxfA/Lrr0N5+DIi92bwIL2I7VY/SpvDyK/rwfjMO0QST7lP3MZ3YHY/zmfJQrUPDvcIytpiEGqvQV3n5738dD/Tb3H/V4CH7sHqZ8xSmVz3NVJM1th65c3VXbJgCcg6R0jW2kO8qyw9XCdfI/XLQtnZURawafU2KnMKanP2n0qpDrpeqQ4453mZnPOC6Qzvqxrztxpb00qx0Jr5I2cxQcuqlNWef5SBeTpWxCt+AlBhYa97xG2bAAAAAElFTkSuQmCC\'); \
@@ -208,7 +208,7 @@ describe('Parse css urls', function(){
urls.should.have.length(0);
});
- it('should ignore base64 encoded fonts', function(){
+ it('should ignore base64 encoded fonts', function () {
var text = ' \
@font-face { \
font-family: \'icons\'; \
@@ -225,7 +225,7 @@ describe('Parse css urls', function(){
urls.should.have.length(0);
});
- it('should ignore utf-8 encoded data uri', function() {
+ it('should ignore utf-8 encoded data uri', function () {
var text = 'img.grayscale { \
filter: url("data:image/svg+xml;utf8,"); \
}';
@@ -234,13 +234,294 @@ describe('Parse css urls', function(){
urls.should.have.length(0);
});
- it('should ignore minimal data uri ("data:,")', function() {
+ it('should ignore minimal data uri ("data:,")', function () {
var text = 'img.grayscale { \
filter: url("data:,"); \
}';
var urls = parseCssUrls(text);
urls.should.be.instanceof(Array);
urls.should.have.length(0);
- })
+ });
+ });
+
+ describe('@import edge cases', function () {
+ it('should find quoted import at the end of input', function () {
+ parseCssUrls('@import "a.css"').should.eql(['a.css']);
+ parseCssUrls('@import \'b.css\'').should.eql(['b.css']);
+ });
+
+ it('should find unquoted import at the end of input', function () {
+ parseCssUrls('@import a.css').should.eql(['a.css']);
+ });
+
+ it('should find quoted import without whitespace after @import', function () {
+ parseCssUrls('@import"a.css";').should.eql(['a.css']);
+ });
+
+ it('should not include trailing characters after quoted import', function () {
+ parseCssUrls('@import "a.css"screen;').should.eql(['a.css']);
+ });
+
+ it('should find import with whitespace between url and parenthesis', function () {
+ parseCssUrls('@import url ("a.css");').should.eql(['a.css']);
+ parseCssUrls('@import URL (b.css);').should.eql(['b.css']);
+ });
+
+ it('should find import separated by comments', function () {
+ parseCssUrls('@import/**/url(a.css);').should.eql(['a.css']);
+ parseCssUrls('@import /* c */ "b.css";').should.eql(['b.css']);
+ parseCssUrls('@import /* c *//**/ c.css;').should.eql(['c.css']);
+ });
+
+ it('should not treat unterminated comment as import', function () {
+ parseCssUrls('@import /* a.css;').should.eql([]);
+ });
+ });
+
+ describe('url() edge cases', function () {
+ it('should ignore functions whose name only ends with url', function () {
+ parseCssUrls('.x { mask: my-url(a.png); b: myurl(b.png); }').should.eql([]);
+ });
+
+ it('should keep escaped parentheses in unquoted url', function () {
+ parseCssUrls('.x { background: url(a\\).png); }').should.eql(['a\\).png']);
+ });
+
+ it('should keep escaped quotes in quoted url', function () {
+ parseCssUrls('.x { background: url("a\\"b.png"); }').should.eql(['a\\"b.png']);
+ });
+
+ it('should not return url with unclosed quote', function () {
+ parseCssUrls('.a { background: url("a.png); } .b { background: url(b.png); }').should.eql(['b.png']);
+ });
+
+ it('should find url right after comment', function () {
+ parseCssUrls('.a{background:#fff/**/url(a.png)}').should.eql(['a.png']);
+ });
+
+ it('should not treat /* inside unquoted url as comment', function () {
+ parseCssUrls('.a{background:url(//cdn.com/img/*.png)} .b{background:url(b.png)}')
+ .should.eql(['//cdn.com/img/*.png', 'b.png']);
+ parseCssUrls('.a{background:url(x/*y*/z.png)}').should.eql(['x/*y*/z.png']);
+ });
+
+ it('should skip unquoted url with quotes inside as a whole', function () {
+ var text = '.a{background:url(data:image/svg+xml;utf8,)} .b{background:url(b.png)}';
+ parseCssUrls(text).should.eql(['b.png']);
+ parseCssUrls('.a{background:url(it\'s.png)} /* url(x.png) */').should.eql([]);
+ });
+
+ it('should ignore url inside strings and attribute selectors', function () {
+ parseCssUrls('.a{content:"see url(foo.png)"}').should.eql([]);
+ parseCssUrls('.sel[data-x=\'url(q.png)\']{color:red}').should.eql([]);
+ parseCssUrls('.a{content:"@import \\"a.css\\""}').should.eql([]);
+ });
+
+ it('should find multiple urls on one line', function () {
+ parseCssUrls('.x { background: url(a.png), url("b.png"); }').should.eql(['a.png', 'b.png']);
+ });
+ });
+
+ describe('comment-like sequences in strings', function () {
+ it('should not treat /* */ inside url string as comment', function () {
+ parseCssUrls('.x { background: url("x/*y*/z.png"); }').should.eql(['x/*y*/z.png']);
+ });
+
+ it('should not start comment from /* inside string', function () {
+ var text = '.a { content: "/*"; } .b { background: url(keep.png); } /* c */';
+ parseCssUrls(text).should.eql(['keep.png']);
+ });
+
+ it('should treat unterminated comment as comment till the end of input', function () {
+ parseCssUrls('.a { background: url(a.png); } /* .b { background: url(b.png); }').should.eql(['a.png']);
+ });
+
+ it('should not start string from escaped quote outside of string', function () {
+ var text = '.a\\\'b{color:red}/* url(x.png) */ .c{background:url(c.png)}';
+ parseCssUrls(text).should.eql(['c.png']);
+ parseCssUrls('.content-\\[\\\'\\\'\\]{}/* url(x.png) */.d{background:url(d.png)}').should.eql(['d.png']);
+ });
+
+ it('should end unterminated string at newline', function () {
+ parseCssUrls('.a { content: "/*\n} .b { background: url(b.png); } /* c */').should.eql(['b.png']);
+ });
+ });
+
+ it('should ignore data uri regardless of case', function () {
+ parseCssUrls('.x { background: url(DATA:image/png;base64,AAA); }').should.eql([]);
+ });
+
+ describe('comments inside url()', function () {
+ it('should skip comments around quoted url', function () {
+ parseCssUrls('.a{background:url("a.png" /* c */)}').should.be.eql(['a.png']);
+ parseCssUrls('.a{background:url(/* c */ \'a.png\')}').should.be.eql(['a.png']);
+ parseCssUrls('.a{background:url(/* c *//* d */"a.png"/* e */ /* f */)}').should.be.eql(['a.png']);
+ });
+
+ it('should skip comments separated by whitespace from unquoted url', function () {
+ parseCssUrls('.a{background:url( /* c */ a.png)}').should.be.eql(['a.png']);
+ parseCssUrls('.a{background:url(/* c */a.png /* d */)}').should.be.eql(['a.png']);
+ parseCssUrls('.a{background:url(a.png\n/* d */\n)}').should.be.eql(['a.png']);
+ });
+
+ it('should keep /* inside unquoted url', function () {
+ parseCssUrls('.a{background:url(http://example.com/*/a.png)}').should.be.eql(['http://example.com/*/a.png']);
+ });
+
+ it('should skip comments with closing parenthesis', function () {
+ parseCssUrls('.a{background:url("a.png" /* ) */)}').should.be.eql(['a.png']);
+ parseCssUrls('.a{background:url(/* (c) */ "a.png")}').should.be.eql(['a.png']);
+ });
+
+ it('should not find url in url() with comment only', function () {
+ parseCssUrls('.a{background:url(/* a.png */)} .b{background:url(b.png)}').should.be.eql(['b.png']);
+ });
+ });
+
+ describe('newlines', function () {
+ it('should handle escaped CRLF as line continuation in string', function () {
+ parseCssUrls('.a{content:"x\\\r\ny";background:url(a.png)}\r\n.b{background:url(b.png)}')
+ .should.be.eql(['a.png', 'b.png']);
+ parseCssUrls('.a{content:"foo\\\r\nbar url(x.png)"} .b{background:url(b.png)}').should.be.eql(['b.png']);
+ parseCssUrls('.a{content:\'foo\\\r\nbar url(x.png)\'} .b{background:url(b.png)}').should.be.eql(['b.png']);
+ });
+
+ it('should end unterminated string at \\r and \\f', function () {
+ parseCssUrls('.a{content:"unterminated\r.b{background:url(b.png)}').should.be.eql(['b.png']);
+ parseCssUrls('.a{content:\'unterminated\f.b{background:url(b.png)}').should.be.eql(['b.png']);
+ parseCssUrls('.a{content:"unterminated\r\n.b{background:url(b.png)}').should.be.eql(['b.png']);
+ });
+
+ it('should not find quoted url with unescaped newline', function () {
+ parseCssUrls('.a{background:url("a\r.png")} .b{background:url(b.png)}').should.be.eql(['b.png']);
+ });
+ });
+
+ describe('at-rules with url() which is not a resource', function () {
+ it('should not find url in @namespace', function () {
+ parseCssUrls('@namespace url(http://www.w3.org/1999/xhtml);').should.be.eql([]);
+ parseCssUrls('@NAMESPACE svg url("http://www.w3.org/2000/svg"); .a{background:url(a.png)}').should.be.eql(['a.png']);
+ parseCssUrls('@namespace "http://www.w3.org/1999/xhtml;url(x.png)"; .a{background:url(a.png)}').should.be.eql(['a.png']);
+ });
+
+ it('should not find url in @document prelude, but find urls in its rules', function () {
+ parseCssUrls('@document url(http://example.com/), url-prefix("http://example.com/a") { .a{background:url(a.png)} }')
+ .should.be.eql(['a.png']);
+ parseCssUrls('@-moz-document url(http://example.com/) { .a{background:url(a.png)} }').should.be.eql(['a.png']);
+ });
+
+ it('should find urls in at-rules with similar names', function () {
+ parseCssUrls('@namespaces url(a.png);').should.be.eql(['a.png']);
+ });
+ });
+
+ describe('input type', function () {
+ it('should throw TypeError if text is not a string', function () {
+ [undefined, null, 42, {}, Buffer.from('url(a.png)')].forEach(function (text) {
+ (function () { parseCssUrls(text); }).should.throw(TypeError);
+ });
+ });
+ });
+
+ describe('performance', function () {
+ // Inputs which made some version of the regexp polynomial, built from n repetitions
+ function buildInputs (n) {
+ return [
+ 'url(' + ' '.repeat(n),
+ 'url('.repeat(n),
+ 'url("' + 'a'.repeat(n),
+ 'url(' + 'a '.repeat(n),
+ '@import ' + ' '.repeat(n),
+ '/*' + ' '.repeat(n),
+ '"' + '\\"'.repeat(n),
+ '/*' + 'a/*'.repeat(n),
+ '"\\'.repeat(n),
+ 'url("'.repeat(n),
+ '@import "'.repeat(n),
+ '@import' + '/**/'.repeat(n),
+ '@import/*' + '*a'.repeat(n),
+ '@import ' + '/* */ '.repeat(n) + '(',
+ 'url' + ' '.repeat(n),
+ 'url(a' + ' a'.repeat(n) + '"',
+ '-'.repeat(n) + '\\',
+ '\''.repeat(n),
+ 'url(' + '"\''.repeat(n),
+ 'url(")'.repeat(n) + 'url(\')'.repeat(n),
+ '@import/**/@import*'.repeat(n) + ')',
+ '\\"' + '/**/@import'.repeat(n) + '@import)',
+ '*/' + '@import/*/**/url\u00e9'.repeat(n) + 'url(',
+ 'url(' + '/**/'.repeat(n) + '"',
+ 'url(' + '/**/ '.repeat(n) + '"',
+ 'url(a ' + '/**/ '.repeat(n) + '"',
+ 'url("a"' + '/**/'.repeat(n) + '"',
+ 'url(/*)'.repeat(n),
+ 'url(a /*)'.repeat(n),
+ 'url("a"/*)'.repeat(n),
+ 'url( /*\\)'.repeat(n),
+ 'url(a .' + '/**/'.repeat(n) + '"',
+ 'url( ' + '\\"/*'.repeat(n) + '\r\n',
+ 'url(a \\\r' + '/*url@import'.repeat(n) + '\\\r\nurl(a ',
+ 'url( ' + 'x.css/*\\\r\n'.repeat(n) + '\'',
+ 'url(' + 'a\\\r\n'.repeat(n) + '"',
+ 'url("' + '\\\r\n'.repeat(n),
+ '"' + '\\\r'.repeat(n) + '\n',
+ 'url(/* ) */'.repeat(n),
+ 'url("a"/*)'.repeat(n) + '*',
+ '@namespace"'.repeat(n),
+ '@document ' + '\\"'.repeat(n),
+ '@document \'\\"a'.repeat(n) + '\'',
+ '\\"@namespace\\\r\n@'.repeat(n) + '/',
+ '@namespace\';@document"{'.repeat(n),
+ '@namespace ' + '"a" '.repeat(n) + '\'',
+ Array.from({length: n}, function (_, i) { return 'url(' + i + '.png)'; }).join(' ')
+ ];
+ }
+
+ // Best of several runs, in milliseconds
+ function measure (input) {
+ var best = Infinity;
+ var i, start;
+ for (i = 0; i < 3; i++) {
+ start = process.hrtime.bigint();
+ parseCssUrls(input);
+ best = Math.min(best, Number(process.hrtime.bigint() - start) / 1e6);
+ }
+ return best;
+ }
+
+ it('should not backtrack catastrophically on malicious input', function () {
+ // Time is compared between two sizes instead of a fixed limit, so the result does not depend on the speed
+ // of the machine: for 4 times bigger input linear scan takes 4 times longer, quadratic one - 16 times
+ this.timeout(60000);
+ // Sizes are small enough for a quadratic scan to finish and fail the assertion instead of hanging
+ var small = buildInputs(5000);
+ var big = buildInputs(20000);
+
+ small.forEach(function (input, i) {
+ var smallTime = measure(input);
+ var bigTime = measure(big[i]);
+ bigTime.should.be.below(smallTime * 8 + 10, 'input #' + i + ' ' + JSON.stringify(input.slice(0, 40)));
+ });
+ });
+
+ it('should not overflow regexp stack on very long tokens', function () {
+ var long = 'A'.repeat(10000000);
+ var rest = ' .b{background:url(b.png)}';
+ var inputs = [
+ '.a{src:url(data:font/woff2;base64,' + long + ')}',
+ '.a{src:url("data:font/woff2;base64,' + long + '")}',
+ '.a{src:url(\'data:font/woff2;base64,' + long + '\')}',
+ '.a{content:"' + long + '"}',
+ '.a{content:"' + long + '\n',
+ long,
+ '@import' + ' '.repeat(10000000) + '"b.png";',
+ '@import' + ' '.repeat(10000000) + 'b.png;',
+ '.a{src:url(a"' + long + ')}'
+ ];
+ inputs.forEach(function (input) {
+ parseCssUrls(input + rest).should.be.eql(['b.png']);
+ });
+ });
});
});