code:
/**
 * @fileoverview A helper that translates context.report() calls from the rule API into generic problem objects
 * @author Teddy Katz
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const assert = require("assert");
const ruleFixer = require("./rule-fixer");
const interpolate = require("./interpolate");

//------------------------------------------------------------------------------
// Typedefs
//------------------------------------------------------------------------------

/** @typedef {import("../shared/types").LintMessage} LintMessage */

/**
 * An error message description
 * @typedef {Object} MessageDescriptor
 * @property {ASTNode} [node] The reported node
 * @property {Location} loc The location of the problem.
 * @property {string} message The problem message.
 * @property {Object} [data] Optional data to use to fill in placeholders in the
 *      message.
 * @property {Function} [fix] The function to call that creates a fix command.
 * @property {Array<{desc?: string, messageId?: string, fix: Function}>} suggest Suggestion descriptions and functions to create a the associated fixes.
 */

//------------------------------------------------------------------------------
// Module Definition
//------------------------------------------------------------------------------

/**
 * Translates a multi-argument context.report() call into a single object argument call
 * @param {...*} args A list of arguments passed to `context.report`
 * @returns {MessageDescriptor} A normalized object containing report information
 */
function normalizeMultiArgReportCall(...args) {

    // If there is one argument, it is considered to be a new-style call already.
    if (args.length === 1) {

        // Shallow clone the object to avoid surprises if reusing the descriptor
        return Object.assign({}, args[0]);
    }

    // If the second argument is a string, the arguments are interpreted as [node, message, data, fix].
    if (typeof args[1] === "string") {
        return {
            node: args[0],
            message: args[1],
            data: args[2],
            fix: args[3]
        };
    }

    // Otherwise, the arguments are interpreted as [node, loc, message, data, fix].
    return {
        node: args[0],
        loc: args[1],
        message: args[2],
        data: args[3],
        fix: args[4]
    };
}

/**
 * Asserts that either a loc or a node was provided, and the node is valid if it was provided.
 * @param {MessageDescriptor} descriptor A descriptor to validate
 * @returns {void}
 * @throws AssertionError if neither a node nor a loc was provided, or if the node is not an object
 */
function assertValidNodeInfo(descriptor) {
    if (descriptor.node) {
        assert(typeof descriptor.node === "object", "Node must be an object");
    } else {
        assert(descriptor.loc, "Node must be provided when reporting error if location is not provided");
    }
}

/**
 * Normalizes a MessageDescriptor to always have a `loc` with `start` and `end` properties
 * @param {MessageDescriptor} descriptor A descriptor for the report from a rule.
 * @returns {{start: Location, end: (Location|null)}} An updated location that infers the `start` and `end` properties
 * from the `node` of the original descriptor, or infers the `start` from the `loc` of the original descriptor.
 */
function normalizeReportLoc(descriptor) {
    if (descriptor.loc) {
        if (descriptor.loc.start) {
            return descriptor.loc;
        }
        return { start: descriptor.loc, end: null };
    }
    return descriptor.node.loc;
}

/**
 * Clones the given fix object.
 * @param {Fix|null} fix The fix to clone.
 * @returns {Fix|null} Deep cloned fix object or `null` if `null` or `undefined` was passed in.
 */
function cloneFix(fix) {
    if (!fix) {
        return null;
    }

    return {
        range: [fix.range[0], fix.range[1]],
        text: fix.text
    };
}

/**
 * Check that a fix has a valid range.
 * @param {Fix|null} fix The fix to validate.
 * @returns {void}
 */
function assertValidFix(fix) {
    if (fix) {
        assert(fix.range && typeof fix.range[0] === "number" && typeof fix.range[1] === "number", `Fix has invalid range: ${JSON.stringify(fix, null, 2)}`);
    }
}

/**
 * Compares items in a fixes array by range.
 * @param {Fix} a The first message.
 * @param {Fix} b The second message.
 * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal.
 * @private
 */
function compareFixesByRange(a, b) {
    return a.range[0] - b.range[0] || a.range[1] - b.range[1];
}

/**
 * Merges the given fixes array into one.
 * @param {Fix[]} fixes The fixes to merge.
 * @param {SourceCode} sourceCode The source code object to get the text between fixes.
 * @returns {{text: string, range: number[]}} The merged fixes
 */
function mergeFixes(fixes, sourceCode) {
    for (const fix of fixes) {
        assertValidFix(fix);
    }

    if (fixes.length === 0) {
        return null;
    }
    if (fixes.length === 1) {
        return cloneFix(fixes[0]);
    }

    fixes.sort(compareFixesByRange);

    const originalText = sourceCode.text;
    const start = fixes[0].range[0];
    const end = fixes[fixes.length - 1].range[1];
    let text = "";
    let lastPos = Number.MIN_SAFE_INTEGER;

    for (const fix of fixes) {
        assert(fix.range[0] >= lastPos, "Fix objects must not be overlapped in a report.");

        if (fix.range[0] >= 0) {
            text += originalText.slice(Math.max(0, start, lastPos), fix.range[0]);
        }
        text += fix.text;
        lastPos = fix.range[1];
    }
    text += originalText.slice(Math.max(0, start, lastPos), end);

    return { range: [start, end], text };
}

/**
 * Gets one fix object from the given descriptor.
 * If the descriptor retrieves multiple fixes, this merges those to one.
 * @param {MessageDescriptor} descriptor The report descriptor.
 * @param {SourceCode} sourceCode The source code object to get text between fixes.
 * @returns {({text: string, range: number[]}|null)} The fix for the descriptor
 */
function normalizeFixes(descriptor, sourceCode) {
    if (typeof descriptor.fix !== "function") {
        return null;
    }

    // @type {null | Fix | Fix[] | IterableIterator<Fix>}
    const fix = descriptor.fix(ruleFixer);

    // Merge to one.
    if (fix && Symbol.iterator in fix) {
        return mergeFixes(Array.from(fix), sourceCode);
    }

    assertValidFix(fix);
    return cloneFix(fix);
}

/**
 * Gets an array of suggestion objects from the given descriptor.
 * @param {MessageDescriptor} descriptor The report descriptor.
 * @param {SourceCode} sourceCode The source code object to get text between fixes.
 * @param {Object} messages Object of meta messages for the rule.
 * @returns {Array<SuggestionResult>} The suggestions for the descriptor
 */
function mapSuggestions(descriptor, sourceCode, messages) {
    if (!descriptor.suggest || !Array.isArray(descriptor.suggest)) {
        return [];
    }

    return descriptor.suggest
        .map(suggestInfo => {
            const computedDesc = suggestInfo.desc || messages[suggestInfo.messageId];

            return {
                ...suggestInfo,
                desc: interpolate(computedDesc, suggestInfo.data),
                fix: normalizeFixes(suggestInfo, sourceCode)
            };
        })

        // Remove suggestions that didn't provide a fix
        .filter(({ fix }) => fix);
}

/**
 * Creates information about the report from a descriptor
 * @param {Object} options Information about the problem
 * @param {string} options.ruleId Rule ID
 * @param {(0|1|2)} options.severity Rule severity
 * @param {(ASTNode|null)} options.node Node
 * @param {string} options.message Error message
 * @param {string} [options.messageId] The error message ID.
 * @param {{start: SourceLocation, end: (SourceLocation|null)}} options.loc Start and end location
 * @param {{text: string, range: (number[]|null)}} options.fix The fix object
 * @param {Array<{text: string, range: (number[]|null)}>} options.suggestions The array of suggestions objects
 * @returns {LintMessage} Information about the report
 */
function createProblem(options) {
    const problem = {
        ruleId: options.ruleId,
        severity: options.severity,
        message: options.message,
        line: options.loc.start.line,
        column: options.loc.start.column + 1,
        nodeType: options.node && options.node.type || null
    };

    /*
     * If this isn’t in the conditional, some of the tests fail
     * because `messageId` is present in the problem object
     */
    if (options.messageId) {
        problem.messageId = options.messageId;
    }

    if (options.loc.end) {
        problem.endLine = options.loc.end.line;
        problem.endColumn = options.loc.end.column + 1;
    }

    if (options.fix) {
        problem.fix = options.fix;
    }

    if (options.suggestions && options.suggestions.length > 0) {
        problem.suggestions = options.suggestions;
    }

    return problem;
}

/**
 * Validates that suggestions are properly defined. Throws if an error is detected.
 * @param {Array<{ desc?: string, messageId?: string }>} suggest The incoming suggest data.
 * @param {Object} messages Object of meta messages for the rule.
 * @returns {void}
 */
function validateSuggestions(suggest, messages) {
    if (suggest && Array.isArray(suggest)) {
        suggest.forEach(suggestion => {
            if (suggestion.messageId) {
                const { messageId } = suggestion;

                if (!messages) {
                    throw new TypeError(`context.report() called with a suggest option with a messageId '${messageId}', but no messages were present in the rule metadata.`);
                }

                if (!messages[messageId]) {
                    throw new TypeError(`context.report() called with a suggest option with a messageId '${messageId}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`);
                }

                if (suggestion.desc) {
                    throw new TypeError("context.report() called with a suggest option that defines both a 'messageId' and an 'desc'. Please only pass one.");
                }
            } else if (!suggestion.desc) {
                throw new TypeError("context.report() called with a suggest option that doesn't have either a `desc` or `messageId`");
            }

            if (typeof suggestion.fix !== "function") {
                throw new TypeError(`context.report() called with a suggest option without a fix function. See: ${suggestion}`);
            }
        });
    }
}

/**
 * Returns a function that converts the arguments of a `context.report` call from a rule into a reported
 * problem for the Node.js API.
 * @param {{ruleId: string, severity: number, sourceCode: SourceCode, messageIds: Object, disableFixes: boolean}} metadata Metadata for the reported problem
 * @param {SourceCode} sourceCode The `SourceCode` instance for the text being linted
 * @returns {function(...args): LintMessage} Function that returns information about the report
 */

module.exports = function createReportTranslator(metadata) {

    /*
     * `createReportTranslator` gets called once per enabled rule per file. It needs to be very performant.
     * The report translator itself (i.e. the function that `createReportTranslator` returns) gets
     * called every time a rule reports a problem, which happens much less frequently (usually, the vast
     * majority of rules don't report any problems for a given file).
     */
    return (...args) => {
        const descriptor = normalizeMultiArgReportCall(...args);
        const messages = metadata.messageIds;

        assertValidNodeInfo(descriptor);

        let computedMessage;

        if (descriptor.messageId) {
            if (!messages) {
                throw new TypeError("context.report() called with a messageId, but no messages were present in the rule metadata.");
            }
            const id = descriptor.messageId;

            if (descriptor.message) {
                throw new TypeError("context.report() called with a message and a messageId. Please only pass one.");
            }
            if (!messages || !Object.prototype.hasOwnProperty.call(messages, id)) {
                throw new TypeError(`context.report() called with a messageId of '${id}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`);
            }
            computedMessage = messages[id];
        } else if (descriptor.message) {
            computedMessage = descriptor.message;
        } else {
            throw new TypeError("Missing `message` property in report() call; add a message that describes the linting problem.");
        }

        validateSuggestions(descriptor.suggest, messages);

        return createProblem({
            ruleId: metadata.ruleId,
            severity: metadata.severity,
            node: descriptor.node,
            message: interpolate(computedMessage, descriptor.data),
            messageId: descriptor.messageId,
            loc: normalizeReportLoc(descriptor),
            fix: metadata.disableFixes ? null : normalizeFixes(descriptor, metadata.sourceCode),
            suggestions: metadata.disableFixes ? [] : mapSuggestions(descriptor, metadata.sourceCode, messages)
        });
    };
};


code:
/**
 * @fileoverview An object that creates fix commands for rules.
 * @author Nicholas C. Zakas
 */
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

// none!

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
 * Creates a fix command that inserts text at the specified index in the source text.
 * @param {int} index The 0-based index at which to insert the new text.
 * @param {string} text The text to insert.
 * @returns {Object} The fix command.
 * @private
 */
function insertTextAt(index, text) {
    return {
        range: [index, index],
        text
    };
}

//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

/**
 * Creates code fixing commands for rules.
 */

const ruleFixer = Object.freeze({

    /**
     * Creates a fix command that inserts text after the given node or token.
     * The fix is not applied until applyFixes() is called.
     * @param {ASTNode|Token} nodeOrToken The node or token to insert after.
     * @param {string} text The text to insert.
     * @returns {Object} The fix command.
     */
    insertTextAfter(nodeOrToken, text) {
        return this.insertTextAfterRange(nodeOrToken.range, text);
    },

    /**
     * Creates a fix command that inserts text after the specified range in the source text.
     * The fix is not applied until applyFixes() is called.
     * @param {int[]} range The range to replace, first item is start of range, second
     *      is end of range.
     * @param {string} text The text to insert.
     * @returns {Object} The fix command.
     */
    insertTextAfterRange(range, text) {
        return insertTextAt(range[1], text);
    },

    /**
     * Creates a fix command that inserts text before the given node or token.
     * The fix is not applied until applyFixes() is called.
     * @param {ASTNode|Token} nodeOrToken The node or token to insert before.
     * @param {string} text The text to insert.
     * @returns {Object} The fix command.
     */
    insertTextBefore(nodeOrToken, text) {
        return this.insertTextBeforeRange(nodeOrToken.range, text);
    },

    /**
     * Creates a fix command that inserts text before the specified range in the source text.
     * The fix is not applied until applyFixes() is called.
     * @param {int[]} range The range to replace, first item is start of range, second
     *      is end of range.
     * @param {string} text The text to insert.
     * @returns {Object} The fix command.
     */
    insertTextBeforeRange(range, text) {
        return insertTextAt(range[0], text);
    },

    /**
     * Creates a fix command that replaces text at the node or token.
     * The fix is not applied until applyFixes() is called.
     * @param {ASTNode|Token} nodeOrToken The node or token to remove.
     * @param {string} text The text to insert.
     * @returns {Object} The fix command.
     */
    replaceText(nodeOrToken, text) {
        return this.replaceTextRange(nodeOrToken.range, text);
    },

    /**
     * Creates a fix command that replaces text at the specified range in the source text.
     * The fix is not applied until applyFixes() is called.
     * @param {int[]} range The range to replace, first item is start of range, second
     *      is end of range.
     * @param {string} text The text to insert.
     * @returns {Object} The fix command.
     */
    replaceTextRange(range, text) {
        return {
            range,
            text
        };
    },

    /**
     * Creates a fix command that removes the node or token from the source.
     * The fix is not applied until applyFixes() is called.
     * @param {ASTNode|Token} nodeOrToken The node or token to remove.
     * @returns {Object} The fix command.
     */
    remove(nodeOrToken) {
        return this.removeRange(nodeOrToken.range);
    },

    /**
     * Creates a fix command that removes the specified range of text from the source.
     * The fix is not applied until applyFixes() is called.
     * @param {int[]} range The range to remove, first item is start of range, second
     *      is end of range.
     * @returns {Object} The fix command.
     */
    removeRange(range) {
        return {
            range,
            text: ""
        };
    }

});

module.exports = ruleFixer;

license: mit


code:
/**
 * @fileoverview Defines a storage for rules.
 * @author Nicholas C. Zakas
 * @author aladdin-add
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const builtInRules = require("../rules");

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
 * Normalizes a rule module to the new-style API
 * @param {(Function|{create: Function})} rule A rule object, which can either be a function
 * ("old-style") or an object with a `create` method ("new-style")
 * @returns {{create: Function}} A new-style rule.
 */
function normalizeRule(rule) {
    return typeof rule === "function" ? Object.assign({ create: rule }, rule) : rule;
}

//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

/**
 * A storage for rules.
 */
class Rules {
    constructor() {
        this._rules = Object.create(null);
    }

    /**
     * Registers a rule module for rule id in storage.
     * @param {string} ruleId Rule id (file name).
     * @param {Function} ruleModule Rule handler.
     * @returns {void}
     */
    define(ruleId, ruleModule) {
        this._rules[ruleId] = normalizeRule(ruleModule);
    }

    /**
     * Access rule handler by id (file name).
     * @param {string} ruleId Rule id (file name).
     * @returns {{create: Function, schema: JsonSchema[]}}
     * A rule. This is normalized to always have the new-style shape with a `create` method.
     */
    get(ruleId) {
        if (typeof this._rules[ruleId] === "string") {
            this.define(ruleId, require(this._rules[ruleId]));
        }
        if (this._rules[ruleId]) {
            return this._rules[ruleId];
        }
        if (builtInRules.has(ruleId)) {
            return builtInRules.get(ruleId);
        }

        return null;
    }

    *[Symbol.iterator]() {
        yield* builtInRules;

        for (const ruleId of Object.keys(this._rules)) {
            yield [ruleId, this.get(ruleId)];
        }
    }
}

module.exports = Rules;


code:
/**
 * @fileoverview A variant of EventEmitter which does not give listeners information about each other
 * @author Teddy Katz
 */

"use strict";

//------------------------------------------------------------------------------
// Typedefs
//------------------------------------------------------------------------------

/**
 * An event emitter
 * @typedef {Object} SafeEmitter
 * @property {(eventName: string, listenerFunc: Function) => void} on Adds a listener for a given event name
 * @property {(eventName: string, arg1?: any, arg2?: any, arg3?: any) => void} emit Emits an event with a given name.
 * This calls all the listeners that were listening for that name, with `arg1`, `arg2`, and `arg3` as arguments.
 * @property {function(): string[]} eventNames Gets the list of event names that have registered listeners.
 */

/**
 * Creates an object which can listen for and emit events.
 * This is similar to the EventEmitter API in Node's standard library, but it has a few differences.
 * The goal is to allow multiple modules to attach arbitrary listeners to the same emitter, without
 * letting the modules know about each other at all.
 * 1. It has no special keys like `error` and `newListener`, which would allow modules to detect when
 * another module throws an error or registers a listener.
 * 2. It calls listener functions without any `this` value. (`EventEmitter` calls listeners with a
 * `this` value of the emitter instance, which would give listeners access to other listeners.)
 * @returns {SafeEmitter} An emitter
 */
module.exports = () => {
    const listeners = Object.create(null);

    return Object.freeze({
        on(eventName, listener) {
            if (eventName in listeners) {
                listeners[eventName].push(listener);
            } else {
                listeners[eventName] = [listener];
            }
        },
        emit(eventName, ...args) {
            if (eventName in listeners) {
                listeners[eventName].forEach(listener => listener(...args));
            }
        },
        eventNames() {
            return Object.keys(listeners);
        }
    });
};


code:
/**
 * @fileoverview An object that caches and applies source code fixes.
 * @author Nicholas C. Zakas
 */
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const debug = require("debug")("eslint:source-code-fixer");

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

const BOM = "\uFEFF";

/**
 * Compares items in a messages array by range.
 * @param {Message} a The first message.
 * @param {Message} b The second message.
 * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal.
 * @private
 */
function compareMessagesByFixRange(a, b) {
    return a.fix.range[0] - b.fix.range[0] || a.fix.range[1] - b.fix.range[1];
}

/**
 * Compares items in a messages array by line and column.
 * @param {Message} a The first message.
 * @param {Message} b The second message.
 * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal.
 * @private
 */
function compareMessagesByLocation(a, b) {
    return a.line - b.line || a.column - b.column;
}

//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

/**
 * Utility for apply fixes to source code.
 * @constructor
 */
function SourceCodeFixer() {
    Object.freeze(this);
}

/**
 * Applies the fixes specified by the messages to the given text. Tries to be
 * smart about the fixes and won't apply fixes over the same area in the text.
 * @param {string} sourceText The text to apply the changes to.
 * @param {Message[]} messages The array of messages reported by ESLint.
 * @param {boolean|Function} [shouldFix=true] Determines whether each message should be fixed
 * @returns {Object} An object containing the fixed text and any unfixed messages.
 */
SourceCodeFixer.applyFixes = function(sourceText, messages, shouldFix) {
    debug("Applying fixes");

    if (shouldFix === false) {
        debug("shouldFix parameter was false, not attempting fixes");
        return {
            fixed: false,
            messages,
            output: sourceText
        };
    }

    // clone the array
    const remainingMessages = [],
        fixes = [],
        bom = sourceText.startsWith(BOM) ? BOM : "",
        text = bom ? sourceText.slice(1) : sourceText;
    let lastPos = Number.NEGATIVE_INFINITY,
        output = bom;

    /**
     * Try to use the 'fix' from a problem.
     * @param {Message} problem The message object to apply fixes from
     * @returns {boolean} Whether fix was successfully applied
     */
    function attemptFix(problem) {
        const fix = problem.fix;
        const start = fix.range[0];
        const end = fix.range[1];

        // Remain it as a problem if it's overlapped or it's a negative range
        if (lastPos >= start || start > end) {
            remainingMessages.push(problem);
            return false;
        }

        // Remove BOM.
        if ((start < 0 && end >= 0) || (start === 0 && fix.text.startsWith(BOM))) {
            output = "";
        }

        // Make output to this fix.
        output += text.slice(Math.max(0, lastPos), Math.max(0, start));
        output += fix.text;
        lastPos = end;
        return true;
    }

    messages.forEach(problem => {
        if (Object.prototype.hasOwnProperty.call(problem, "fix")) {
            fixes.push(problem);
        } else {
            remainingMessages.push(problem);
        }
    });

    if (fixes.length) {
        debug("Found fixes to apply");
        let fixesWereApplied = false;

        for (const problem of fixes.sort(compareMessagesByFixRange)) {
            if (typeof shouldFix !== "function" || shouldFix(problem)) {
                attemptFix(problem);

                /*
                 * The only time attemptFix will fail is if a previous fix was
                 * applied which conflicts with it.  So we can mark this as true.
                 */
                fixesWereApplied = true;
            } else {
                remainingMessages.push(problem);
            }
        }
        output += text.slice(Math.max(0, lastPos));

        return {
            fixed: fixesWereApplied,
            messages: remainingMessages.sort(compareMessagesByLocation),
            output
        };
    }

    debug("No fixes to apply");
    return {
        fixed: false,
        messages,
        output: bom + text
    };

};

module.exports = SourceCodeFixer;


code:
/**
 * @fileoverview Tracks performance of individual rules.
 * @author Brandon Mills
 */

"use strict";

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/* c8 ignore next */
/**
 * Align the string to left
 * @param {string} str string to evaluate
 * @param {int} len length of the string
 * @param {string} ch delimiter character
 * @returns {string} modified string
 * @private
 */
function alignLeft(str, len, ch) {
    return str + new Array(len - str.length + 1).join(ch || " ");
}

/* c8 ignore next */
/**
 * Align the string to right
 * @param {string} str string to evaluate
 * @param {int} len length of the string
 * @param {string} ch delimiter character
 * @returns {string} modified string
 * @private
 */
function alignRight(str, len, ch) {
    return new Array(len - str.length + 1).join(ch || " ") + str;
}

//------------------------------------------------------------------------------
// Module definition
//------------------------------------------------------------------------------

const enabled = !!process.env.TIMING;

const HEADERS = ["Rule", "Time (ms)", "Relative"];
const ALIGN = [alignLeft, alignRight, alignRight];

/**
 * Decide how many rules to show in the output list.
 * @returns {number} the number of rules to show
 */
function getListSize() {
    const MINIMUM_SIZE = 10;

    if (typeof process.env.TIMING !== "string") {
        return MINIMUM_SIZE;
    }

    if (process.env.TIMING.toLowerCase() === "all") {
        return Number.POSITIVE_INFINITY;
    }

    const TIMING_ENV_VAR_AS_INTEGER = Number.parseInt(process.env.TIMING, 10);

    return TIMING_ENV_VAR_AS_INTEGER > 10 ? TIMING_ENV_VAR_AS_INTEGER : MINIMUM_SIZE;
}

/* c8 ignore next */
/**
 * display the data
 * @param {Object} data Data object to be displayed
 * @returns {void} prints modified string with console.log
 * @private
 */
function display(data) {
    let total = 0;
    const rows = Object.keys(data)
        .map(key => {
            const time = data[key];

            total += time;
            return [key, time];
        })
        .sort((a, b) => b[1] - a[1])
        .slice(0, getListSize());

    rows.forEach(row => {
        row.push(`${(row[1] * 100 / total).toFixed(1)}%`);
        row[1] = row[1].toFixed(3);
    });

    rows.unshift(HEADERS);

    const widths = [];

    rows.forEach(row => {
        const len = row.length;

        for (let i = 0; i < len; i++) {
            const n = row[i].length;

            if (!widths[i] || n > widths[i]) {
                widths[i] = n;
            }
        }
    });

    const table = rows.map(row => (
        row
            .map((cell, index) => ALIGN[index](cell, widths[index]))
            .join(" | ")
    ));

    table.splice(1, 0, widths.map((width, index) => {
        const extraAlignment = index !== 0 && index !== widths.length - 1 ? 2 : 1;

        return ALIGN[index](":", width + extraAlignment, "-");
    }).join("|"));

    console.log(table.join("\n")); // eslint-disable-line no-console -- Debugging function
}

/* c8 ignore next */
module.exports = (function() {

    const data = Object.create(null);

    /**
     * Time the run
     * @param {any} key key from the data object
     * @param {Function} fn function to be called
     * @returns {Function} function to be executed
     * @private
     */
    function time(key, fn) {
        if (typeof data[key] === "undefined") {
            data[key] = 0;
        }

        return function(...args) {
            let t = process.hrtime();
            const result = fn(...args);

            t = process.hrtime(t);
            data[key] += t[0] * 1e3 + t[1] / 1e6;
            return result;
        };
    }

    if (enabled) {
        process.on("exit", () => {
            display(data);
        });
    }

    return {
        time,
        enabled,
        getListSize
    };

}());


code:
/**
 * @fileoverview Options configuration for optionator.
 * @author George Zahariev
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const optionator = require("optionator");

//------------------------------------------------------------------------------
// Typedefs
//------------------------------------------------------------------------------

/**
 * The options object parsed by Optionator.
 * @typedef {Object} ParsedCLIOptions
 * @property {boolean} cache Only check changed files
 * @property {string} cacheFile Path to the cache file. Deprecated: use --cache-location
 * @property {string} [cacheLocation] Path to the cache file or directory
 * @property {"metadata" | "content"} cacheStrategy Strategy to use for detecting changed files in the cache
 * @property {boolean} [color] Force enabling/disabling of color
 * @property {string} [config] Use this configuration, overriding .eslintrc.* config options if present
 * @property {boolean} debug Output debugging information
 * @property {string[]} [env] Specify environments
 * @property {boolean} envInfo Output execution environment information
 * @property {boolean} errorOnUnmatchedPattern Prevent errors when pattern is unmatched
 * @property {boolean} eslintrc Disable use of configuration from .eslintrc.*
 * @property {string[]} [ext] Specify JavaScript file extensions
 * @property {boolean} fix Automatically fix problems
 * @property {boolean} fixDryRun Automatically fix problems without saving the changes to the file system
 * @property {("directive" | "problem" | "suggestion" | "layout")[]} [fixType] Specify the types of fixes to apply (directive, problem, suggestion, layout)
 * @property {string} format Use a specific output format
 * @property {string[]} [global] Define global variables
 * @property {boolean} [help] Show help
 * @property {boolean} ignore Disable use of ignore files and patterns
 * @property {string} [ignorePath] Specify path of ignore file
 * @property {string[]} [ignorePattern] Pattern of files to ignore (in addition to those in .eslintignore)
 * @property {boolean} init Run config initialization wizard
 * @property {boolean} inlineConfig Prevent comments from changing config or rules
 * @property {number} maxWarnings Number of warnings to trigger nonzero exit code
 * @property {string} [outputFile] Specify file to write report to
 * @property {string} [parser] Specify the parser to be used
 * @property {Object} [parserOptions] Specify parser options
 * @property {string[]} [plugin] Specify plugins
 * @property {string} [printConfig] Print the configuration for the given file
 * @property {boolean | undefined} reportUnusedDisableDirectives Adds reported errors for unused eslint-disable and eslint-enable directives
 * @property {string | undefined} reportUnusedDisableDirectivesSeverity A severity string indicating if and how unused disable and enable directives should be tracked and reported.
 * @property {string} [resolvePluginsRelativeTo] A folder where plugins should be resolved from, CWD by default
 * @property {Object} [rule] Specify rules
 * @property {string[]} [rulesdir] Load additional rules from this directory. Deprecated: Use rules from plugins
 * @property {boolean} stdin Lint code provided on <STDIN>
 * @property {string} [stdinFilename] Specify filename to process STDIN as
 * @property {boolean} quiet Report errors only
 * @property {boolean} [version] Output the version number
 * @property {boolean} warnIgnored Show warnings when the file list includes ignored files
 * @property {string[]} _ Positional filenames or patterns
 */

//------------------------------------------------------------------------------
// Initialization and Public Interface
//------------------------------------------------------------------------------

// exports "parse(args)", "generateHelp()", and "generateHelpForOption(optionName)"

/**
 * Creates the CLI options for ESLint.
 * @param {boolean} usingFlatConfig Indicates if flat config is being used.
 * @returns {Object} The optionator instance.
 */
module.exports = function(usingFlatConfig) {

    let lookupFlag;

    if (usingFlatConfig) {
        lookupFlag = {
            option: "config-lookup",
            type: "Boolean",
            default: "true",
            description: "Disable look up for eslint.config.js"
        };
    } else {
        lookupFlag = {
            option: "eslintrc",
            type: "Boolean",
            default: "true",
            description: "Disable use of configuration from .eslintrc.*"
        };
    }

    let envFlag;

    if (!usingFlatConfig) {
        envFlag = {
            option: "env",
            type: "[String]",
            description: "Specify environments"
        };
    }

    let extFlag;

    if (!usingFlatConfig) {
        extFlag = {
            option: "ext",
            type: "[String]",
            description: "Specify JavaScript file extensions"
        };
    }

    let resolvePluginsFlag;

    if (!usingFlatConfig) {
        resolvePluginsFlag = {
            option: "resolve-plugins-relative-to",
            type: "path::String",
            description: "A folder where plugins should be resolved from, CWD by default"
        };
    }

    let rulesDirFlag;

    if (!usingFlatConfig) {
        rulesDirFlag = {
            option: "rulesdir",
            type: "[path::String]",
            description: "Load additional rules from this directory. Deprecated: Use rules from plugins"
        };
    }

    let ignorePathFlag;

    if (!usingFlatConfig) {
        ignorePathFlag = {
            option: "ignore-path",
            type: "path::String",
            description: "Specify path of ignore file"
        };
    }

    let warnIgnoredFlag;

    if (usingFlatConfig) {
        warnIgnoredFlag = {
            option: "warn-ignored",
            type: "Boolean",
            default: "true",
            description: "Suppress warnings when the file list includes ignored files"
        };
    }

    return optionator({
        prepend: "eslint [options] file.js [file.js] [dir]",
        defaults: {
            concatRepeatedArrays: true,
            mergeRepeatedObjects: true
        },
        options: [
            {
                heading: "Basic configuration"
            },
            lookupFlag,
            {
                option: "config",
                alias: "c",
                type: "path::String",
                description: usingFlatConfig
                    ? "Use this configuration instead of eslint.config.js, eslint.config.mjs, or eslint.config.cjs"
                    : "Use this configuration, overriding .eslintrc.* config options if present"
            },
            envFlag,
            extFlag,
            {
                option: "global",
                type: "[String]",
                description: "Define global variables"
            },
            {
                option: "parser",
                type: "String",
                description: "Specify the parser to be used"
            },
            {
                option: "parser-options",
                type: "Object",
                description: "Specify parser options"
            },
            resolvePluginsFlag,
            {
                heading: "Specify Rules and Plugins"
            },
            {
                option: "plugin",
                type: "[String]",
                description: "Specify plugins"
            },
            {
                option: "rule",
                type: "Object",
                description: "Specify rules"
            },
            rulesDirFlag,
            {
                heading: "Fix Problems"
            },
            {
                option: "fix",
                type: "Boolean",
                default: false,
                description: "Automatically fix problems"
            },
            {
                option: "fix-dry-run",
                type: "Boolean",
                default: false,
                description: "Automatically fix problems without saving the changes to the file system"
            },
            {
                option: "fix-type",
                type: "Array",
                description: "Specify the types of fixes to apply (directive, problem, suggestion, layout)"
            },
            {
                heading: "Ignore Files"
            },
            ignorePathFlag,
            {
                option: "ignore",
                type: "Boolean",
                default: "true",
                description: "Disable use of ignore files and patterns"
            },
            {
                option: "ignore-pattern",
                type: "[String]",
                description: "Pattern of files to ignore (in addition to those in .eslintignore)",
                concatRepeatedArrays: [true, {
                    oneValuePerFlag: true
                }]
            },
            {
                heading: "Use stdin"
            },
            {
                option: "stdin",
                type: "Boolean",
                default: "false",
                description: "Lint code provided on <STDIN>"
            },
            {
                option: "stdin-filename",
                type: "String",
                description: "Specify filename to process STDIN as"
            },
            {
                heading: "Handle Warnings"
            },
            {
                option: "quiet",
                type: "Boolean",
                default: "false",
                description: "Report errors only"
            },
            {
                option: "max-warnings",
                type: "Int",
                default: "-1",
                description: "Number of warnings to trigger nonzero exit code"
            },
            {
                heading: "Output"
            },
            {
                option: "output-file",
                alias: "o",
                type: "path::String",
                description: "Specify file to write report to"
            },
            {
                option: "format",
                alias: "f",
                type: "String",
                default: "stylish",
                description: "Use a specific output format"
            },
            {
                option: "color",
                type: "Boolean",
                alias: "no-color",
                description: "Force enabling/disabling of color"
            },
            {
                heading: "Inline configuration comments"
            },
            {
                option: "inline-config",
                type: "Boolean",
                default: "true",
                description: "Prevent comments from changing config or rules"
            },
            {
                option: "report-unused-disable-directives",
                type: "Boolean",
                default: void 0,
                description: "Adds reported errors for unused eslint-disable and eslint-enable directives"
            },
            {
                option: "report-unused-disable-directives-severity",
                type: "String",
                default: void 0,
                description: "Chooses severity level for reporting unused eslint-disable and eslint-enable directives",
                enum: ["off", "warn", "error", "0", "1", "2"]
            },
            {
                heading: "Caching"
            },
            {
                option: "cache",
                type: "Boolean",
                default: "false",
                description: "Only check changed files"
            },
            {
                option: "cache-file",
                type: "path::String",
                default: ".eslintcache",
                description: "Path to the cache file. Deprecated: use --cache-location"
            },
            {
                option: "cache-location",
                type: "path::String",
                description: "Path to the cache file or directory"
            },
            {
                option: "cache-strategy",
                dependsOn: ["cache"],
                type: "String",
                default: "metadata",
                enum: ["metadata", "content"],
                description: "Strategy to use for detecting changed files in the cache"
            },
            {
                heading: "Miscellaneous"
            },
            {
                option: "init",
                type: "Boolean",
                default: "false",
                description: "Run config initialization wizard"
            },
            {
                option: "env-info",
                type: "Boolean",
                default: "false",
                description: "Output execution environment information"
            },
            {
                option: "error-on-unmatched-pattern",
                type: "Boolean",
                default: "true",
                description: "Prevent errors when pattern is unmatched"
            },
            {
                option: "exit-on-fatal-error",
                type: "Boolean",
                default: "false",
                description: "Exit with exit code 2 in case of fatal error"
            },
            warnIgnoredFlag,
            {
                option: "debug",
                type: "Boolean",
                default: false,
                description: "Output debugging information"
            },
            {
                option: "help",
                alias: "h",
                type: "Boolean",
                description: "Show help"
            },
            {
                option: "version",
                alias: "v",
                type: "Boolean",
                description: "Output the version number"
            },
            {
                option: "print-config",
                type: "path::String",
                description: "Print the configuration for the given file"
            }
        ].filter(value => !!value)
    });
};


code:
/**
 * @fileoverview Mocha/Jest test wrapper
 * @author Ilya Volodin
 */
"use strict";

/* globals describe, it -- Mocha globals */

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const
    assert = require("assert"),
    util = require("util"),
    path = require("path"),
    equal = require("fast-deep-equal"),
    Traverser = require("../shared/traverser"),
    { getRuleOptionsSchema } = require("../config/flat-config-helpers"),
    { Linter, SourceCodeFixer, interpolate } = require("../linter"),
    CodePath = require("../linter/code-path-analysis/code-path");

const { FlatConfigArray } = require("../config/flat-config-array");
const { defaultConfig } = require("../config/default-config");

const ajv = require("../shared/ajv")({ strictDefaults: true });

const parserSymbol = Symbol.for("eslint.RuleTester.parser");
const { SourceCode } = require("../source-code");
const { ConfigArraySymbol } = require("@humanwhocodes/config-array");

//------------------------------------------------------------------------------
// Typedefs
//------------------------------------------------------------------------------

/** @typedef {import("../shared/types").Parser} Parser */
/** @typedef {import("../shared/types").LanguageOptions} LanguageOptions */
/** @typedef {import("../shared/types").Rule} Rule */

/**
 * A test case that is expected to pass lint.
 * @typedef {Object} ValidTestCase
 * @property {string} [name] Name for the test case.
 * @property {string} code Code for the test case.
 * @property {any[]} [options] Options for the test case.
 * @property {LanguageOptions} [languageOptions] The language options to use in the test case.
 * @property {{ [name: string]: any }} [settings] Settings for the test case.
 * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames.
 * @property {boolean} [only] Run only this test case or the subset of test cases with this property.
 */

/**
 * A test case that is expected to fail lint.
 * @typedef {Object} InvalidTestCase
 * @property {string} [name] Name for the test case.
 * @property {string} code Code for the test case.
 * @property {number | Array<TestCaseError | string | RegExp>} errors Expected errors.
 * @property {string | null} [output] The expected code after autofixes are applied. If set to `null`, the test runner will assert that no autofix is suggested.
 * @property {any[]} [options] Options for the test case.
 * @property {{ [name: string]: any }} [settings] Settings for the test case.
 * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames.
 * @property {LanguageOptions} [languageOptions] The language options to use in the test case.
 * @property {boolean} [only] Run only this test case or the subset of test cases with this property.
 */

/**
 * A description of a reported error used in a rule tester test.
 * @typedef {Object} TestCaseError
 * @property {string | RegExp} [message] Message.
 * @property {string} [messageId] Message ID.
 * @property {string} [type] The type of the reported AST node.
 * @property {{ [name: string]: string }} [data] The data used to fill the message template.
 * @property {number} [line] The 1-based line number of the reported start location.
 * @property {number} [column] The 1-based column number of the reported start location.
 * @property {number} [endLine] The 1-based line number of the reported end location.
 * @property {number} [endColumn] The 1-based column number of the reported end location.
 */

//------------------------------------------------------------------------------
// Private Members
//------------------------------------------------------------------------------

/*
 * testerDefaultConfig must not be modified as it allows to reset the tester to
 * the initial default configuration
 */
const testerDefaultConfig = { rules: {} };

/*
 * RuleTester uses this config as its default. This can be overwritten via
 * setDefaultConfig().
 */
let sharedDefaultConfig = { rules: {} };

/*
 * List every parameters possible on a test case that are not related to eslint
 * configuration
 */
const RuleTesterParameters = [
    "name",
    "code",
    "filename",
    "options",
    "errors",
    "output",
    "only"
];

/*
 * All allowed property names in error objects.
 */
const errorObjectParameters = new Set([
    "message",
    "messageId",
    "data",
    "type",
    "line",
    "column",
    "endLine",
    "endColumn",
    "suggestions"
]);
const friendlyErrorObjectParameterList = `[${[...errorObjectParameters].map(key => `'${key}'`).join(", ")}]`;

/*
 * All allowed property names in suggestion objects.
 */
const suggestionObjectParameters = new Set([
    "desc",
    "messageId",
    "data",
    "output"
]);
const friendlySuggestionObjectParameterList = `[${[...suggestionObjectParameters].map(key => `'${key}'`).join(", ")}]`;

const forbiddenMethods = [
    "applyInlineConfig",
    "applyLanguageOptions",
    "finalize"
];

/** @type {Map<string,WeakSet>} */
const forbiddenMethodCalls = new Map(forbiddenMethods.map(methodName => ([methodName, new WeakSet()])));

const hasOwnProperty = Function.call.bind(Object.hasOwnProperty);

/**
 * Clones a given value deeply.
 * Note: This ignores `parent` property.
 * @param {any} x A value to clone.
 * @returns {any} A cloned value.
 */
function cloneDeeplyExcludesParent(x) {
    if (typeof x === "object" && x !== null) {
        if (Array.isArray(x)) {
            return x.map(cloneDeeplyExcludesParent);
        }

        const retv = {};

        for (const key in x) {
            if (key !== "parent" && hasOwnProperty(x, key)) {
                retv[key] = cloneDeeplyExcludesParent(x[key]);
            }
        }

        return retv;
    }

    return x;
}

/**
 * Freezes a given value deeply.
 * @param {any} x A value to freeze.
 * @returns {void}
 */
function freezeDeeply(x) {
    if (typeof x === "object" && x !== null) {
        if (Array.isArray(x)) {
            x.forEach(freezeDeeply);
        } else {
            for (const key in x) {
                if (key !== "parent" && hasOwnProperty(x, key)) {
                    freezeDeeply(x[key]);
                }
            }
        }
        Object.freeze(x);
    }
}

/**
 * Replace control characters by `\u00xx` form.
 * @param {string} text The text to sanitize.
 * @returns {string} The sanitized text.
 */
function sanitize(text) {
    if (typeof text !== "string") {
        return "";
    }
    return text.replace(
        /[\u0000-\u0009\u000b-\u001a]/gu, // eslint-disable-line no-control-regex -- Escaping controls
        c => `\\u${c.codePointAt(0).toString(16).padStart(4, "0")}`
    );
}

/**
 * Define `start`/`end` properties as throwing error.
 * @param {string} objName Object name used for error messages.
 * @param {ASTNode} node The node to define.
 * @returns {void}
 */
function defineStartEndAsError(objName, node) {
    Object.defineProperties(node, {
        start: {
            get() {
                throw new Error(`Use ${objName}.range[0] instead of ${objName}.start`);
            },
            configurable: true,
            enumerable: false
        },
        end: {
            get() {
                throw new Error(`Use ${objName}.range[1] instead of ${objName}.end`);
            },
            configurable: true,
            enumerable: false
        }
    });
}

/**
 * Define `start`/`end` properties of all nodes of the given AST as throwing error.
 * @param {ASTNode} ast The root node to errorize `start`/`end` properties.
 * @param {Object} [visitorKeys] Visitor keys to be used for traversing the given ast.
 * @returns {void}
 */
function defineStartEndAsErrorInTree(ast, visitorKeys) {
    Traverser.traverse(ast, { visitorKeys, enter: defineStartEndAsError.bind(null, "node") });
    ast.tokens.forEach(defineStartEndAsError.bind(null, "token"));
    ast.comments.forEach(defineStartEndAsError.bind(null, "token"));
}

/**
 * Wraps the given parser in order to intercept and modify return values from the `parse` and `parseForESLint` methods, for test purposes.
 * In particular, to modify ast nodes, tokens and comments to throw on access to their `start` and `end` properties.
 * @param {Parser} parser Parser object.
 * @returns {Parser} Wrapped parser object.
 */
function wrapParser(parser) {

    if (typeof parser.parseForESLint === "function") {
        return {
            [parserSymbol]: parser,
            parseForESLint(...args) {
                const ret = parser.parseForESLint(...args);

                defineStartEndAsErrorInTree(ret.ast, ret.visitorKeys);
                return ret;
            }
        };
    }

    return {
        [parserSymbol]: parser,
        parse(...args) {
            const ast = parser.parse(...args);

            defineStartEndAsErrorInTree(ast);
            return ast;
        }
    };
}

/**
 * Function to replace `SourceCode.prototype.getComments`.
 * @returns {void}
 * @throws {Error} Deprecation message.
 */
function getCommentsDeprecation() {
    throw new Error(
        "`SourceCode#getComments()` is deprecated and will be removed in a future major version. Use `getCommentsBefore()`, `getCommentsAfter()`, and `getCommentsInside()` instead."
    );
}

/**
 * Emit a deprecation warning if rule uses CodePath#currentSegments.
 * @param {string} ruleName Name of the rule.
 * @returns {void}
 */
function emitCodePathCurrentSegmentsWarning(ruleName) {
    if (!emitCodePathCurrentSegmentsWarning[`warned-${ruleName}`]) {
        emitCodePathCurrentSegmentsWarning[`warned-${ruleName}`] = true;
        process.emitWarning(
            `"${ruleName}" rule uses CodePath#currentSegments and will stop working in ESLint v9. Please read the documentation for how to update your code: https://eslint.org/docs/latest/extend/code-path-analysis#usage-examples`,
            "DeprecationWarning"
        );
    }
}

/**
 * Function to replace forbidden `SourceCode` methods. Allows just one call per method.
 * @param {string} methodName The name of the method to forbid.
 * @param {Function} prototype The prototype with the original method to call.
 * @returns {Function} The function that throws the error.
 */
function throwForbiddenMethodError(methodName, prototype) {

    const original = prototype[methodName];

    return function(...args) {

        const called = forbiddenMethodCalls.get(methodName);

        /* eslint-disable no-invalid-this -- needed to operate as a method. */
        if (!called.has(this)) {
            called.add(this);

            return original.apply(this, args);
        }
        /* eslint-enable no-invalid-this -- not needed past this point */

        throw new Error(
            `\`SourceCode#${methodName}()\` cannot be called inside a rule.`
        );
    };
}

//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

// default separators for testing
const DESCRIBE = Symbol("describe");
const IT = Symbol("it");
const IT_ONLY = Symbol("itOnly");

/**
 * This is `it` default handler if `it` don't exist.
 * @this {Mocha}
 * @param {string} text The description of the test case.
 * @param {Function} method The logic of the test case.
 * @throws {Error} Any error upon execution of `method`.
 * @returns {any} Returned value of `method`.
 */
function itDefaultHandler(text, method) {
    try {
        return method.call(this);
    } catch (err) {
        if (err instanceof assert.AssertionError) {
            err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`;
        }
        throw err;
    }
}

/**
 * This is `describe` default handler if `describe` don't exist.
 * @this {Mocha}
 * @param {string} text The description of the test case.
 * @param {Function} method The logic of the test case.
 * @returns {any} Returned value of `method`.
 */
function describeDefaultHandler(text, method) {
    return method.call(this);
}

/**
 * Mocha test wrapper.
 */
class FlatRuleTester {

    /**
     * Creates a new instance of RuleTester.
     * @param {Object} [testerConfig] Optional, extra configuration for the tester
     */
    constructor(testerConfig = {}) {

        /**
         * The configuration to use for this tester. Combination of the tester
         * configuration and the default configuration.
         * @type {Object}
         */
        this.testerConfig = [
            sharedDefaultConfig,
            testerConfig,
            { rules: { "rule-tester/validate-ast": "error" } }
        ];

        this.linter = new Linter({ configType: "flat" });
    }

    /**
     * Set the configuration to use for all future tests
     * @param {Object} config the configuration to use.
     * @throws {TypeError} If non-object config.
     * @returns {void}
     */
    static setDefaultConfig(config) {
        if (typeof config !== "object" || config === null) {
            throw new TypeError("FlatRuleTester.setDefaultConfig: config must be an object");
        }
        sharedDefaultConfig = config;

        // Make sure the rules object exists since it is assumed to exist later
        sharedDefaultConfig.rules = sharedDefaultConfig.rules || {};
    }

    /**
     * Get the current configuration used for all tests
     * @returns {Object} the current configuration
     */
    static getDefaultConfig() {
        return sharedDefaultConfig;
    }

    /**
     * Reset the configuration to the initial configuration of the tester removing
     * any changes made until now.
     * @returns {void}
     */
    static resetDefaultConfig() {
        sharedDefaultConfig = {
            rules: {
                ...testerDefaultConfig.rules
            }
        };
    }

    /*
     * If people use `mocha test.js --watch` command, `describe` and `it` function
     * instances are different for each execution. So `describe` and `it` should get fresh instance
     * always.
     */
    static get describe() {
        return (
            this[DESCRIBE] ||
            (typeof describe === "function" ? describe : describeDefaultHandler)
        );
    }

    static set describe(value) {
        this[DESCRIBE] = value;
    }

    static get it() {
        return (
            this[IT] ||
            (typeof it === "function" ? it : itDefaultHandler)
        );
    }

    static set it(value) {
        this[IT] = value;
    }

    /**
     * Adds the `only` property to a test to run it in isolation.
     * @param {string | ValidTestCase | InvalidTestCase} item A single test to run by itself.
     * @returns {ValidTestCase | InvalidTestCase} The test with `only` set.
     */
    static only(item) {
        if (typeof item === "string") {
            return { code: item, only: true };
        }

        return { ...item, only: true };
    }

    static get itOnly() {
        if (typeof this[IT_ONLY] === "function") {
            return this[IT_ONLY];
        }
        if (typeof this[IT] === "function" && typeof this[IT].only === "function") {
            return Function.bind.call(this[IT].only, this[IT]);
        }
        if (typeof it === "function" && typeof it.only === "function") {
            return Function.bind.call(it.only, it);
        }

        if (typeof this[DESCRIBE] === "function" || typeof this[IT] === "function") {
            throw new Error(
                "Set `RuleTester.itOnly` to use `only` with a custom test framework.\n" +
                "See https://eslint.org/docs/latest/integrate/nodejs-api#customizing-ruletester for more."
            );
        }
        if (typeof it === "function") {
            throw new Error("The current test framework does not support exclusive tests with `only`.");
        }
        throw new Error("To use `only`, use RuleTester with a test framework that provides `it.only()` like Mocha.");
    }

    static set itOnly(value) {
        this[IT_ONLY] = value;
    }

    /**
     * Adds a new rule test to execute.
     * @param {string} ruleName The name of the rule to run.
     * @param {Function | Rule} rule The rule to test.
     * @param {{
     *   valid: (ValidTestCase | string)[],
     *   invalid: InvalidTestCase[]
     * }} test The collection of tests to run.
     * @throws {TypeError|Error} If non-object `test`, or if a required
     * scenario of the given type is missing.
     * @returns {void}
     */
    run(ruleName, rule, test) {

        const testerConfig = this.testerConfig,
            requiredScenarios = ["valid", "invalid"],
            scenarioErrors = [],
            linter = this.linter,
            ruleId = `rule-to-test/${ruleName}`;

        if (!test || typeof test !== "object") {
            throw new TypeError(`Test Scenarios for rule ${ruleName} : Could not find test scenario object`);
        }

        requiredScenarios.forEach(scenarioType => {
            if (!test[scenarioType]) {
                scenarioErrors.push(`Could not find any ${scenarioType} test scenarios`);
            }
        });

        if (scenarioErrors.length > 0) {
            throw new Error([
                `Test Scenarios for rule ${ruleName} is invalid:`
            ].concat(scenarioErrors).join("\n"));
        }

        const baseConfig = [
            { files: ["**"] }, // Make sure the default config matches for all files
            {
                plugins: {

                    // copy root plugin over
                    "@": {

                        /*
                         * Parsers are wrapped to detect more errors, so this needs
                         * to be a new object for each call to run(), otherwise the
                         * parsers will be wrapped multiple times.
                         */
                        parsers: {
                            ...defaultConfig[0].plugins["@"].parsers
                        },

                        /*
                         * The rules key on the default plugin is a proxy to lazy-load
                         * just the rules that are needed. So, don't create a new object
                         * here, just use the default one to keep that performance
                         * enhancement.
                         */
                        rules: defaultConfig[0].plugins["@"].rules
                    },
                    "rule-to-test": {
                        rules: {
                            [ruleName]: Object.assign({}, rule, {

                                // Create a wrapper rule that freezes the `context` properties.
                                create(context) {
                                    freezeDeeply(context.options);
                                    freezeDeeply(context.settings);
                                    freezeDeeply(context.parserOptions);

                                    // freezeDeeply(context.languageOptions);

                                    return (typeof rule === "function" ? rule : rule.create)(context);
                                }
                            })
                        }
                    }
                },
                languageOptions: {
                    ...defaultConfig[0].languageOptions
                }
            },
            ...defaultConfig.slice(1)
        ];

        /**
         * Run the rule for the given item
         * @param {string|Object} item Item to run the rule against
         * @throws {Error} If an invalid schema.
         * @returns {Object} Eslint run result
         * @private
         */
        function runRuleForItem(item) {
            const flatConfigArrayOptions = {
                baseConfig
            };

            if (item.filename) {
                flatConfigArrayOptions.basePath = path.parse(item.filename).root;
            }

            const configs = new FlatConfigArray(testerConfig, flatConfigArrayOptions);

            /*
             * Modify the returned config so that the parser is wrapped to catch
             * access of the start/end properties. This method is called just
             * once per code snippet being tested, so each test case gets a clean
             * parser.
             */
            configs[ConfigArraySymbol.finalizeConfig] = function(...args) {

                // can't do super here :(
                const proto = Object.getPrototypeOf(this);
                const calculatedConfig = proto[ConfigArraySymbol.finalizeConfig].apply(this, args);

                // wrap the parser to catch start/end property access
                calculatedConfig.languageOptions.parser = wrapParser(calculatedConfig.languageOptions.parser);
                return calculatedConfig;
            };

            let code, filename, output, beforeAST, afterAST;

            if (typeof item === "string") {
                code = item;
            } else {
                code = item.code;

                /*
                 * Assumes everything on the item is a config except for the
                 * parameters used by this tester
                 */
                const itemConfig = { ...item };

                for (const parameter of RuleTesterParameters) {
                    delete itemConfig[parameter];
                }

                // wrap any parsers
                if (itemConfig.languageOptions && itemConfig.languageOptions.parser) {

                    const parser = itemConfig.languageOptions.parser;

                    if (parser && typeof parser !== "object") {
                        throw new Error("Parser must be an object with a parse() or parseForESLint() method.");
                    }

                }

                /*
                 * Create the config object from the tester config and this item
                 * specific configurations.
                 */
                configs.push(itemConfig);
            }

            if (item.filename) {
                filename = item.filename;
            }

            let ruleConfig = 1;

            if (hasOwnProperty(item, "options")) {
                assert(Array.isArray(item.options), "options must be an array");
                ruleConfig = [1, ...item.options];
            }

            configs.push({
                rules: {
                    [ruleId]: ruleConfig
                }
            });

            const schema = getRuleOptionsSchema(rule);

            /*
             * Setup AST getters.
             * The goal is to check whether or not AST was modified when
             * running the rule under test.
             */
            configs.push({
                plugins: {
                    "rule-tester": {
                        rules: {
                            "validate-ast": {
                                create() {
                                    return {
                                        Program(node) {
                                            beforeAST = cloneDeeplyExcludesParent(node);
                                        },
                                        "Program:exit"(node) {
                                            afterAST = node;
                                        }
                                    };
                                }
                            }
                        }
                    }
                }
            });

            if (schema) {
                ajv.validateSchema(schema);

                if (ajv.errors) {
                    const errors = ajv.errors.map(error => {
                        const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;

                        return `\t${field}: ${error.message}`;
                    }).join("\n");

                    throw new Error([`Schema for rule ${ruleName} is invalid:`, errors]);
                }

                /*
                 * `ajv.validateSchema` checks for errors in the structure of the schema (by comparing the schema against a "meta-schema"),
                 * and it reports those errors individually. However, there are other types of schema errors that only occur when compiling
                 * the schema (e.g. using invalid defaults in a schema), and only one of these errors can be reported at a time. As a result,
                 * the schema is compiled here separately from checking for `validateSchema` errors.
                 */
                try {
                    ajv.compile(schema);
                } catch (err) {
                    throw new Error(`Schema for rule ${ruleName} is invalid: ${err.message}`);
                }
            }

            // check for validation errors
            try {
                configs.normalizeSync();
                configs.getConfig("test.js");
            } catch (error) {
                error.message = `ESLint configuration in rule-tester is invalid: ${error.message}`;
                throw error;
            }

            // Verify the code.
            const { getComments, applyLanguageOptions, applyInlineConfig, finalize } = SourceCode.prototype;
            const originalCurrentSegments = Object.getOwnPropertyDescriptor(CodePath.prototype, "currentSegments");
            let messages;

            try {
                SourceCode.prototype.getComments = getCommentsDeprecation;
                Object.defineProperty(CodePath.prototype, "currentSegments", {
                    get() {
                        emitCodePathCurrentSegmentsWarning(ruleName);
                        return originalCurrentSegments.get.call(this);
                    }
                });

                forbiddenMethods.forEach(methodName => {
                    SourceCode.prototype[methodName] = throwForbiddenMethodError(methodName, SourceCode.prototype);
                });

                messages = linter.verify(code, configs, filename);
            } finally {
                SourceCode.prototype.getComments = getComments;
                Object.defineProperty(CodePath.prototype, "currentSegments", originalCurrentSegments);
                SourceCode.prototype.applyInlineConfig = applyInlineConfig;
                SourceCode.prototype.applyLanguageOptions = applyLanguageOptions;
                SourceCode.prototype.finalize = finalize;
            }

            const fatalErrorMessage = messages.find(m => m.fatal);

            assert(!fatalErrorMessage, `A fatal parsing error occurred: ${fatalErrorMessage && fatalErrorMessage.message}`);

            // Verify if autofix makes a syntax error or not.
            if (messages.some(m => m.fix)) {
                output = SourceCodeFixer.applyFixes(code, messages).output;
                const errorMessageInFix = linter.verify(output, configs, filename).find(m => m.fatal);

                assert(!errorMessageInFix, [
                    "A fatal parsing error occurred in autofix.",
                    `Error: ${errorMessageInFix && errorMessageInFix.message}`,
                    "Autofix output:",
                    output
                ].join("\n"));
            } else {
                output = code;
            }

            return {
                messages,
                output,
                beforeAST,
                afterAST: cloneDeeplyExcludesParent(afterAST)
            };
        }

        /**
         * Check if the AST was changed
         * @param {ASTNode} beforeAST AST node before running
         * @param {ASTNode} afterAST AST node after running
         * @returns {void}
         * @private
         */
        function assertASTDidntChange(beforeAST, afterAST) {
            if (!equal(beforeAST, afterAST)) {
                assert.fail("Rule should not modify AST.");
            }
        }

        /**
         * Check if the template is valid or not
         * all valid cases go through this
         * @param {string|Object} item Item to run the rule against
         * @returns {void}
         * @private
         */
        function testValidTemplate(item) {
            const code = typeof item === "object" ? item.code : item;

            assert.ok(typeof code === "string", "Test case must specify a string value for 'code'");
            if (item.name) {
                assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string");
            }

            const result = runRuleForItem(item);
            const messages = result.messages;

            assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s",
                messages.length,
                util.inspect(messages)));

            assertASTDidntChange(result.beforeAST, result.afterAST);
        }

        /**
         * Asserts that the message matches its expected value. If the expected
         * value is a regular expression, it is checked against the actual
         * value.
         * @param {string} actual Actual value
         * @param {string|RegExp} expected Expected value
         * @returns {void}
         * @private
         */
        function assertMessageMatches(actual, expected) {
            if (expected instanceof RegExp) {

                // assert.js doesn't have a built-in RegExp match function
                assert.ok(
                    expected.test(actual),
                    `Expected '${actual}' to match ${expected}`
                );
            } else {
                assert.strictEqual(actual, expected);
            }
        }

        /**
         * Check if the template is invalid or not
         * all invalid cases go through this.
         * @param {string|Object} item Item to run the rule against
         * @returns {void}
         * @private
         */
        function testInvalidTemplate(item) {
            assert.ok(typeof item.code === "string", "Test case must specify a string value for 'code'");
            if (item.name) {
                assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string");
            }
            assert.ok(item.errors || item.errors === 0,
                `Did not specify errors for an invalid test of ${ruleName}`);

            if (Array.isArray(item.errors) && item.errors.length === 0) {
                assert.fail("Invalid cases must have at least one error");
            }

            const ruleHasMetaMessages = hasOwnProperty(rule, "meta") && hasOwnProperty(rule.meta, "messages");
            const friendlyIDList = ruleHasMetaMessages ? `[${Object.keys(rule.meta.messages).map(key => `'${key}'`).join(", ")}]` : null;

            const result = runRuleForItem(item);
            const messages = result.messages;

            if (typeof item.errors === "number") {

                if (item.errors === 0) {
                    assert.fail("Invalid cases must have 'error' value greater than 0");
                }

                assert.strictEqual(messages.length, item.errors, util.format("Should have %d error%s but had %d: %s",
                    item.errors,
                    item.errors === 1 ? "" : "s",
                    messages.length,
                    util.inspect(messages)));
            } else {
                assert.strictEqual(
                    messages.length, item.errors.length, util.format(
                        "Should have %d error%s but had %d: %s",
                        item.errors.length,
                        item.errors.length === 1 ? "" : "s",
                        messages.length,
                        util.inspect(messages)
                    )
                );

                const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleId);

                for (let i = 0, l = item.errors.length; i < l; i++) {
                    const error = item.errors[i];
                    const message = messages[i];

                    assert(hasMessageOfThisRule, "Error rule name should be the same as the name of the rule being tested");

                    if (typeof error === "string" || error instanceof RegExp) {

                        // Just an error message.
                        assertMessageMatches(message.message, error);
                    } else if (typeof error === "object" && error !== null) {

                        /*
                         * Error object.
                         * This may have a message, messageId, data, node type, line, and/or
                         * column.
                         */

                        Object.keys(error).forEach(propertyName => {
                            assert.ok(
                                errorObjectParameters.has(propertyName),
                                `Invalid error property name '${propertyName}'. Expected one of ${friendlyErrorObjectParameterList}.`
                            );
                        });

                        if (hasOwnProperty(error, "message")) {
                            assert.ok(!hasOwnProperty(error, "messageId"), "Error should not specify both 'message' and a 'messageId'.");
                            assert.ok(!hasOwnProperty(error, "data"), "Error should not specify both 'data' and 'message'.");
                            assertMessageMatches(message.message, error.message);
                        } else if (hasOwnProperty(error, "messageId")) {
                            assert.ok(
                                ruleHasMetaMessages,
                                "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'."
                            );
                            if (!hasOwnProperty(rule.meta.messages, error.messageId)) {
                                assert(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`);
                            }
                            assert.strictEqual(
                                message.messageId,
                                error.messageId,
                                `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.`
                            );
                            if (hasOwnProperty(error, "data")) {

                                /*
                                 *  if data was provided, then directly compare the returned message to a synthetic
                                 *  interpolated message using the same message ID and data provided in the test.
                                 *  See https://github.com/eslint/eslint/issues/9890 for context.
                                 */
                                const unformattedOriginalMessage = rule.meta.messages[error.messageId];
                                const rehydratedMessage = interpolate(unformattedOriginalMessage, error.data);

                                assert.strictEqual(
                                    message.message,
                                    rehydratedMessage,
                                    `Hydrated message "${rehydratedMessage}" does not match "${message.message}"`
                                );
                            }
                        }

                        assert.ok(
                            hasOwnProperty(error, "data") ? hasOwnProperty(error, "messageId") : true,
                            "Error must specify 'messageId' if 'data' is used."
                        );

                        if (error.type) {
                            assert.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`);
                        }

                        if (hasOwnProperty(error, "line")) {
                            assert.strictEqual(message.line, error.line, `Error line should be ${error.line}`);
                        }

                        if (hasOwnProperty(error, "column")) {
                            assert.strictEqual(message.column, error.column, `Error column should be ${error.column}`);
                        }

                        if (hasOwnProperty(error, "endLine")) {
                            assert.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`);
                        }

                        if (hasOwnProperty(error, "endColumn")) {
                            assert.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`);
                        }

                        if (hasOwnProperty(error, "suggestions")) {

                            // Support asserting there are no suggestions
                            if (!error.suggestions || (Array.isArray(error.suggestions) && error.suggestions.length === 0)) {
                                if (Array.isArray(message.suggestions) && message.suggestions.length > 0) {
                                    assert.fail(`Error should have no suggestions on error with message: "${message.message}"`);
                                }
                            } else {
                                assert.strictEqual(Array.isArray(message.suggestions), true, `Error should have an array of suggestions. Instead received "${message.suggestions}" on error with message: "${message.message}"`);
                                assert.strictEqual(message.suggestions.length, error.suggestions.length, `Error should have ${error.suggestions.length} suggestions. Instead found ${message.suggestions.length} suggestions`);

                                error.suggestions.forEach((expectedSuggestion, index) => {
                                    assert.ok(
                                        typeof expectedSuggestion === "object" && expectedSuggestion !== null,
                                        "Test suggestion in 'suggestions' array must be an object."
                                    );
                                    Object.keys(expectedSuggestion).forEach(propertyName => {
                                        assert.ok(
                                            suggestionObjectParameters.has(propertyName),
                                            `Invalid suggestion property name '${propertyName}'. Expected one of ${friendlySuggestionObjectParameterList}.`
                                        );
                                    });

                                    const actualSuggestion = message.suggestions[index];
                                    const suggestionPrefix = `Error Suggestion at index ${index} :`;

                                    if (hasOwnProperty(expectedSuggestion, "desc")) {
                                        assert.ok(
                                            !hasOwnProperty(expectedSuggestion, "data"),
                                            `${suggestionPrefix} Test should not specify both 'desc' and 'data'.`
                                        );
                                        assert.strictEqual(
                                            actualSuggestion.desc,
                                            expectedSuggestion.desc,
                                            `${suggestionPrefix} desc should be "${expectedSuggestion.desc}" but got "${actualSuggestion.desc}" instead.`
                                        );
                                    }

                                    if (hasOwnProperty(expectedSuggestion, "messageId")) {
                                        assert.ok(
                                            ruleHasMetaMessages,
                                            `${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.`
                                        );
                                        assert.ok(
                                            hasOwnProperty(rule.meta.messages, expectedSuggestion.messageId),
                                            `${suggestionPrefix} Test has invalid messageId '${expectedSuggestion.messageId}', the rule under test allows only one of ${friendlyIDList}.`
                                        );
                                        assert.strictEqual(
                                            actualSuggestion.messageId,
                                            expectedSuggestion.messageId,
                                            `${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.`
                                        );
                                        if (hasOwnProperty(expectedSuggestion, "data")) {
                                            const unformattedMetaMessage = rule.meta.messages[expectedSuggestion.messageId];
                                            const rehydratedDesc = interpolate(unformattedMetaMessage, expectedSuggestion.data);

                                            assert.strictEqual(
                                                actualSuggestion.desc,
                                                rehydratedDesc,
                                                `${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".`
                                            );
                                        }
                                    } else {
                                        assert.ok(
                                            !hasOwnProperty(expectedSuggestion, "data"),
                                            `${suggestionPrefix} Test must specify 'messageId' if 'data' is used.`
                                        );
                                    }

                                    if (hasOwnProperty(expectedSuggestion, "output")) {
                                        const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [actualSuggestion]).output;

                                        assert.strictEqual(codeWithAppliedSuggestion, expectedSuggestion.output, `Expected the applied suggestion fix to match the test suggestion output for suggestion at index: ${index} on error with message: "${message.message}"`);
                                    }
                                });
                            }
                        }
                    } else {

                        // Message was an unexpected type
                        assert.fail(`Error should be a string, object, or RegExp, but found (${util.inspect(message)})`);
                    }
                }
            }

            if (hasOwnProperty(item, "output")) {
                if (item.output === null) {
                    assert.strictEqual(
                        result.output,
                        item.code,
                        "Expected no autofixes to be suggested"
                    );
                } else {
                    assert.strictEqual(result.output, item.output, "Output is incorrect.");
                }
            } else {
                assert.strictEqual(
                    result.output,
                    item.code,
                    "The rule fixed the code. Please add 'output' property."
                );
            }

            assertASTDidntChange(result.beforeAST, result.afterAST);
        }

        /*
         * This creates a mocha test suite and pipes all supplied info through
         * one of the templates above.
         * The test suites for valid/invalid are created conditionally as
         * test runners (eg. vitest) fail for empty test suites.
         */
        this.constructor.describe(ruleName, () => {
            if (test.valid.length > 0) {
                this.constructor.describe("valid", () => {
                    test.valid.forEach(valid => {
                        this.constructor[valid.only ? "itOnly" : "it"](
                            sanitize(typeof valid === "object" ? valid.name || valid.code : valid),
                            () => {
                                testValidTemplate(valid);
                            }
                        );
                    });
                });
            }

            if (test.invalid.length > 0) {
                this.constructor.describe("invalid", () => {
                    test.invalid.forEach(invalid => {
                        this.constructor[invalid.only ? "itOnly" : "it"](
                            sanitize(invalid.name || invalid.code),
                            () => {
                                testInvalidTemplate(invalid);
                            }
                        );
                    });
                });
            }
        });
    }
}

FlatRuleTester[DESCRIBE] = FlatRuleTester[IT] = FlatRuleTester[IT_ONLY] = null;

module.exports = FlatRuleTester;


code:
"use strict";

module.exports = {
    RuleTester: require("./rule-tester")
};