/
utils.ts
449 lines (375 loc) · 11.5 KB
/
utils.ts
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
import { CLIEngine, Linter } from 'eslint';
import requireRelative from 'require-relative';
import { runInNewContext } from 'vm';
const pathToBlankFile = require.resolve('../blank.js');
const getsertCache = <T>(
cache: Map<string, T>,
key: string,
fn: () => T,
_name: string
): T => {
const cached = cache.get(key);
if (cached) {
// console.debug(`${_name}: hit`);
return cached;
}
// console.debug(`${_name}: miss`);
const fresh = fn();
cache.set(key, fresh);
return fresh;
};
const relativeRequire = (name: string): unknown =>
requireRelative(name, process.cwd()) as unknown;
relativeRequire.resolve = (name: string): string =>
requireRelative.resolve(name, process.cwd());
const compileConfigCodeCache = new Map<string, Linter.Config>();
const compileConfigCode = (fileCode: string): Linter.Config => {
return getsertCache(
compileConfigCodeCache,
fileCode,
() =>
(runInNewContext(fileCode, {
module: { exports: {} },
require: relativeRequire
}) ?? {}) as Linter.Config,
'compileConfigCode'
);
};
const createCliEngineCache = new Map<string, CLIEngine>();
const createCLIEngine = (config: Linter.Config): CLIEngine => {
const extraConfig: Linter.Config = {
parserOptions: {
...config.parserOptions,
project: require.resolve('../../tsconfig.fake.json'),
projectFolderIgnoreList: []
}
};
if (config.ignorePatterns) {
const patterns = Array.isArray(config.ignorePatterns)
? config.ignorePatterns
: [config.ignorePatterns];
extraConfig.ignorePatterns = patterns.filter(
pattern => typeof pattern !== 'string'
);
}
return getsertCache(
createCliEngineCache,
JSON.stringify(config),
() =>
new CLIEngine({
useEslintrc: false,
ignorePath: pathToBlankFile,
ignorePattern: ['!node_modules/*'],
cache: false,
envs: ['node'],
baseConfig: {
...config,
...extraConfig
}
}),
'createCLIEngine'
);
};
interface ConfigInfo {
deprecatedRules: CLIEngine.DeprecatedRuleUse[];
unknownRules: string[];
errors: ESLintError[];
}
const mergeConfigInfo = (a: ConfigInfo, b: ConfigInfo): ConfigInfo => ({
deprecatedRules: [...a.deprecatedRules, ...b.deprecatedRules],
unknownRules: [...a.unknownRules, ...b.unknownRules],
errors: [...a.errors, ...b.errors]
});
const ensureArray = <T>(v: T | T[] = []): T[] => (Array.isArray(v) ? v : [v]);
/**
* Merges two ESLint configs, favoring the second config over the first.
*
* Merging is done at the top level only, and based on explicit named properties,
* so any additional properties on either config will be lost.
*/
const mergeConfigs = (a: Linter.Config, b: Linter.Config): Linter.Config => ({
parser: b.parser ?? a.parser,
parserOptions: { ...a.parserOptions, ...b.parserOptions },
processor: b.processor ?? a.processor,
env: { ...a.env, ...b.env },
globals: { ...a.globals, ...b.globals },
plugins: [
...ensureArray(a.plugins),
...(Array.isArray(b.plugins) ? b.plugins : [])
],
extends: [...ensureArray(a.extends), ...ensureArray(b.extends)],
settings: { ...a.settings, ...b.settings },
overrides: [...ensureArray(a.overrides), ...ensureArray(b.overrides)],
rules: { ...a.rules, ...b.rules }
});
const extractRelevantConfigs = (config: Linter.Config): Linter.Config[] => [
{ ...config, overrides: [] },
...(config.overrides ?? [])
.map(override =>
extractRelevantConfigs(
mergeConfigs({ ...config, overrides: [], rules: {} }, override)
)
)
.reduce((prev, curr) => prev.concat(curr), [])
];
export enum ESLintErrorType {
FailedToLoadModule = 'FailedToLoadModule',
InvalidRuleConfig = 'InvalidRuleConfig',
ProcessorNotFound = 'ProcessorNotFound',
FailedToExtend = 'FailedToExtend',
InvalidConfig = 'InvalidConfig'
}
interface ESLintFailedToLoadModuleError {
type: ESLintErrorType.FailedToLoadModule;
kind: 'parser' | 'plugin' | string;
name: string;
path: string;
}
interface ESLintInvalidRuleConfigError {
type: ESLintErrorType.InvalidRuleConfig;
reason: string;
ruleId: string;
path: string;
}
interface ESLintProcessorNotFoundError {
type: ESLintErrorType.ProcessorNotFound;
name: string;
path?: never;
}
interface ESLintFailedToExtendError {
type: ESLintErrorType.FailedToExtend;
name: string;
path: string;
}
interface ESLintInvalidConfigError {
type: ESLintErrorType.InvalidConfig;
reason: string;
path?: never;
}
export type ESLintError =
| ESLintFailedToLoadModuleError
| ESLintInvalidRuleConfigError
| ESLintProcessorNotFoundError
| ESLintFailedToExtendError
| ESLintInvalidConfigError;
export type ESLintErrorParser = (error: Error) => ESLintError | null;
const tryParseAsFailedToLoadModuleError = (
error: Error
): ESLintFailedToLoadModuleError | null => {
// noinspection RegExpRedundantEscape
const [, kind, name, path] =
/Failed to load (.+) '(.*)' declared in 'BaseConfig((?:#overrides\[\d*?\])*)': Cannot find module '/isu.exec(
error.message.trim()
) ?? [];
return kind //
? { type: ESLintErrorType.FailedToLoadModule, kind, name, path }
: null;
};
const tryParseAsInvalidRuleConfigError = (
error: Error
): ESLintInvalidRuleConfigError | null => {
// noinspection RegExpRedundantEscape
const [, path, ruleId, reason] =
/BaseConfig((?:#overrides\[\d*?\])*):\s+Configuration for rule "(.+)" is invalid:(.+)/isu.exec(
error.message.trim()
) ?? [];
return ruleId //
? { type: ESLintErrorType.InvalidRuleConfig, reason, ruleId, path }
: null;
};
const tryParseAsFailedToExtendError = (
error: Error
): ESLintFailedToExtendError | null => {
// noinspection RegExpRedundantEscape
const [, name, path] =
/Failed to load config "(.+)" to extend from\.\nReferenced from: BaseConfig((?:#overrides\[\d*?\])*)/isu.exec(
error.message.trim()
) ?? [];
return name //
? { type: ESLintErrorType.FailedToExtend, name, path }
: null;
};
const tryToParseAsProcessorNotFoundError = (
error: Error
): ESLintProcessorNotFoundError | null => {
const [, name] =
/ESLint configuration of processor in '(?:.+)' is invalid: '(.+)' was not found\./isu.exec(
error.message.trim()
) ?? [];
return name //
? { type: ESLintErrorType.ProcessorNotFound, name }
: null;
};
const tryParseAsInvalidConfigError = (
error: Error
): ESLintInvalidConfigError | null => {
const [, reason] =
/ESLint configuration (?:.+) is invalid:(.+)/isu.exec(
error.message.trim()
) ?? [];
return reason //
? { type: ESLintErrorType.InvalidConfig, reason }
: null;
};
const errorParsers: ESLintErrorParser[] = [
tryParseAsFailedToLoadModuleError,
tryParseAsInvalidRuleConfigError,
tryToParseAsProcessorNotFoundError,
tryParseAsFailedToExtendError,
tryParseAsInvalidConfigError
];
const parseESLintError = (error: Error): ESLintError => {
for (const errorParser of errorParsers) {
const parsedError = errorParser(error);
if (parsedError) {
return parsedError;
}
}
error.message = `Unable to parse error from ESLint: ${error.message}`;
throw error;
};
const followErrorPathToConfig = (
config: Linter.Config,
error: ESLintError
): Linter.Config => {
if (!error.path || !config.overrides) {
return config;
}
const levels = error.path
.substr(1)
.split('#')
.map(p => parseInt(p.substring(p.indexOf('[') + 1, p.length - 1)));
/* istanbul ignore next */
return levels.reduce((conf, i) => conf.overrides?.[i] ?? {}, config);
};
const tryRemoveErrorPointFromConfig = (
config: Linter.Config,
error: ESLintError
): boolean => {
const configToDeleteFrom = followErrorPathToConfig(config, error);
if (error.type === ESLintErrorType.FailedToExtend) {
if (typeof configToDeleteFrom.extends === 'string') {
delete configToDeleteFrom.extends;
return true;
}
configToDeleteFrom.extends = ensureArray(configToDeleteFrom.extends).filter(
extend => extend !== error.name
);
return true;
}
if (error.type === ESLintErrorType.FailedToLoadModule) {
switch (error.kind) {
case 'plugin':
configToDeleteFrom.plugins = configToDeleteFrom.plugins?.filter(
plugin => plugin !== error.name
);
return true;
case 'parser':
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete configToDeleteFrom[error.kind];
return true;
// no default
}
}
if (error.type === ESLintErrorType.InvalidRuleConfig) {
const { ruleId } = error;
/* istanbul ignore if */
if (!(configToDeleteFrom.rules && ruleId in configToDeleteFrom.rules)) {
throw new Error('Cannot delete InvalidRuleConfig error - please report');
}
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete configToDeleteFrom.rules[ruleId];
return true;
}
return false;
};
const collectConfigInfoFromESLint = (config: Linter.Config): ConfigInfo => {
const theConfig = { rules: {}, ...config };
const errors: ESLintError[] = [];
let counter = 0;
do {
/* istanbul ignore if */
if ((counter += 1) > 20) {
throw new Error('inf. loop detected - please report');
}
try {
const results = createCLIEngine(theConfig).executeOnText(
'',
pathToBlankFile
);
return {
deprecatedRules: results.usedDeprecatedRules,
unknownRules: results.results[0].messages
.filter(({ message }) =>
/Definition for rule .+ was not found\./iu.test(message)
)
.map(({ ruleId }) => ruleId)
.filter((ruleId): ruleId is string => !!ruleId),
errors
};
} catch (error) {
const eslintError = parseESLintError(error as Error);
errors.push(eslintError);
if (tryRemoveErrorPointFromConfig(theConfig, eslintError)) {
continue;
}
return {
deprecatedRules: [],
unknownRules: [],
errors
};
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition,no-constant-condition
} while (true);
};
const collectConfigInfoCache = new Map<string, ConfigInfo>();
/**
* Collects information about the given `config` using ESLint.
*
* Info about any `overrides` the `config` might have will be collected and
* merged into the returned info object.
*/
const collectConfigInfo = (config: Linter.Config): ConfigInfo => {
return getsertCache(
collectConfigInfoCache,
JSON.stringify(config),
() => collectConfigInfoFromESLint(config),
'collectConfigInfo'
);
};
const getConfigInfoCache = new Map<string, ConfigInfo>();
export const getConfigInfo = (configText: string): ConfigInfo => {
return getsertCache(
getConfigInfoCache,
configText,
() => {
const config = compileConfigCode(configText);
const topLevelInfo = collectConfigInfo(config);
return (
extractRelevantConfigs(config)
.map(collectConfigInfo)
.map(info => ({
...info,
errors: info.errors.filter(
error =>
![
ESLintErrorType.InvalidRuleConfig,
ESLintErrorType.InvalidConfig
].includes(error.type)
)
}))
//
.concat(topLevelInfo)
.reduce(mergeConfigInfo)
);
},
'getConfigInfo'
);
};
export const tryGetConfigInfo = (configText: string): ConfigInfo | null => {
try {
return getConfigInfo(configText);
} catch {
return null;
}
};