Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
extends: "eslint:recommended"
parserOptions:
ecmaVersion: 6
ecmaVersion: 2018
env:
node: true
es6: true
Expand Down Expand Up @@ -32,4 +32,10 @@ rules:
no-spaced-func: "warn"
keyword-spacing: "error"
space-before-blocks: "error"
no-console: "error"
no-console: "error"
overrides:
- files: ["test/**/*.js"]
env:
mocha: true
rules:
func-names: "off"
78 changes: 71 additions & 7 deletions lib/css-parser.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,86 @@
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());
}

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);
}
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading