1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
'use strict';
const minimatch = require('minimatch');
const path = require('path');
const paths = require('./paths');
const isUrlShouldBeIgnored = paths.isUrlShouldBeIgnored;
/**
* Returns whether the given asset matches the given pattern
* Allways returns true if the given pattern is empty
*
* @param {PostcssUrl~Asset} asset the processed asset
* @param {String|RegExp|Function} pattern A minimatch string,
* regular expression or function to test the asset
*
* @returns {Boolean}
*/
const matchesFilter = (asset, pattern) => {
const relativeToRoot = path.relative(process.cwd(), asset.absolutePath);
if (typeof pattern === 'string') {
pattern = minimatch.filter(pattern);
return pattern(relativeToRoot);
}
if (pattern instanceof RegExp) {
return pattern.test(relativeToRoot);
}
if (pattern instanceof Function) {
return pattern(asset);
}
return true;
};
/**
* Matching single option
*
* @param {PostcssUrl~Asset} asset
* @param {PostcssUrl~Options} option
* @returns {Boolean}
*/
const matchOption = (asset, option) => {
const matched = matchesFilter(asset, option.filter);
if (!matched) return false;
return typeof option.url === 'function' || !isUrlShouldBeIgnored(asset.url, option);
};
const isMultiOption = (option) =>
option.multi && typeof option.url === 'function';
/**
* Matching options by asset
*
* @param {PostcssUrl~Asset} asset
* @param {PostcssUrl~Options|PostcssUrl~Options[]} options
* @returns {PostcssUrl~Options|undefined}
*/
const matchOptions = (asset, options) => {
if (!options) return;
if (Array.isArray(options)) {
const optionIndex = options.findIndex((option) => matchOption(asset, option));
if (optionIndex < 0) return;
const matchedOption = options[optionIndex];
// if founded option is last
if (optionIndex === options.length - 1) return matchedOption;
const extendOptions = options
.slice(optionIndex + 1)
.filter((option) =>
(isMultiOption(matchedOption) || isMultiOption(option)) && matchOption(asset, option)
);
return extendOptions.length
? [matchedOption].concat(extendOptions)
: matchedOption;
}
if (matchOption(asset, options)) return options;
};
module.exports = matchOptions;