|
| 1 | +import type { Config, Plugin } from 'stylelint'; |
| 2 | +import type { PartialStyleLintConfig } from './types'; |
| 3 | + |
| 4 | +const formatValue = <T>(value: T | T[] | undefined): T[] => { |
| 5 | + if (!value) { |
| 6 | + return []; |
| 7 | + } |
| 8 | + if (Array.isArray(value)) { |
| 9 | + return value; |
| 10 | + } |
| 11 | + return [value]; |
| 12 | +}; |
| 13 | + |
| 14 | +const dedupeAdd = <T>(array: T[], values: T[], set: Set<T>) => { |
| 15 | + for (const item of values) { |
| 16 | + if (!set.has(item)) { |
| 17 | + set.add(item); |
| 18 | + array.push(item); |
| 19 | + } |
| 20 | + } |
| 21 | +}; |
| 22 | + |
| 23 | +export const defineStylelintConfig = ( |
| 24 | + configs: PartialStyleLintConfig[], |
| 25 | +): Config => { |
| 26 | + const finalPlugins: (Plugin | string)[] = []; |
| 27 | + const finalExtends: string[] = []; |
| 28 | + const finalIgnoreFiles: string[] = []; |
| 29 | + const finalRules: Config['rules'] = {}; |
| 30 | + |
| 31 | + // use set to deduplicate |
| 32 | + const pluginSet = new Set<Plugin | string>(); |
| 33 | + const extendsSet = new Set<string>(); |
| 34 | + const ignoreFilesSet = new Set<string>(); |
| 35 | + |
| 36 | + for (const config of configs) { |
| 37 | + const plugins = formatValue(config.plugins); |
| 38 | + dedupeAdd(finalPlugins, plugins, pluginSet); |
| 39 | + |
| 40 | + const extendsValue = formatValue(config.extends); |
| 41 | + dedupeAdd(finalExtends, extendsValue, extendsSet); |
| 42 | + |
| 43 | + const ignoreFiles = formatValue(config.ignoreFiles); |
| 44 | + dedupeAdd(finalIgnoreFiles, ignoreFiles, ignoreFilesSet); |
| 45 | + |
| 46 | + const rules = config.rules; |
| 47 | + if (rules) { |
| 48 | + Object.assign(finalRules, rules); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return { |
| 53 | + plugins: finalPlugins, |
| 54 | + extends: finalExtends, |
| 55 | + rules: finalRules, |
| 56 | + ignoreFiles: finalIgnoreFiles, |
| 57 | + }; |
| 58 | +}; |
0 commit comments