1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407 |
- "use strict";
- const
- path = require("node:path"),
- eslintScope = require("eslint-scope"),
- evk = require("eslint-visitor-keys"),
- espree = require("espree"),
- merge = require("lodash.merge"),
- pkg = require("../../package.json"),
- {
- Legacy: {
- ConfigOps,
- ConfigValidator,
- environments: BuiltInEnvironments
- }
- } = require("@eslint/eslintrc/universal"),
- Traverser = require("../shared/traverser"),
- { SourceCode } = require("../languages/js/source-code"),
- applyDisableDirectives = require("./apply-disable-directives"),
- { ConfigCommentParser } = require("@eslint/plugin-kit"),
- NodeEventGenerator = require("./node-event-generator"),
- createReportTranslator = require("./report-translator"),
- Rules = require("./rules"),
- createEmitter = require("./safe-emitter"),
- SourceCodeFixer = require("./source-code-fixer"),
- timing = require("./timing"),
- ruleReplacements = require("../../conf/replacements.json");
- const { getRuleFromConfig } = require("../config/flat-config-helpers");
- const { FlatConfigArray } = require("../config/flat-config-array");
- const { startTime, endTime } = require("../shared/stats");
- const { RuleValidator } = require("../config/rule-validator");
- const { assertIsRuleSeverity } = require("../config/flat-config-schema");
- const { normalizeSeverityToString } = require("../shared/severity");
- const { deepMergeArrays } = require("../shared/deep-merge-arrays");
- const jslang = require("../languages/js");
- const { activeFlags, inactiveFlags } = require("../shared/flags");
- const debug = require("debug")("eslint:linter");
- const MAX_AUTOFIX_PASSES = 10;
- const DEFAULT_PARSER_NAME = "espree";
- const DEFAULT_ECMA_VERSION = 5;
- const commentParser = new ConfigCommentParser();
- const DEFAULT_ERROR_LOC = { start: { line: 1, column: 0 }, end: { line: 1, column: 1 } };
- const parserSymbol = Symbol.for("eslint.RuleTester.parser");
- const { LATEST_ECMA_VERSION } = require("../../conf/ecma-version");
- const { VFile } = require("./vfile");
- const { ParserService } = require("../services/parser-service");
- const { FileContext } = require("./file-context");
- const { ProcessorService } = require("../services/processor-service");
- const STEP_KIND_VISIT = 1;
- const STEP_KIND_CALL = 2;
- function isEspree(parser) {
- return !!(parser === espree || parser[parserSymbol] === espree);
- }
- function addDeclaredGlobals(globalScope, configGlobals, { exportedVariables, enabledGlobals }) {
-
- for (const id of new Set([...Object.keys(configGlobals), ...Object.keys(enabledGlobals)])) {
-
- const configValue = configGlobals[id] === void 0 ? void 0 : ConfigOps.normalizeConfigGlobal(configGlobals[id]);
- const commentValue = enabledGlobals[id] && enabledGlobals[id].value;
- const value = commentValue || configValue;
- const sourceComments = enabledGlobals[id] && enabledGlobals[id].comments;
- if (value === "off") {
- continue;
- }
- let variable = globalScope.set.get(id);
- if (!variable) {
- variable = new eslintScope.Variable(id, globalScope);
- globalScope.variables.push(variable);
- globalScope.set.set(id, variable);
- }
- variable.eslintImplicitGlobalSetting = configValue;
- variable.eslintExplicitGlobal = sourceComments !== void 0;
- variable.eslintExplicitGlobalComments = sourceComments;
- variable.writeable = (value === "writable");
- }
-
- Object.keys(exportedVariables).forEach(name => {
- const variable = globalScope.set.get(name);
- if (variable) {
- variable.eslintUsed = true;
- variable.eslintExported = true;
- }
- });
-
- globalScope.through = globalScope.through.filter(reference => {
- const name = reference.identifier.name;
- const variable = globalScope.set.get(name);
- if (variable) {
-
- reference.resolved = variable;
- variable.references.push(reference);
- return false;
- }
- return true;
- });
- }
- function createMissingRuleMessage(ruleId) {
- return Object.hasOwn(ruleReplacements.rules, ruleId)
- ? `Rule '${ruleId}' was removed and replaced by: ${ruleReplacements.rules[ruleId].join(", ")}`
- : `Definition for rule '${ruleId}' was not found.`;
- }
- function updateLocationInformation({ line, column, endLine, endColumn }, language) {
- const columnOffset = language.columnStart === 1 ? 0 : 1;
- const lineOffset = language.lineStart === 1 ? 0 : 1;
-
- const finalEndLine = endLine === void 0 ? endLine : endLine + lineOffset;
- const finalEndColumn = endColumn === void 0 ? endColumn : endColumn + columnOffset;
- return {
- line: line + lineOffset,
- column: column + columnOffset,
- endLine: finalEndLine,
- endColumn: finalEndColumn
- };
- }
- function createLintingProblem(options) {
- const {
- ruleId = null,
- loc = DEFAULT_ERROR_LOC,
- message = createMissingRuleMessage(options.ruleId),
- severity = 2,
-
- language = {
- columnStart: 0,
- lineStart: 1
- }
- } = options;
- return {
- ruleId,
- message,
- ...updateLocationInformation({
- line: loc.start.line,
- column: loc.start.column,
- endLine: loc.end.line,
- endColumn: loc.end.column
- }, language),
- severity,
- nodeType: null
- };
- }
- function createDisableDirectives({ type, value, justification, node }, ruleMapper, language, sourceCode) {
- const ruleIds = Object.keys(commentParser.parseListConfig(value));
- const directiveRules = ruleIds.length ? ruleIds : [null];
- const result = {
- directives: [],
- directiveProblems: []
- };
- const parentDirective = { node, value, ruleIds };
- for (const ruleId of directiveRules) {
- const loc = sourceCode.getLoc(node);
-
- if (ruleId === null || !!ruleMapper(ruleId)) {
- if (type === "disable-next-line") {
- const { line, column } = updateLocationInformation(
- loc.end,
- language
- );
- result.directives.push({
- parentDirective,
- type,
- line,
- column,
- ruleId,
- justification
- });
- } else {
- const { line, column } = updateLocationInformation(
- loc.start,
- language
- );
- result.directives.push({
- parentDirective,
- type,
- line,
- column,
- ruleId,
- justification
- });
- }
- } else {
- result.directiveProblems.push(createLintingProblem({ ruleId, loc, language }));
- }
- }
- return result;
- }
- function getDirectiveComments(sourceCode, ruleMapper, warnInlineConfig, config) {
- const configuredRules = {};
- const enabledGlobals = Object.create(null);
- const exportedVariables = {};
- const problems = [];
- const disableDirectives = [];
- const validator = new ConfigValidator({
- builtInRules: Rules
- });
- sourceCode.getInlineConfigNodes().filter(token => token.type !== "Shebang").forEach(comment => {
- const directive = commentParser.parseDirective(comment.value);
- if (!directive) {
- return;
- }
- const {
- label,
- value,
- justification: justificationPart
- } = directive;
- const lineCommentSupported = /^eslint-disable-(next-)?line$/u.test(label);
- if (comment.type === "Line" && !lineCommentSupported) {
- return;
- }
- const loc = sourceCode.getLoc(comment);
- if (warnInlineConfig) {
- const kind = comment.type === "Block" ? `/*${label}*/` : `//${label}`;
- problems.push(createLintingProblem({
- ruleId: null,
- message: `'${kind}' has no effect because you have 'noInlineConfig' setting in ${warnInlineConfig}.`,
- loc,
- severity: 1
- }));
- return;
- }
- if (label === "eslint-disable-line" && loc.start.line !== loc.end.line) {
- const message = `${label} comment should not span multiple lines.`;
- problems.push(createLintingProblem({
- ruleId: null,
- message,
- loc
- }));
- return;
- }
- switch (label) {
- case "eslint-disable":
- case "eslint-enable":
- case "eslint-disable-next-line":
- case "eslint-disable-line": {
- const directiveType = label.slice("eslint-".length);
- const { directives, directiveProblems } = createDisableDirectives({
- type: directiveType,
- value,
- justification: justificationPart,
- node: comment
- }, ruleMapper, jslang, sourceCode);
- disableDirectives.push(...directives);
- problems.push(...directiveProblems);
- break;
- }
- case "exported":
- Object.assign(exportedVariables, commentParser.parseListConfig(value));
- break;
- case "globals":
- case "global":
- for (const [id, idSetting] of Object.entries(commentParser.parseStringConfig(value))) {
- let normalizedValue;
- try {
- normalizedValue = ConfigOps.normalizeConfigGlobal(idSetting);
- } catch (err) {
- problems.push(createLintingProblem({
- ruleId: null,
- loc,
- message: err.message
- }));
- continue;
- }
- if (enabledGlobals[id]) {
- enabledGlobals[id].comments.push(comment);
- enabledGlobals[id].value = normalizedValue;
- } else {
- enabledGlobals[id] = {
- comments: [comment],
- value: normalizedValue
- };
- }
- }
- break;
- case "eslint": {
- const parseResult = commentParser.parseJSONLikeConfig(value);
- if (parseResult.ok) {
- Object.keys(parseResult.config).forEach(name => {
- const rule = ruleMapper(name);
- const ruleValue = parseResult.config[name];
- if (!rule) {
- problems.push(createLintingProblem({ ruleId: name, loc }));
- return;
- }
- if (Object.hasOwn(configuredRules, name)) {
- problems.push(createLintingProblem({
- message: `Rule "${name}" is already configured by another configuration comment in the preceding code. This configuration is ignored.`,
- loc
- }));
- return;
- }
- let ruleOptions = Array.isArray(ruleValue) ? ruleValue : [ruleValue];
-
- if (
-
- ruleOptions.length === 1 &&
-
- config.rules && Object.hasOwn(config.rules, name)
- ) {
-
- ruleOptions = [
- ruleOptions[0],
- ...Array.isArray(config.rules[name]) ? config.rules[name].slice(1) : []
- ];
- }
- try {
- validator.validateRuleOptions(rule, name, ruleOptions);
- } catch (err) {
-
- if (err.code === "ESLINT_INVALID_RULE_OPTIONS_SCHEMA") {
- throw err;
- }
- problems.push(createLintingProblem({
- ruleId: name,
- message: err.message,
- loc
- }));
-
- return;
- }
- configuredRules[name] = ruleOptions;
- });
- } else {
- const problem = createLintingProblem({
- ruleId: null,
- loc,
- message: parseResult.error.message
- });
- problem.fatal = true;
- problems.push(problem);
- }
- break;
- }
-
- }
- });
- return {
- configuredRules,
- enabledGlobals,
- exportedVariables,
- problems,
- disableDirectives
- };
- }
- function getDirectiveCommentsForFlatConfig(sourceCode, ruleMapper, language) {
- const disableDirectives = [];
- const problems = [];
- if (sourceCode.getDisableDirectives) {
- const {
- directives: directivesSources,
- problems: directivesProblems
- } = sourceCode.getDisableDirectives();
- problems.push(...directivesProblems.map(directiveProblem => createLintingProblem({
- ...directiveProblem,
- language
- })));
- directivesSources.forEach(directive => {
- const { directives, directiveProblems } = createDisableDirectives(directive, ruleMapper, language, sourceCode);
- disableDirectives.push(...directives);
- problems.push(...directiveProblems);
- });
- }
- return {
- problems,
- disableDirectives
- };
- }
- function normalizeEcmaVersion(parser, ecmaVersion) {
- if (isEspree(parser)) {
- if (ecmaVersion === "latest") {
- return espree.latestEcmaVersion;
- }
- }
-
- return ecmaVersion >= 2015 ? ecmaVersion - 2009 : ecmaVersion;
- }
- function normalizeEcmaVersionForLanguageOptions(ecmaVersion) {
- switch (ecmaVersion) {
- case 3:
- return 3;
-
- case 5:
- case void 0:
- return 5;
- default:
- if (typeof ecmaVersion === "number") {
- return ecmaVersion >= 2015 ? ecmaVersion : ecmaVersion + 2009;
- }
- }
-
- return LATEST_ECMA_VERSION;
- }
- const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)(?:\*\/|$)/gsu;
- function findEslintEnv(text) {
- let match, retv;
- eslintEnvPattern.lastIndex = 0;
- while ((match = eslintEnvPattern.exec(text)) !== null) {
- if (match[0].endsWith("*/")) {
- retv = Object.assign(
- retv || {},
- commentParser.parseListConfig(commentParser.parseDirective(match[0].slice(2, -2)).value)
- );
- }
- }
- return retv;
- }
- function normalizeFilename(filename) {
- const parts = filename.split(path.sep);
- const index = parts.lastIndexOf("<text>");
- return index === -1 ? filename : parts.slice(index).join(path.sep);
- }
- function normalizeVerifyOptions(providedOptions, config) {
- const linterOptions = config.linterOptions || config;
-
- const disableInlineConfig = linterOptions.noInlineConfig === true;
- const ignoreInlineConfig = providedOptions.allowInlineConfig === false;
- const configNameOfNoInlineConfig = config.configNameOfNoInlineConfig
- ? ` (${config.configNameOfNoInlineConfig})`
- : "";
- let reportUnusedDisableDirectives = providedOptions.reportUnusedDisableDirectives;
- if (typeof reportUnusedDisableDirectives === "boolean") {
- reportUnusedDisableDirectives = reportUnusedDisableDirectives ? "error" : "off";
- }
- if (typeof reportUnusedDisableDirectives !== "string") {
- if (typeof linterOptions.reportUnusedDisableDirectives === "boolean") {
- reportUnusedDisableDirectives = linterOptions.reportUnusedDisableDirectives ? "warn" : "off";
- } else {
- reportUnusedDisableDirectives = linterOptions.reportUnusedDisableDirectives === void 0 ? "off" : normalizeSeverityToString(linterOptions.reportUnusedDisableDirectives);
- }
- }
- let ruleFilter = providedOptions.ruleFilter;
- if (typeof ruleFilter !== "function") {
- ruleFilter = () => true;
- }
- return {
- filename: normalizeFilename(providedOptions.filename || "<input>"),
- allowInlineConfig: !ignoreInlineConfig,
- warnInlineConfig: disableInlineConfig && !ignoreInlineConfig
- ? `your config${configNameOfNoInlineConfig}`
- : null,
- reportUnusedDisableDirectives,
- disableFixes: Boolean(providedOptions.disableFixes),
- stats: providedOptions.stats,
- ruleFilter
- };
- }
- function resolveParserOptions(parser, providedOptions, enabledEnvironments) {
- const parserOptionsFromEnv = enabledEnvironments
- .filter(env => env.parserOptions)
- .reduce((parserOptions, env) => merge(parserOptions, env.parserOptions), {});
- const mergedParserOptions = merge(parserOptionsFromEnv, providedOptions || {});
- const isModule = mergedParserOptions.sourceType === "module";
- if (isModule) {
-
- mergedParserOptions.ecmaFeatures = Object.assign({}, mergedParserOptions.ecmaFeatures, { globalReturn: false });
- }
- mergedParserOptions.ecmaVersion = normalizeEcmaVersion(parser, mergedParserOptions.ecmaVersion);
- return mergedParserOptions;
- }
- function createLanguageOptions({ globals: configuredGlobals, parser, parserOptions }) {
- const {
- ecmaVersion,
- sourceType
- } = parserOptions;
- return {
- globals: configuredGlobals,
- ecmaVersion: normalizeEcmaVersionForLanguageOptions(ecmaVersion),
- sourceType,
- parser,
- parserOptions
- };
- }
- function resolveGlobals(providedGlobals, enabledEnvironments) {
- return Object.assign(
- Object.create(null),
- ...enabledEnvironments.filter(env => env.globals).map(env => env.globals),
- providedGlobals
- );
- }
- function storeTime(time, timeOpts, slots) {
- const { type, key } = timeOpts;
- if (!slots.times) {
- slots.times = { passes: [{}] };
- }
- const passIndex = slots.fixPasses;
- if (passIndex > slots.times.passes.length - 1) {
- slots.times.passes.push({});
- }
- if (key) {
- slots.times.passes[passIndex][type] ??= {};
- slots.times.passes[passIndex][type][key] ??= { total: 0 };
- slots.times.passes[passIndex][type][key].total += time;
- } else {
- slots.times.passes[passIndex][type] ??= { total: 0 };
- slots.times.passes[passIndex][type].total += time;
- }
- }
- function getRuleOptions(ruleConfig, defaultOptions) {
- if (Array.isArray(ruleConfig)) {
- return deepMergeArrays(defaultOptions, ruleConfig.slice(1));
- }
- return defaultOptions ?? [];
- }
- function analyzeScope(ast, languageOptions, visitorKeys) {
- const parserOptions = languageOptions.parserOptions;
- const ecmaFeatures = parserOptions.ecmaFeatures || {};
- const ecmaVersion = languageOptions.ecmaVersion || DEFAULT_ECMA_VERSION;
- return eslintScope.analyze(ast, {
- ignoreEval: true,
- nodejsScope: ecmaFeatures.globalReturn,
- impliedStrict: ecmaFeatures.impliedStrict,
- ecmaVersion: typeof ecmaVersion === "number" ? ecmaVersion : 6,
- sourceType: languageOptions.sourceType || "script",
- childVisitorKeys: visitorKeys || evk.KEYS,
- fallback: Traverser.getKeys
- });
- }
- function createRuleListeners(rule, ruleContext) {
- if (!rule || typeof rule !== "object" || typeof rule.create !== "function") {
- throw new TypeError(`Error while loading rule '${ruleContext.id}': Rule must be an object with a \`create\` method`);
- }
- try {
- return rule.create(ruleContext);
- } catch (ex) {
- ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`;
- throw ex;
- }
- }
- function runRules(
- sourceCode,
- configuredRules,
- ruleMapper,
- parserName,
- language,
- languageOptions,
- settings,
- filename,
- applyDefaultOptions,
- disableFixes,
- cwd,
- physicalFilename,
- ruleFilter,
- stats,
- slots
- ) {
- const emitter = createEmitter();
-
- const eventQueue = sourceCode.traverse();
-
- const sharedTraversalContext = new FileContext({
- cwd,
- filename,
- physicalFilename: physicalFilename || filename,
- sourceCode,
- parserOptions: {
- ...languageOptions.parserOptions
- },
- parserPath: parserName,
- languageOptions,
- settings
- });
- const lintingProblems = [];
- Object.keys(configuredRules).forEach(ruleId => {
- const severity = ConfigOps.getRuleSeverity(configuredRules[ruleId]);
-
- if (severity === 0) {
- return;
- }
- if (ruleFilter && !ruleFilter({ ruleId, severity })) {
- return;
- }
- const rule = ruleMapper(ruleId);
- if (!rule) {
- lintingProblems.push(createLintingProblem({ ruleId, language }));
- return;
- }
- const messageIds = rule.meta && rule.meta.messages;
- let reportTranslator = null;
- const ruleContext = Object.freeze(
- Object.assign(
- Object.create(sharedTraversalContext),
- {
- id: ruleId,
- options: getRuleOptions(configuredRules[ruleId], applyDefaultOptions ? rule.meta?.defaultOptions : void 0),
- report(...args) {
-
- if (reportTranslator === null) {
- reportTranslator = createReportTranslator({
- ruleId,
- severity,
- sourceCode,
- messageIds,
- disableFixes,
- language
- });
- }
- const problem = reportTranslator(...args);
- if (problem.fix && !(rule.meta && rule.meta.fixable)) {
- throw new Error("Fixable rules must set the `meta.fixable` property to \"code\" or \"whitespace\".");
- }
- if (problem.suggestions && !(rule.meta && rule.meta.hasSuggestions === true)) {
- if (rule.meta && rule.meta.docs && typeof rule.meta.docs.suggestion !== "undefined") {
-
- throw new Error("Rules with suggestions must set the `meta.hasSuggestions` property to `true`. `meta.docs.suggestion` is ignored by ESLint.");
- }
- throw new Error("Rules with suggestions must set the `meta.hasSuggestions` property to `true`.");
- }
- lintingProblems.push(problem);
- }
- }
- )
- );
- const ruleListenersReturn = (timing.enabled || stats)
- ? timing.time(ruleId, createRuleListeners, stats)(rule, ruleContext) : createRuleListeners(rule, ruleContext);
- const ruleListeners = stats ? ruleListenersReturn.result : ruleListenersReturn;
- if (stats) {
- storeTime(ruleListenersReturn.tdiff, { type: "rules", key: ruleId }, slots);
- }
-
- function addRuleErrorHandler(ruleListener) {
- return function ruleErrorHandler(...listenerArgs) {
- try {
- const ruleListenerReturn = ruleListener(...listenerArgs);
- const ruleListenerResult = stats ? ruleListenerReturn.result : ruleListenerReturn;
- if (stats) {
- storeTime(ruleListenerReturn.tdiff, { type: "rules", key: ruleId }, slots);
- }
- return ruleListenerResult;
- } catch (e) {
- e.ruleId = ruleId;
- throw e;
- }
- };
- }
- if (typeof ruleListeners === "undefined" || ruleListeners === null) {
- throw new Error(`The create() function for rule '${ruleId}' did not return an object.`);
- }
-
- Object.keys(ruleListeners).forEach(selector => {
- const ruleListener = (timing.enabled || stats)
- ? timing.time(ruleId, ruleListeners[selector], stats) : ruleListeners[selector];
- emitter.on(
- selector,
- addRuleErrorHandler(ruleListener)
- );
- });
- });
- const eventGenerator = new NodeEventGenerator(emitter, {
- visitorKeys: sourceCode.visitorKeys ?? language.visitorKeys,
- fallback: Traverser.getKeys,
- matchClass: language.matchesSelectorClass ?? (() => false),
- nodeTypeKey: language.nodeTypeKey
- });
- for (const step of eventQueue) {
- switch (step.kind) {
- case STEP_KIND_VISIT: {
- try {
- if (step.phase === 1) {
- eventGenerator.enterNode(step.target);
- } else {
- eventGenerator.leaveNode(step.target);
- }
- } catch (err) {
- err.currentNode = step.target;
- throw err;
- }
- break;
- }
- case STEP_KIND_CALL: {
- emitter.emit(step.target, ...step.args);
- break;
- }
- default:
- throw new Error(`Invalid traversal step found: "${step.type}".`);
- }
- }
- return lintingProblems;
- }
- function ensureText(textOrSourceCode) {
- if (typeof textOrSourceCode === "object") {
- const { hasBOM, text } = textOrSourceCode;
- const bom = hasBOM ? "\uFEFF" : "";
- return bom + text;
- }
- return String(textOrSourceCode);
- }
- function getEnv(slots, envId) {
- return (
- (slots.lastConfigArray && slots.lastConfigArray.pluginEnvironments.get(envId)) ||
- BuiltInEnvironments.get(envId) ||
- null
- );
- }
- function getRule(slots, ruleId) {
- return (
- (slots.lastConfigArray && slots.lastConfigArray.pluginRules.get(ruleId)) ||
- slots.ruleMap.get(ruleId)
- );
- }
- function normalizeCwd(cwd) {
- if (cwd) {
- return cwd;
- }
- if (typeof process === "object") {
- return process.cwd();
- }
-
-
- return undefined;
- }
- const internalSlotsMap = new WeakMap();
- function assertEslintrcConfig(linter) {
- const { configType } = internalSlotsMap.get(linter);
- if (configType === "flat") {
- throw new Error("This method cannot be used with flat config. Add your entries directly into the config array.");
- }
- }
- class Linter {
-
- constructor({ cwd, configType = "flat", flags = [] } = {}) {
- flags.forEach(flag => {
- if (inactiveFlags.has(flag)) {
- throw new Error(`The flag '${flag}' is inactive: ${inactiveFlags.get(flag)}`);
- }
- if (!activeFlags.has(flag)) {
- throw new Error(`Unknown flag '${flag}'.`);
- }
- });
- internalSlotsMap.set(this, {
- cwd: normalizeCwd(cwd),
- flags,
- lastConfigArray: null,
- lastSourceCode: null,
- lastSuppressedMessages: [],
- configType,
- parserMap: new Map([["espree", espree]]),
- ruleMap: new Rules()
- });
- this.version = pkg.version;
- }
-
- static get version() {
- return pkg.version;
- }
-
- hasFlag(flag) {
- return internalSlotsMap.get(this).flags.includes(flag);
- }
-
- #eslintrcVerifyWithoutProcessors(file, providedConfig, providedOptions) {
- const slots = internalSlotsMap.get(this);
- const config = providedConfig || {};
- const options = normalizeVerifyOptions(providedOptions, config);
-
- let parserName = DEFAULT_PARSER_NAME;
- let parser = espree;
- if (typeof config.parser === "object" && config.parser !== null) {
- parserName = config.parser.filePath;
- parser = config.parser.definition;
- } else if (typeof config.parser === "string") {
- if (!slots.parserMap.has(config.parser)) {
- return [{
- ruleId: null,
- fatal: true,
- severity: 2,
- message: `Configured parser '${config.parser}' was not found.`,
- line: 0,
- column: 0,
- nodeType: null
- }];
- }
- parserName = config.parser;
- parser = slots.parserMap.get(config.parser);
- }
-
- const envInFile = options.allowInlineConfig && !options.warnInlineConfig
- ? findEslintEnv(file.body)
- : {};
- const resolvedEnvConfig = Object.assign({ builtin: true }, config.env, envInFile);
- const enabledEnvs = Object.keys(resolvedEnvConfig)
- .filter(envName => resolvedEnvConfig[envName])
- .map(envName => getEnv(slots, envName))
- .filter(env => env);
- const parserOptions = resolveParserOptions(parser, config.parserOptions || {}, enabledEnvs);
- const configuredGlobals = resolveGlobals(config.globals || {}, enabledEnvs);
- const settings = config.settings || {};
- const languageOptions = createLanguageOptions({
- globals: config.globals,
- parser,
- parserOptions
- });
- if (!slots.lastSourceCode) {
- let t;
- if (options.stats) {
- t = startTime();
- }
- const parserService = new ParserService();
- const parseResult = parserService.parseSync(
- file,
- {
- language: jslang,
- languageOptions
- }
- );
- if (options.stats) {
- const time = endTime(t);
- const timeOpts = { type: "parse" };
- storeTime(time, timeOpts, slots);
- }
- if (!parseResult.ok) {
- return parseResult.errors;
- }
- slots.lastSourceCode = parseResult.sourceCode;
- } else {
-
- if (!slots.lastSourceCode.scopeManager) {
- slots.lastSourceCode = new SourceCode({
- text: slots.lastSourceCode.text,
- ast: slots.lastSourceCode.ast,
- hasBOM: slots.lastSourceCode.hasBOM,
- parserServices: slots.lastSourceCode.parserServices,
- visitorKeys: slots.lastSourceCode.visitorKeys,
- scopeManager: analyzeScope(slots.lastSourceCode.ast, languageOptions)
- });
- }
- }
- const sourceCode = slots.lastSourceCode;
- const commentDirectives = options.allowInlineConfig
- ? getDirectiveComments(sourceCode, ruleId => getRule(slots, ruleId), options.warnInlineConfig, config)
- : { configuredRules: {}, enabledGlobals: {}, exportedVariables: {}, problems: [], disableDirectives: [] };
- addDeclaredGlobals(
- sourceCode.scopeManager.scopes[0],
- configuredGlobals,
- { exportedVariables: commentDirectives.exportedVariables, enabledGlobals: commentDirectives.enabledGlobals }
- );
- const configuredRules = Object.assign({}, config.rules, commentDirectives.configuredRules);
- let lintingProblems;
- try {
- lintingProblems = runRules(
- sourceCode,
- configuredRules,
- ruleId => getRule(slots, ruleId),
- parserName,
- jslang,
- languageOptions,
- settings,
- options.filename,
- true,
- options.disableFixes,
- slots.cwd,
- providedOptions.physicalFilename,
- null,
- options.stats,
- slots
- );
- } catch (err) {
- err.message += `\nOccurred while linting ${options.filename}`;
- debug("An error occurred while traversing");
- debug("Filename:", options.filename);
- if (err.currentNode) {
- const { line } = sourceCode.getLoc(err.currentNode).start;
- debug("Line:", line);
- err.message += `:${line}`;
- }
- debug("Parser Options:", parserOptions);
- debug("Parser Path:", parserName);
- debug("Settings:", settings);
- if (err.ruleId) {
- err.message += `\nRule: "${err.ruleId}"`;
- }
- throw err;
- }
- return applyDisableDirectives({
- language: jslang,
- sourceCode,
- directives: commentDirectives.disableDirectives,
- disableFixes: options.disableFixes,
- problems: lintingProblems
- .concat(commentDirectives.problems)
- .sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column),
- reportUnusedDisableDirectives: options.reportUnusedDisableDirectives
- });
- }
-
- _verifyWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) {
- const slots = internalSlotsMap.get(this);
- const filename = normalizeFilename(providedOptions.filename || "<input>");
- let text;
-
- if (typeof textOrSourceCode === "string") {
- slots.lastSourceCode = null;
- text = textOrSourceCode;
- } else {
- slots.lastSourceCode = textOrSourceCode;
- text = textOrSourceCode.text;
- }
- const file = new VFile(filename, text, {
- physicalPath: providedOptions.physicalFilename
- });
- return this.#eslintrcVerifyWithoutProcessors(file, providedConfig, providedOptions);
- }
-
- verify(textOrSourceCode, config, filenameOrOptions) {
- debug("Verify");
- const { configType, cwd } = internalSlotsMap.get(this);
- const options = typeof filenameOrOptions === "string"
- ? { filename: filenameOrOptions }
- : filenameOrOptions || {};
- const configToUse = config ?? {};
- if (configType !== "eslintrc") {
-
- let configArray = configToUse;
- if (!Array.isArray(configToUse) || typeof configToUse.getConfig !== "function") {
- configArray = new FlatConfigArray(configToUse, { basePath: cwd });
- configArray.normalizeSync();
- }
- return this._distinguishSuppressedMessages(this._verifyWithFlatConfigArray(textOrSourceCode, configArray, options, true));
- }
- if (typeof configToUse.extractConfig === "function") {
- return this._distinguishSuppressedMessages(this._verifyWithConfigArray(textOrSourceCode, configToUse, options));
- }
-
-
- if (options.preprocess || options.postprocess) {
- return this._distinguishSuppressedMessages(this._verifyWithProcessor(textOrSourceCode, configToUse, options));
- }
- return this._distinguishSuppressedMessages(this._verifyWithoutProcessors(textOrSourceCode, configToUse, options));
- }
-
- _verifyWithFlatConfigArrayAndProcessor(textOrSourceCode, config, options, configForRecursive) {
- const slots = internalSlotsMap.get(this);
- const filename = options.filename || "<input>";
- const filenameToExpose = normalizeFilename(filename);
- const physicalFilename = options.physicalFilename || filenameToExpose;
- const text = ensureText(textOrSourceCode);
- const file = new VFile(filenameToExpose, text, {
- physicalPath: physicalFilename
- });
- const preprocess = options.preprocess || (rawText => [rawText]);
- const postprocess = options.postprocess || (messagesList => messagesList.flat());
- const processorService = new ProcessorService();
- const preprocessResult = processorService.preprocessSync(file, {
- processor: {
- preprocess,
- postprocess
- }
- });
- if (!preprocessResult.ok) {
- return preprocessResult.errors;
- }
- const filterCodeBlock =
- options.filterCodeBlock ||
- (blockFilename => blockFilename.endsWith(".js"));
- const originalExtname = path.extname(filename);
- const { files } = preprocessResult;
- const messageLists = files.map(block => {
- debug("A code block was found: %o", block.path || "(unnamed)");
-
- if (typeof block === "string") {
- return this._verifyWithFlatConfigArrayAndWithoutProcessors(block, config, options);
- }
-
- if (!filterCodeBlock(block.path, block.body)) {
- debug("This code block was skipped.");
- return [];
- }
-
- if (configForRecursive && (text !== block.rawBody || path.extname(block.path) !== originalExtname)) {
- debug("Resolving configuration again because the file content or extension was changed.");
- return this._verifyWithFlatConfigArray(
- block.rawBody,
- configForRecursive,
- { ...options, filename: block.path, physicalFilename: block.physicalPath }
- );
- }
- slots.lastSourceCode = null;
-
- return this.#flatVerifyWithoutProcessors(
- block,
- config,
- { ...options, filename: block.path, physicalFilename: block.physicalPath }
- );
- });
- return processorService.postprocessSync(file, messageLists, {
- processor: {
- preprocess,
- postprocess
- }
- });
- }
-
- #flatVerifyWithoutProcessors(file, providedConfig, providedOptions) {
- const slots = internalSlotsMap.get(this);
- const config = providedConfig || {};
- const { settings = {}, languageOptions } = config;
- const options = normalizeVerifyOptions(providedOptions, config);
- if (!slots.lastSourceCode) {
- let t;
- if (options.stats) {
- t = startTime();
- }
- const parserService = new ParserService();
- const parseResult = parserService.parseSync(
- file,
- config
- );
- if (options.stats) {
- const time = endTime(t);
- storeTime(time, { type: "parse" }, slots);
- }
- if (!parseResult.ok) {
- return parseResult.errors;
- }
- slots.lastSourceCode = parseResult.sourceCode;
- } else {
-
- if (slots.lastSourceCode.scopeManager === null) {
- slots.lastSourceCode = new SourceCode({
- text: slots.lastSourceCode.text,
- ast: slots.lastSourceCode.ast,
- hasBOM: slots.lastSourceCode.hasBOM,
- parserServices: slots.lastSourceCode.parserServices,
- visitorKeys: slots.lastSourceCode.visitorKeys,
- scopeManager: analyzeScope(slots.lastSourceCode.ast, languageOptions)
- });
- }
- }
- const sourceCode = slots.lastSourceCode;
-
- sourceCode.applyLanguageOptions?.(languageOptions);
- const mergedInlineConfig = {
- rules: {}
- };
- const inlineConfigProblems = [];
-
- if (options.allowInlineConfig) {
-
- if (options.warnInlineConfig) {
- if (sourceCode.getInlineConfigNodes) {
- sourceCode.getInlineConfigNodes().forEach(node => {
- const loc = sourceCode.getLoc(node);
- const range = sourceCode.getRange(node);
- inlineConfigProblems.push(createLintingProblem({
- ruleId: null,
- message: `'${sourceCode.text.slice(range[0], range[1])}' has no effect because you have 'noInlineConfig' setting in ${options.warnInlineConfig}.`,
- loc,
- severity: 1,
- language: config.language
- }));
- });
- }
- } else {
- const inlineConfigResult = sourceCode.applyInlineConfig?.();
- if (inlineConfigResult) {
- inlineConfigProblems.push(
- ...inlineConfigResult.problems
- .map(problem => createLintingProblem({ ...problem, language: config.language }))
- .map(problem => {
- problem.fatal = true;
- return problem;
- })
- );
-
- const ruleValidator = new RuleValidator();
- for (const { config: inlineConfig, loc } of inlineConfigResult.configs) {
- Object.keys(inlineConfig.rules).forEach(ruleId => {
- const rule = getRuleFromConfig(ruleId, config);
- const ruleValue = inlineConfig.rules[ruleId];
- if (!rule) {
- inlineConfigProblems.push(createLintingProblem({
- ruleId,
- loc,
- language: config.language
- }));
- return;
- }
- if (Object.hasOwn(mergedInlineConfig.rules, ruleId)) {
- inlineConfigProblems.push(createLintingProblem({
- message: `Rule "${ruleId}" is already configured by another configuration comment in the preceding code. This configuration is ignored.`,
- loc,
- language: config.language
- }));
- return;
- }
- try {
- let ruleOptions = Array.isArray(ruleValue) ? ruleValue : [ruleValue];
- assertIsRuleSeverity(ruleId, ruleOptions[0]);
-
- let shouldValidateOptions = true;
- if (
-
- ruleOptions.length === 1 &&
-
- config.rules && Object.hasOwn(config.rules, ruleId)
- ) {
-
- ruleOptions = [
- ruleOptions[0],
- ...config.rules[ruleId].slice(1)
- ];
-
- if (config.rules[ruleId][0] > 0) {
- shouldValidateOptions = false;
- }
- } else {
-
- const slicedOptions = ruleOptions.slice(1);
- const mergedOptions = deepMergeArrays(rule.meta?.defaultOptions, slicedOptions);
- if (mergedOptions.length) {
- ruleOptions = [ruleOptions[0], ...mergedOptions];
- }
- }
- if (shouldValidateOptions) {
- ruleValidator.validate({
- plugins: config.plugins,
- rules: {
- [ruleId]: ruleOptions
- }
- });
- }
- mergedInlineConfig.rules[ruleId] = ruleOptions;
- } catch (err) {
-
- if (err.code === "ESLINT_INVALID_RULE_OPTIONS_SCHEMA") {
- throw err;
- }
- let baseMessage = err.message.slice(
- err.message.startsWith("Key \"rules\":")
- ? err.message.indexOf(":", 12) + 1
- : err.message.indexOf(":") + 1
- ).trim();
- if (err.messageTemplate) {
- baseMessage += ` You passed "${ruleValue}".`;
- }
- inlineConfigProblems.push(createLintingProblem({
- ruleId,
- message: `Inline configuration for rule "${ruleId}" is invalid:\n\t${baseMessage}\n`,
- loc,
- language: config.language
- }));
- }
- });
- }
- }
- }
- }
- const commentDirectives = options.allowInlineConfig && !options.warnInlineConfig
- ? getDirectiveCommentsForFlatConfig(
- sourceCode,
- ruleId => getRuleFromConfig(ruleId, config),
- config.language
- )
- : { problems: [], disableDirectives: [] };
- const configuredRules = Object.assign({}, config.rules, mergedInlineConfig.rules);
- let lintingProblems;
- sourceCode.finalize?.();
- try {
- lintingProblems = runRules(
- sourceCode,
- configuredRules,
- ruleId => getRuleFromConfig(ruleId, config),
- void 0,
- config.language,
- languageOptions,
- settings,
- options.filename,
- false,
- options.disableFixes,
- slots.cwd,
- providedOptions.physicalFilename,
- options.ruleFilter,
- options.stats,
- slots
- );
- } catch (err) {
- err.message += `\nOccurred while linting ${options.filename}`;
- debug("An error occurred while traversing");
- debug("Filename:", options.filename);
- if (err.currentNode) {
- const { line } = sourceCode.getLoc(err.currentNode).start;
- debug("Line:", line);
- err.message += `:${line}`;
- }
- debug("Parser Options:", languageOptions.parserOptions);
-
- debug("Settings:", settings);
- if (err.ruleId) {
- err.message += `\nRule: "${err.ruleId}"`;
- }
- throw err;
- }
- return applyDisableDirectives({
- language: config.language,
- sourceCode,
- directives: commentDirectives.disableDirectives,
- disableFixes: options.disableFixes,
- problems: lintingProblems
- .concat(commentDirectives.problems)
- .concat(inlineConfigProblems)
- .sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column),
- reportUnusedDisableDirectives: options.reportUnusedDisableDirectives,
- ruleFilter: options.ruleFilter,
- configuredRules
- });
- }
-
- _verifyWithFlatConfigArrayAndWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) {
- const slots = internalSlotsMap.get(this);
- const filename = normalizeFilename(providedOptions.filename || "<input>");
- let text;
-
- if (typeof textOrSourceCode === "string") {
- slots.lastSourceCode = null;
- text = textOrSourceCode;
- } else {
- slots.lastSourceCode = textOrSourceCode;
- text = textOrSourceCode.text;
- }
- const file = new VFile(filename, text, {
- physicalPath: providedOptions.physicalFilename
- });
- return this.#flatVerifyWithoutProcessors(file, providedConfig, providedOptions);
- }
-
- _verifyWithConfigArray(textOrSourceCode, configArray, options) {
- debug("With ConfigArray: %s", options.filename);
-
- internalSlotsMap.get(this).lastConfigArray = configArray;
-
- const config = configArray.extractConfig(options.filename);
- const processor =
- config.processor &&
- configArray.pluginProcessors.get(config.processor);
-
- if (processor) {
- debug("Apply the processor: %o", config.processor);
- const { preprocess, postprocess, supportsAutofix } = processor;
- const disableFixes = options.disableFixes || !supportsAutofix;
- return this._verifyWithProcessor(
- textOrSourceCode,
- config,
- { ...options, disableFixes, postprocess, preprocess },
- configArray
- );
- }
- return this._verifyWithoutProcessors(textOrSourceCode, config, options);
- }
-
- _verifyWithFlatConfigArray(textOrSourceCode, configArray, options, firstCall = false) {
- debug("With flat config: %s", options.filename);
-
- const filename = options.filename || "__placeholder__.js";
-
- internalSlotsMap.get(this).lastConfigArray = configArray;
- const config = configArray.getConfig(filename);
- if (!config) {
- return [
- {
- ruleId: null,
- severity: 1,
- message: `No matching configuration found for ${filename}.`,
- line: 0,
- column: 0,
- nodeType: null
- }
- ];
- }
-
- if (config.processor) {
- debug("Apply the processor: %o", config.processor);
- const { preprocess, postprocess, supportsAutofix } = config.processor;
- const disableFixes = options.disableFixes || !supportsAutofix;
- return this._verifyWithFlatConfigArrayAndProcessor(
- textOrSourceCode,
- config,
- { ...options, filename, disableFixes, postprocess, preprocess },
- configArray
- );
- }
-
- if (firstCall && (options.preprocess || options.postprocess)) {
- return this._verifyWithFlatConfigArrayAndProcessor(textOrSourceCode, config, options);
- }
- return this._verifyWithFlatConfigArrayAndWithoutProcessors(textOrSourceCode, config, options);
- }
-
- _verifyWithProcessor(textOrSourceCode, config, options, configForRecursive) {
- const slots = internalSlotsMap.get(this);
- const filename = options.filename || "<input>";
- const filenameToExpose = normalizeFilename(filename);
- const physicalFilename = options.physicalFilename || filenameToExpose;
- const text = ensureText(textOrSourceCode);
- const file = new VFile(filenameToExpose, text, {
- physicalPath: physicalFilename
- });
- const preprocess = options.preprocess || (rawText => [rawText]);
- const postprocess = options.postprocess || (messagesList => messagesList.flat());
- const processorService = new ProcessorService();
- const preprocessResult = processorService.preprocessSync(file, {
- processor: {
- preprocess,
- postprocess
- }
- });
- if (!preprocessResult.ok) {
- return preprocessResult.errors;
- }
- const filterCodeBlock =
- options.filterCodeBlock ||
- (blockFilePath => blockFilePath.endsWith(".js"));
- const originalExtname = path.extname(filename);
- const { files } = preprocessResult;
- const messageLists = files.map(block => {
- debug("A code block was found: %o", block.path ?? "(unnamed)");
-
- if (typeof block === "string") {
- return this._verifyWithoutProcessors(block, config, options);
- }
-
- if (!filterCodeBlock(block.path, block.body)) {
- debug("This code block was skipped.");
- return [];
- }
-
- if (configForRecursive && (text !== block.rawBody || path.extname(block.path) !== originalExtname)) {
- debug("Resolving configuration again because the file content or extension was changed.");
- return this._verifyWithConfigArray(
- block.rawBody,
- configForRecursive,
- { ...options, filename: block.path, physicalFilename: block.physicalPath }
- );
- }
- slots.lastSourceCode = null;
-
- return this.#eslintrcVerifyWithoutProcessors(
- block,
- config,
- { ...options, filename: block.path, physicalFilename: block.physicalPath }
- );
- });
- return processorService.postprocessSync(file, messageLists, {
- processor: {
- preprocess,
- postprocess
- }
- });
- }
-
- _distinguishSuppressedMessages(problems) {
- const messages = [];
- const suppressedMessages = [];
- const slots = internalSlotsMap.get(this);
- for (const problem of problems) {
- if (problem.suppressions) {
- suppressedMessages.push(problem);
- } else {
- messages.push(problem);
- }
- }
- slots.lastSuppressedMessages = suppressedMessages;
- return messages;
- }
-
- getSourceCode() {
- return internalSlotsMap.get(this).lastSourceCode;
- }
-
- getTimes() {
- return internalSlotsMap.get(this).times ?? { passes: [] };
- }
-
- getFixPassCount() {
- return internalSlotsMap.get(this).fixPasses ?? 0;
- }
-
- getSuppressedMessages() {
- return internalSlotsMap.get(this).lastSuppressedMessages;
- }
-
- defineRule(ruleId, rule) {
- assertEslintrcConfig(this);
- internalSlotsMap.get(this).ruleMap.define(ruleId, rule);
- }
-
- defineRules(rulesToDefine) {
- assertEslintrcConfig(this);
- Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => {
- this.defineRule(ruleId, rulesToDefine[ruleId]);
- });
- }
-
- getRules() {
- assertEslintrcConfig(this);
- const { lastConfigArray, ruleMap } = internalSlotsMap.get(this);
- return new Map(function *() {
- yield* ruleMap;
- if (lastConfigArray) {
- yield* lastConfigArray.pluginRules;
- }
- }());
- }
-
- defineParser(parserId, parserModule) {
- assertEslintrcConfig(this);
- internalSlotsMap.get(this).parserMap.set(parserId, parserModule);
- }
-
- verifyAndFix(text, config, options) {
- let messages,
- fixedResult,
- fixed = false,
- passNumber = 0,
- currentText = text;
- const debugTextDescription = options && options.filename || `${text.slice(0, 10)}...`;
- const shouldFix = options && typeof options.fix !== "undefined" ? options.fix : true;
- const stats = options?.stats;
-
- const slots = internalSlotsMap.get(this);
-
- if (stats) {
- delete slots.times;
- slots.fixPasses = 0;
- }
- do {
- passNumber++;
- let tTotal;
- if (stats) {
- tTotal = startTime();
- }
- debug(`Linting code for ${debugTextDescription} (pass ${passNumber})`);
- messages = this.verify(currentText, config, options);
- debug(`Generating fixed text for ${debugTextDescription} (pass ${passNumber})`);
- let t;
- if (stats) {
- t = startTime();
- }
- fixedResult = SourceCodeFixer.applyFixes(currentText, messages, shouldFix);
- if (stats) {
- if (fixedResult.fixed) {
- const time = endTime(t);
- storeTime(time, { type: "fix" }, slots);
- slots.fixPasses++;
- } else {
- storeTime(0, { type: "fix" }, slots);
- }
- }
-
- if (messages.length === 1 && messages[0].fatal) {
- break;
- }
-
- fixed = fixed || fixedResult.fixed;
-
- currentText = fixedResult.output;
- if (stats) {
- tTotal = endTime(tTotal);
- const passIndex = slots.times.passes.length - 1;
- slots.times.passes[passIndex].total = tTotal;
- }
- } while (
- fixedResult.fixed &&
- passNumber < MAX_AUTOFIX_PASSES
- );
-
- if (fixedResult.fixed) {
- let tTotal;
- if (stats) {
- tTotal = startTime();
- }
- fixedResult.messages = this.verify(currentText, config, options);
- if (stats) {
- storeTime(0, { type: "fix" }, slots);
- slots.times.passes.at(-1).total = endTime(tTotal);
- }
- }
-
- fixedResult.fixed = fixed;
- fixedResult.output = currentText;
- return fixedResult;
- }
- }
- module.exports = {
- Linter,
-
- getLinterInternalSlots(instance) {
- return internalSlotsMap.get(instance);
- }
- };
|