{"path":"data.jsonl","content":"{\"instruction\":\"Write an ESLint rule 'component-function-max-lines.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils } from \\\"@typescript-eslint/utils\\\";\\nimport type { TSESTree } from \\\"@typescript-eslint/utils\\\";\\nimport { RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\n\\nconst url = \\\"https://example.com/rules/\\\";\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${url}${ruleName}`);\\n\\nfunction isMultilineFunction(\\n node: TSESTree.FunctionDeclaration | TSESTree.FunctionExpression | TSESTree.ArrowFunctionExpression,\\n) {\\n return node.body.type === \\\"BlockStatement\\\" && node.body.body.length > 1;\\n}\\n\\ntype AnyFunctionNode =\\n | TSESTree.FunctionDeclaration\\n | TSESTree.FunctionExpression\\n | TSESTree.ArrowFunctionExpression;\\n\\nfunction isComponentLikeFunction(node: AnyFunctionNode | null) {\\n if (typeof node?.body?.type !== \\\"string\\\" || node.body.type !== \\\"BlockStatement\\\") return false;\\n\\n return node.body.body.some((statement) => {\\n return (\\n statement.type === \\\"ReturnStatement\\\" &&\\n statement.argument &&\\n (statement.argument.type === \\\"JSXElement\\\" || statement.argument.type === \\\"JSXFragment\\\")\\n );\\n });\\n}\\n\\nfunction isComponentFunction(node: AnyFunctionNode | null) {\\n if (!node) return false;\\n\\n if (!isComponentLikeFunction(node)) return false;\\n\\n const parent = node.parent;\\n\\n if (parent?.type === \\\"VariableDeclarator\\\" && parent.id.type === \\\"Identifier\\\") {\\n return true;\\n }\\n\\n return (\\n node.type === \\\"FunctionDeclaration\\\" &&\\n (parent?.type === \\\"ExportNamedDeclaration\\\" ||\\n parent?.type === \\\"ExportDefaultDeclaration\\\" ||\\n parent?.type === \\\"Program\\\")\\n );\\n}\\n\\nfunction isInsideComponentFunction(node: TSESTree.Node | null) {\\n let currentNode = node;\\n while (currentNode) {\\n if (\\n currentNode.type === \\\"FunctionDeclaration\\\" ||\\n currentNode.type === \\\"FunctionExpression\\\" ||\\n currentNode.type === \\\"ArrowFunctionExpression\\\"\\n ) {\\n if (isComponentLikeFunction(currentNode)) return true;\\n }\\n\\n currentNode = currentNode.parent ?? null;\\n }\\n return false;\\n}\\n\\nconst componentFunctionMaxLines = createRule({\\n name: \\\"component-function-max-lines\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Functions declared inside components can have maximum 1 line\\\",\\n },\\n messages: {\\n componentFunctionMaxLines: \\\"Functions declared inside components can have maximum 1 line\\\",\\n },\\n schema: [],\\n },\\n create(context: RuleContext<\\\"componentFunctionMaxLines\\\", []>) {\\n return {\\n ArrowFunctionExpression(node) {\\n if (\\n !isComponentFunction(node) &&\\n isInsideComponentFunction(node.parent) &&\\n isMultilineFunction(node)\\n ) {\\n context.report({ node, messageId: \\\"componentFunctionMaxLines\\\" });\\n }\\n },\\n FunctionExpression(node) {\\n if (\\n !isComponentFunction(node) &&\\n isInsideComponentFunction(node.parent) &&\\n isMultilineFunction(node)\\n ) {\\n context.report({ node, messageId: \\\"componentFunctionMaxLines\\\" });\\n }\\n },\\n FunctionDeclaration(node) {\\n if (\\n !isComponentFunction(node) &&\\n isInsideComponentFunction(node.parent) &&\\n isMultilineFunction(node)\\n ) {\\n context.report({ node, messageId: \\\"componentFunctionMaxLines\\\" });\\n }\\n },\\n\\n JSXExpressionContainer(node) {\\n const expr = node.expression;\\n\\n if (\\n expr &&\\n expr.type === \\\"CallExpression\\\" &&\\n expr.callee.type === \\\"ArrowFunctionExpression\\\" &&\\n !isComponentFunction(expr.callee) &&\\n isMultilineFunction(expr.callee) &&\\n isInsideComponentFunction(node.parent)\\n ) {\\n context.report({ node, messageId: \\\"componentFunctionMaxLines\\\" });\\n }\\n },\\n };\\n },\\n defaultOptions: [],\\n});\\n\\nexport default componentFunctionMaxLines;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport rule from \\\"@root/rules/component-function-max-lines\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n export const Component1 = () => {\\n const oneLineFunc = () => 42; // Ок\\n return
{oneLineFunc()}
;\\n };\\n `,\\n },\\n {\\n code: `\\n export const Component2 = () =>
Hello
;\\n `,\\n },\\n {\\n code: `\\n export const Component3 = () => {\\n function oneLineFunc() {\\n return 10;\\n }\\n\\n return
{oneLineFunc()}
;\\n };\\n `,\\n },\\n {\\n code: `\\n function outsideFunc() {\\n const x = 1;\\n return x + 1;\\n }\\n \\n export const Component4 = () => {\\n return
{outsideFunc()}
;\\n };\\n `,\\n },\\n {\\n code: `\\n const Component5 = () => {\\n const [a, setA] = useState();\\n const [b, setB] = useState();\\n return
;\\n };\\n `,\\n },\\n {\\n code: `\\n const Component6 = () => {\\n const handleClick = () => alert('test');\\n return
;\\n };\\n `,\\n },\\n {\\n code: `\\n function Component7() {\\n return
Valid function component
;\\n }\\n `,\\n },\\n {\\n code: `\\n export function Component8() {\\n return
Exported valid component
;\\n }\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n export const InvalidComponent1 = () => {\\n const multiLineFunc = () => {\\n const x = 5;\\n return x * 2;\\n };\\n return
{multiLineFunc()}
;\\n };\\n `,\\n errors: [{ messageId: \\\"componentFunctionMaxLines\\\" }],\\n },\\n {\\n code: `\\n export const InvalidComponent2 = () => {\\n function complexFunc() {\\n const a = 1;\\n const b = 2;\\n return a + b;\\n }\\n\\n return
{complexFunc()}
;\\n };\\n `,\\n errors: [{ messageId: \\\"componentFunctionMaxLines\\\" }],\\n },\\n {\\n code: `\\n export const InvalidComponent3 = () => {\\n return (\\n
\\n {(() => {\\n const y = 3;\\n return y + 4;\\n })()}\\n
\\n );\\n };\\n `,\\n errors: [{ messageId: \\\"componentFunctionMaxLines\\\" }, { messageId: \\\"componentFunctionMaxLines\\\" }],\\n },\\n {\\n code: `\\n const InvalidComponent4 = () => {\\n const handleSubmit = () => {\\n console.log('line 1');\\n console.log('line 2');\\n };\\n \\n return
;\\n };\\n `,\\n errors: [{ messageId: \\\"componentFunctionMaxLines\\\" }],\\n },\\n {\\n code: `\\n function InvalidComponent5() {\\n function complexFunc() {\\n const a = 1;\\n const b = 2;\\n return a + b;\\n }\\n\\n return
{complexFunc()}
;\\n }\\n `,\\n errors: [{ messageId: \\\"componentFunctionMaxLines\\\" }],\\n },\\n {\\n code: `\\n export default function InvalidComponent6() {\\n function complexFunc() {\\n const a = 1;\\n const b = 2;\\n return a + b;\\n }\\n\\n return
{complexFunc()}
;\\n }\\n `,\\n errors: [{ messageId: \\\"componentFunctionMaxLines\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"component-function-max-lines\\\", rule, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'exported-func-above-regular.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, AST_NODE_TYPES } from \\\"@typescript-eslint/utils\\\";\\nimport { RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\n\\nconst url = \\\"https://example.com/rules/\\\";\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${url}${ruleName}`);\\n\\nconst exportedFuncAboveRegular = createRule({\\n name: \\\"exported-func-above-regular\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Ensure exported functions are defined above regular functions.\\\",\\n },\\n messages: {\\n exportedFuncAboveRegular: \\\"Exported functions should be defined above regular functions.\\\",\\n },\\n schema: [],\\n },\\n\\n create(context: RuleContext<\\\"exportedFuncAboveRegular\\\", []>) {\\n let seenNonExport = false;\\n return {\\n Program(node) {\\n for (const stmt of node.body) {\\n if (\\n stmt.type === AST_NODE_TYPES.ExportNamedDeclaration ||\\n stmt.type === AST_NODE_TYPES.ExportAllDeclaration\\n ) {\\n if (seenNonExport) {\\n context.report({\\n node: stmt,\\n messageId: \\\"exportedFuncAboveRegular\\\",\\n });\\n }\\n } else if (stmt.type !== AST_NODE_TYPES.ImportDeclaration) {\\n seenNonExport = true;\\n }\\n }\\n },\\n };\\n },\\n defaultOptions: [],\\n});\\n\\nexport default exportedFuncAboveRegular;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport rule from \\\"@root/rules/exported-func-above-regular\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n export const foo = 1;\\n export function bar() {}\\n export default function main() {}\\n\\n const helper = () => {\\n };\\n\\n console.log(foo, bar());\\n `,\\n },\\n {\\n code: `\\n export const a = 1;\\n export const b = 2;\\n\\n\\n const c = a + b;\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n const x = 1;\\n\\n export const something = 42;\\n\\n `,\\n errors: [{ messageId: \\\"exportedFuncAboveRegular\\\" }],\\n },\\n {\\n code: `\\n const a = 5;\\n\\n function internal() {\\n }\\n\\n export const foo = a + 1;\\n `,\\n errors: [{ messageId: \\\"exportedFuncAboveRegular\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"exported-func-above-regular\\\", rule, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'filename-kebab-case.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils } from \\\"@typescript-eslint/utils\\\";\\nimport { RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\nimport path from \\\"path\\\";\\n\\nconst url = \\\"https://example.com/rules/\\\";\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${url}${ruleName}`);\\n\\nconst virtualFilename = \\\"input-file\\\";\\nconst ignoredFilenames = [\\n \\\"README\\\",\\n \\\"README.md\\\",\\n \\\"LICENSE\\\",\\n \\\"Makefile\\\",\\n \\\".env\\\",\\n \\\".gitignore\\\",\\n \\\".eslintrc.js\\\",\\n \\\".prettierrc\\\",\\n \\\".prettierignore\\\",\\n];\\n\\nfunction isKebabCase(fileName: string) {\\n let isValid: boolean;\\n\\n if (ignoredFilenames.includes(fileName)) {\\n isValid = true;\\n } else {\\n const fileBaseName = path.basename(fileName, path.extname(fileName));\\n const mainName = fileBaseName.split(\\\".\\\")[0];\\n\\n if (!mainName) {\\n isValid = false;\\n } else {\\n isValid = /^[a-z0-9]+([-.][a-z0-9]+)*(\\\\.[a-z]+)?$/.test(mainName);\\n }\\n }\\n\\n return isValid;\\n}\\n\\nconst kebabCaseFilenames = createRule({\\n name: \\\"filename-kebab-case\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Enforce kebab case for file names\\\",\\n },\\n messages: {\\n useKebabCase: \\\"Filename '{{fileName}}' must be in kebab-case format\\\",\\n },\\n schema: [],\\n },\\n create(context: RuleContext<\\\"useKebabCase\\\", []>) {\\n const filePath = context.filename;\\n const fileName = path.basename(filePath);\\n\\n const result = {};\\n\\n if (fileName !== virtualFilename && !isKebabCase(fileName)) {\\n context.report({\\n loc: { line: 1, column: 0 },\\n messageId: \\\"useKebabCase\\\",\\n data: { fileName },\\n });\\n }\\n\\n return result;\\n },\\n defaultOptions: [],\\n});\\n\\nexport default kebabCaseFilenames;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport kebabCaseFilenames from \\\"@root/rules/filename-kebab-case\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n //my-component.ts\\n export const a = 1;`,\\n filename: \\\"my-component.ts\\\",\\n },\\n {\\n code: `\\n //another-file-name.js\\n console.log('ok')`,\\n filename: \\\"another-file-name.js\\\",\\n },\\n {\\n code: `\\n //input-file\\n const x = 42;`,\\n filename: \\\"input-file\\\",\\n },\\n {\\n code: `\\n //component.ts\\n const x = 24;`,\\n filename: \\\"component.ts\\\",\\n },\\n {\\n code: `\\n //my-component.spec.ts\\n export const a = 1;`,\\n filename: \\\"my-component.spec.ts\\\",\\n },\\n {\\n code: `\\n //component.spec.ts\\n const x = 24;`,\\n filename: \\\"component.spec.ts\\\",\\n },\\n {\\n code: `\\n //README\\n console.log('good')`,\\n filename: \\\"README\\\",\\n },\\n\\n {\\n code: `\\n //.env\\n console.log('good')`,\\n filename: \\\".env\\\",\\n },\\n {\\n code: `\\n //.eslintrc.js\\n console.log('good')`,\\n filename: \\\".eslintrc.js\\\",\\n },\\n {\\n code: `\\n //eslint.config.js\\n console.log('good')`,\\n filename: \\\"eslint.config.js\\\",\\n },\\n {\\n code: `\\n //.gitignore\\n console.log('good')`,\\n filename: \\\".gitignore\\\",\\n },\\n {\\n code: `\\n //.prettierignore\\n console.log('good')`,\\n filename: \\\".prettierignore\\\",\\n },\\n {\\n code: `\\n //my-component.name.ts\\n console.log('good')`,\\n filename: \\\"my-component.name.ts\\\",\\n },\\n {\\n code: `\\n //component123.ts\\n console.log('good')`,\\n filename: \\\"component123.ts\\\",\\n },\\n {\\n code: `\\n //component123.spec.ts\\n console.log('good')`,\\n filename: \\\"component123.spec.ts\\\",\\n },\\n {\\n code: `\\n //index.d.ts\\n console.log('good')`,\\n filename: \\\"index.d.ts\\\",\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n //MyComponent.ts\\n export const A = 1;`,\\n filename: \\\"MyComponent.ts\\\",\\n errors: [{ messageId: \\\"useKebabCase\\\" }],\\n },\\n {\\n code: `\\n //myComponent.ts\\n export default function() {};`,\\n filename: \\\"myComponent.ts\\\",\\n errors: [{ messageId: \\\"useKebabCase\\\" }],\\n },\\n {\\n code: `\\n //snake_case.ts\\n console.log('bad')`,\\n filename: \\\"snake_case.ts\\\",\\n errors: [{ messageId: \\\"useKebabCase\\\" }],\\n },\\n {\\n code: `\\n //MyComponent.spec.ts\\n export const A = 1;`,\\n filename: \\\"MyComponent.spec.ts\\\",\\n errors: [{ messageId: \\\"useKebabCase\\\" }],\\n },\\n {\\n code: `\\n //myComponent.spec.ts\\n export default function() {};`,\\n filename: \\\"myComponent.spec.ts\\\",\\n errors: [{ messageId: \\\"useKebabCase\\\" }],\\n },\\n {\\n code: `\\n //snake_case.spec.ts\\n console.log('bad')`,\\n filename: \\\"snake_case.spec.ts\\\",\\n errors: [{ messageId: \\\"useKebabCase\\\" }],\\n },\\n {\\n code: `\\n //src/components/MyComponent.ts\\n console.log('good')`,\\n filename: \\\"src/components/MyComponent.ts\\\",\\n errors: [{ messageId: \\\"useKebabCase\\\" }],\\n },\\n {\\n code: `\\n //src/components/MyComponent.spec.ts\\n console.log('good')`,\\n filename: \\\"src/components/MyComponent.spec.ts\\\",\\n errors: [{ messageId: \\\"useKebabCase\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"use-kebab-case\\\", kebabCaseFilenames, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'for-each-max-lines.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree } from \\\"@typescript-eslint/utils\\\";\\nimport { RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\n\\nconst url = \\\"https://example.com/rules/\\\";\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${url}${ruleName}`);\\n\\nconst forEachMaxLines = createRule({\\n name: \\\"for-each-max-lines\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"forEach blocks can have maximum 3 lines\\\",\\n },\\n messages: {\\n forEachMaxLines: \\\"forEach blocks can have maximum 3 lines\\\",\\n },\\n schema: [\\n {\\n type: \\\"object\\\",\\n properties: {\\n maxStatements: {\\n type: \\\"integer\\\",\\n minimum: 1,\\n default: 3,\\n },\\n },\\n additionalProperties: false,\\n },\\n ],\\n },\\n create(context: RuleContext<\\\"forEachMaxLines\\\", [{ maxStatements: number }]>) {\\n function checkForEach(node: TSESTree.CallExpression) {\\n const options = context.options[0] ?? { maxStatements: 3 };\\n\\n if (node.arguments.length > 0) {\\n const callback = node.arguments[0];\\n\\n if (callback?.type === \\\"ArrowFunctionExpression\\\" || callback?.type === \\\"FunctionExpression\\\") {\\n const body =\\n callback.body.type === \\\"BlockStatement\\\" ? callback.body.body : [callback.body];\\n\\n if (body.length > options.maxStatements) {\\n context.report({ node, messageId: \\\"forEachMaxLines\\\" });\\n }\\n }\\n }\\n }\\n\\n return {\\n CallExpression(node: TSESTree.CallExpression) {\\n if (\\n node.callee.type === \\\"MemberExpression\\\" &&\\n node.callee.property.type === \\\"Identifier\\\" &&\\n node.callee.property.name === \\\"forEach\\\"\\n ) {\\n checkForEach(node);\\n }\\n },\\n };\\n },\\n defaultOptions: [{ maxStatements: 3 }],\\n});\\n\\nexport default forEachMaxLines;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport forEachMaxLines from \\\"@root/rules/for-each-max-lines\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n [1, 2, 3].forEach(item => {\\n console.log(item);\\n });\\n `,\\n },\\n {\\n code: `\\n [1, 2, 3].forEach(item => {\\n const a = item * 2;\\n console.log(a);\\n });\\n `,\\n },\\n {\\n code: `\\n [1, 2, 3].forEach(item => {\\n const a = item * 2;\\n const b = item + 1;\\n console.log(b);\\n });\\n `,\\n },\\n {\\n code: `\\n [1, 2, 3].forEach(function(item) {\\n console.log(item);\\n });\\n `,\\n },\\n {\\n code: `\\n [1, 2, 3].forEach(function(item) {\\n const a = item * 2;\\n console.log(a);\\n });\\n `,\\n },\\n {\\n code: `\\n [1, 2, 3].forEach(function(item) {\\n const a = item * 2;\\n const b = item + 1;\\n console.log(b);\\n });\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n [1, 2, 3].forEach(item => {\\n const a = item * 2;\\n const b = item + 1;\\n const c = b - 1;\\n console.log(b);\\n });\\n `,\\n errors: [{ messageId: \\\"forEachMaxLines\\\" }],\\n },\\n {\\n code: `\\n [1, 2, 3].forEach(item => {\\n console.log(item);\\n console.log(\\\"four\\\");\\n console.log(\\\"items\\\");\\n console.log(\\\"long\\\");\\n });\\n `,\\n errors: [{ messageId: \\\"forEachMaxLines\\\" }],\\n },\\n {\\n code: `\\n [1, 2, 3].forEach(function(item) {\\n const a = item * 2;\\n const b = item + 1;\\n const c = b - 1;\\n console.log(b);\\n });\\n `,\\n errors: [{ messageId: \\\"forEachMaxLines\\\" }],\\n },\\n {\\n code: `\\n [1, 2, 3].forEach(function(item) {\\n console.log(item);\\n console.log(\\\"four\\\");\\n console.log(\\\"items\\\");\\n console.log(\\\"long\\\");\\n });\\n `,\\n errors: [{ messageId: \\\"forEachMaxLines\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"for-each-max-lines\\\", forEachMaxLines, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'group-consts-as-const.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree, AST_NODE_TYPES } from \\\"@typescript-eslint/utils\\\";\\nimport { RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\n\\nconst url = \\\"https://example.com/rules/\\\";\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${url}${ruleName}`);\\n\\nconst minCountofConsts = 2;\\n\\nconst groupConstsAsConst = createRule({\\n name: \\\"group-consts-as-const\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Group constants in a single object with as const\\\",\\n },\\n messages: {\\n groupConstsAsConst: \\\"Write constants in separated object with as const\\\",\\n },\\n schema: [],\\n },\\n create(context: RuleContext<\\\"groupConstsAsConst\\\", []>) {\\n return {\\n Program(node: TSESTree.Program) {\\n const body = node.body;\\n let group: TSESTree.ExportNamedDeclaration[] = [];\\n\\n const isConstLiteralExport = (stmt: TSESTree.Statement) => {\\n return (\\n stmt.type === AST_NODE_TYPES.ExportNamedDeclaration &&\\n stmt.declaration?.type === AST_NODE_TYPES.VariableDeclaration &&\\n stmt.declaration.kind === \\\"const\\\" &&\\n stmt.declaration.declarations.length === 1 &&\\n (() => {\\n const init = stmt.declaration!.declarations[0]?.init;\\n return (\\n init?.type === AST_NODE_TYPES.Literal ||\\n (init?.type === AST_NODE_TYPES.TemplateLiteral &&\\n init.expressions.length === 0)\\n );\\n })()\\n );\\n };\\n\\n for (let i = 0; i <= body.length; i++) {\\n const stmt = body[i];\\n\\n if (stmt && isConstLiteralExport(stmt)) {\\n group.push(stmt as TSESTree.ExportNamedDeclaration);\\n } else {\\n if (group.length >= minCountofConsts) {\\n for (const g of group) {\\n context.report({\\n node: g,\\n messageId: \\\"groupConstsAsConst\\\",\\n });\\n }\\n }\\n\\n group = [];\\n }\\n }\\n },\\n };\\n },\\n defaultOptions: [],\\n});\\n\\nexport default groupConstsAsConst;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport groupConstsAsConst from \\\"@root/rules/group-consts-as-const\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n export const foo = \\\"Foo\\\";\\n `,\\n },\\n {\\n code: `\\n export const quxes = {\\n foo: \\\"Foo\\\",\\n bar: \\\"Bar\\\",\\n baz: \\\"Baz\\\",\\n } as const;\\n `,\\n },\\n {\\n code: `\\n export let foo = \\\"Foo\\\";\\n export var bar = \\\"Bar\\\";\\n `,\\n },\\n {\\n code: `\\n const foo = \\\"Foo\\\";\\n const bar = \\\"Bar\\\";\\n `,\\n },\\n\\n {\\n code: `\\n export const foo = \\\"Foo\\\";\\n let baz = \\\"Baz\\\";\\n export const bar = \\\"Bar\\\";\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n export const foo = \\\"Foo\\\";\\n export const bar = \\\"Bar\\\";\\n `,\\n errors: [{ messageId: \\\"groupConstsAsConst\\\" }, { messageId: \\\"groupConstsAsConst\\\" }],\\n },\\n {\\n code: `\\n export const foo = \\\"Foo\\\";\\n\\n export const bar = \\\"Bar\\\";\\n `,\\n errors: [{ messageId: \\\"groupConstsAsConst\\\" }, { messageId: \\\"groupConstsAsConst\\\" }],\\n },\\n {\\n code: `\\n export const foo = \\\"Foo\\\"; // comment\\n export const bar = \\\"Bar\\\";\\n `,\\n errors: [{ messageId: \\\"groupConstsAsConst\\\" }, { messageId: \\\"groupConstsAsConst\\\" }],\\n },\\n\\n {\\n code: `\\n export const single = \\\"OnlyOne\\\";\\n\\n export const foo = \\\"Foo\\\";\\n export const bar = \\\"Bar\\\";\\n `,\\n errors: [\\n { messageId: \\\"groupConstsAsConst\\\" },\\n { messageId: \\\"groupConstsAsConst\\\" },\\n { messageId: \\\"groupConstsAsConst\\\" },\\n ],\\n },\\n {\\n code: `\\n export const foo = \\\"Foo\\\";\\n export const bar = \\\"Bar\\\";\\n export const baz = \\\"Baz\\\";\\n `,\\n errors: [\\n { messageId: \\\"groupConstsAsConst\\\" },\\n { messageId: \\\"groupConstsAsConst\\\" },\\n { messageId: \\\"groupConstsAsConst\\\" },\\n ],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"group-consts-as-const\\\", groupConstsAsConst, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'must-add-space-for-comments.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree } from \\\"@typescript-eslint/utils\\\";\\nimport { RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\n\\nconst constants = {\\n url: \\\"https://example.com/rules/\\\",\\n ruleName: \\\"must-add-space-for-comments\\\",\\n messageIds: {\\n missingSpace: \\\"missingSpace\\\",\\n },\\n meta: {\\n type: \\\"suggestion\\\",\\n docs: {\\n description: \\\"Enforce a space after // in single-line comments, excluding ///, //!, //_#\\\",\\n },\\n messages: {\\n missingSpace: \\\"Add a space after '//'.\\\",\\n },\\n schema: [],\\n fixable: \\\"whitespace\\\",\\n },\\n commentTypes: {\\n line: \\\"Line\\\",\\n },\\n regexPatterns: {\\n missingSpaceAfterDoubleSlash: \\\"^//[^/\\\\\\\\s!#]\\\",\\n },\\n chars: {\\n space: \\\" \\\",\\n },\\n} as const;\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${constants.url}${ruleName}`);\\n\\nconst mustAddSpaceForComments = createRule<[], typeof constants.messageIds.missingSpace>({\\n name: constants.ruleName,\\n meta: constants.meta,\\n defaultOptions: [],\\n\\n create(context: RuleContext) {\\n return {\\n Program() {\\n const sourceCode = context.sourceCode;\\n const comments = sourceCode.getAllComments();\\n const regex = new RegExp(constants.regexPatterns.missingSpaceAfterDoubleSlash);\\n\\n comments.forEach((comment: TSESTree.Comment) => {\\n const commentText = sourceCode.getText(comment);\\n\\n if (comment.type === constants.commentTypes.line && regex.test(commentText)) {\\n context.report({\\n node: comment,\\n messageId: constants.messageIds.missingSpace,\\n\\n fix(fixer) {\\n return fixer.insertTextAfterRange(\\n [comment.range[0], comment.range[0] + 2],\\n constants.chars.space,\\n );\\n },\\n });\\n }\\n });\\n },\\n };\\n },\\n});\\n\\nexport default mustAddSpaceForComments;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport mustAddSpaceForComments from \\\"@root/rules/must-add-space-for-comments\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `// This is a foo comment`,\\n },\\n {\\n code: `// Here are bar spaces`,\\n },\\n {\\n code: `/// `,\\n },\\n {\\n code: `//! This is a foo directive`, // Special directive comment\\n },\\n {\\n code: `//# This is a bar region`,\\n },\\n {\\n code: `//`,\\n },\\n {\\n code: `\\n/*\\n * This is a baz block comment\\n */\\nconst x = 1;`,\\n },\\n {\\n code: `//\\\\tFoo comment with a tab`,\\n },\\n {\\n code: `const noCommentsFoo = true;`,\\n },\\n {\\n code: `//// Four slashes, then a space (bar)`,\\n },\\n {\\n code: `////fourSlashesNoSpaceButOkBaz`,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `//noSpaceFoo`,\\n output: `// noSpaceFoo`,\\n errors: [{ messageId: \\\"missingSpace\\\" }],\\n },\\n {\\n code: `const foo = 10; //noSpaceBar`,\\n output: `const foo = 10; // noSpaceBar`,\\n errors: [{ messageId: \\\"missingSpace\\\" }],\\n },\\n {\\n code: `//SOME_TEXT_BAZ();`,\\n output: `// SOME_TEXT_BAZ();`,\\n errors: [{ messageId: \\\"missingSpace\\\" }],\\n },\\n {\\n code: `\\n//firstNoSpaceFoo\\n// second with space Bar\\n//!thisShouldBeSkippedBaz\\n//#thisTooShouldBeSkippedQux\\n//thirdNoSpaceQuux\\nconst y = 20; //andThisOneNoSpaceCorge\\n`,\\n output: `\\n// firstNoSpaceFoo\\n// second with space Bar\\n//!thisShouldBeSkippedBaz\\n//#thisTooShouldBeSkippedQux\\n// thirdNoSpaceQuux\\nconst y = 20; // andThisOneNoSpaceCorge\\n`,\\n errors: [\\n { messageId: \\\"missingSpace\\\", line: 2, column: 1 },\\n { messageId: \\\"missingSpace\\\", line: 6, column: 1 },\\n { messageId: \\\"missingSpace\\\", line: 7, column: 15 },\\n ],\\n },\\n {\\n code: `\\n //badFoo\\n //okBar\\n //!skipBaz\\n //#skipQux\\n `,\\n output: `\\n // badFoo\\n // okBar\\n //!skipBaz\\n //#skipQux\\n `,\\n errors: [\\n { messageId: \\\"missingSpace\\\", line: 2, column: 9 },\\n { messageId: \\\"missingSpace\\\", line: 3, column: 9 },\\n ],\\n },\\n {\\n code: `//+specialCharFoo`,\\n output: `// +specialCharFoo`,\\n errors: [{ messageId: \\\"missingSpace\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\n\\nrunTests(\\\"must-add-space-for-comments\\\", mustAddSpaceForComments, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'must-clean-up-event-listeners.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree, type TSESLint } from \\\"@typescript-eslint/utils\\\";\\n\\nconst ruleConstants = {\\n ruleName: \\\"must-clean-up-event-listeners\\\",\\n urlBase: \\\"https://example.com/rules/\\\",\\n description: \\\"Ensure that event listeners are properly removed in the cleanup function.\\\",\\n errorMessage:\\n \\\"Missing cleanup: {{element}}.removeEventListener('{{event}}', {{callback}}) is not called.\\\",\\n messageId: \\\"mustCleanUpEventListeners\\\",\\n nodeTypes: {\\n blockStatement: \\\"BlockStatement\\\",\\n expressionStatement: \\\"ExpressionStatement\\\",\\n returnStatement: \\\"ReturnStatement\\\",\\n ifStatement: \\\"IfStatement\\\",\\n callExpression: \\\"CallExpression\\\",\\n arrayExpression: \\\"ArrayExpression\\\",\\n memberExpression: \\\"MemberExpression\\\",\\n objectExpression: \\\"ObjectExpression\\\",\\n funcExpression: \\\"FunctionExpression\\\",\\n arrowFuncExpression: \\\"ArrowFunctionExpression\\\",\\n unaryExpression: \\\"UnaryExpression\\\",\\n identifier: \\\"Identifier\\\",\\n literal: \\\"Literal\\\",\\n },\\n listenersTypes: { remove: \\\"removeEventListener\\\", add: \\\"addEventListener\\\" },\\n useEffectTypes: { default: \\\"useEffect\\\" },\\n} as const;\\n\\ntype MessageIds = typeof ruleConstants.messageId;\\ntype Options = [];\\n\\ninterface EventListener {\\n element: TSESTree.Identifier;\\n event: TSESTree.Literal;\\n callback: TSESTree.ArrowFunctionExpression | TSESTree.Identifier;\\n optional?: TSESTree.Literal | TSESTree.ObjectExpression | TSESTree.Identifier;\\n}\\n\\ninterface EventListenerInfo extends EventListener {\\n node: TSESTree.CallExpression;\\n}\\n\\nconst { RuleCreator: ruleCreator } = ESLintUtils;\\nconst createRule = ruleCreator((name: string) => `${ruleConstants.urlBase}${name}`);\\n\\nfunction isValidCallExpression(node: TSESTree.Node, expectedMethod: string): node is TSESTree.CallExpression {\\n return (\\n node.type === ruleConstants.nodeTypes.callExpression &&\\n node.callee.type === ruleConstants.nodeTypes.memberExpression &&\\n node.callee.property.type === ruleConstants.nodeTypes.identifier &&\\n node.callee.property.name === expectedMethod &&\\n node.callee.object.type === ruleConstants.nodeTypes.identifier &&\\n node.arguments.length >= 2\\n );\\n}\\n\\nfunction isValidCallback(\\n node: TSESTree.Node,\\n): node is TSESTree.ArrowFunctionExpression | TSESTree.Identifier {\\n return (\\n node.type === ruleConstants.nodeTypes.identifier ||\\n node.type === ruleConstants.nodeTypes.funcExpression ||\\n node.type === ruleConstants.nodeTypes.arrowFuncExpression\\n );\\n}\\n\\nfunction isValidOptional(\\n node: TSESTree.Node,\\n): node is TSESTree.Literal | TSESTree.ObjectExpression | TSESTree.Identifier {\\n return (\\n node.type === ruleConstants.nodeTypes.literal ||\\n node.type === ruleConstants.nodeTypes.identifier ||\\n node.type === ruleConstants.nodeTypes.objectExpression\\n );\\n}\\n\\nfunction createEventListener(\\n node: TSESTree.CallExpression,\\n event: TSESTree.CallExpressionArgument,\\n callback: TSESTree.CallExpressionArgument,\\n optionalArg?: TSESTree.CallExpressionArgument,\\n): EventListener | null {\\n if (\\n node.callee.type !== ruleConstants.nodeTypes.memberExpression ||\\n node.callee.object.type !== ruleConstants.nodeTypes.identifier ||\\n event.type !== ruleConstants.nodeTypes.literal ||\\n !isValidCallback(callback)\\n )\\n return null;\\n\\n const result: EventListener = { element: node.callee.object, event: event, callback: callback };\\n\\n if (optionalArg && isValidOptional(optionalArg)) result.optional = optionalArg;\\n\\n return result;\\n}\\n\\nfunction isMatchingEventListenerCall(\\n node: TSESTree.Node,\\n expectedMethod: \\\"addEventListener\\\" | \\\"removeEventListener\\\",\\n): EventListener | null {\\n if (!isValidCallExpression(node, expectedMethod)) return null;\\n\\n const [event, callback, optionalArg] = node.arguments;\\n\\n if (!event || !callback) return null;\\n\\n if (event.type !== ruleConstants.nodeTypes.literal || !isValidCallback(callback)) return null;\\n\\n return createEventListener(node, event, callback, optionalArg);\\n}\\n\\nfunction normalizeText(code: string): string {\\n return code.replace(/\\\\s/g, \\\"\\\");\\n}\\n\\nfunction compareEventListeners(\\n context: TSESLint.RuleContext<\\\"mustCleanUpEventListeners\\\", []>,\\n matched: EventListener,\\n target: EventListenerInfo,\\n): boolean {\\n return (\\n matched.element.name === target.element.name &&\\n matched.event.value === target.event.value &&\\n normalizeText(context.sourceCode.getText(matched.callback)) ===\\n normalizeText(context.sourceCode.getText(target.callback)) &&\\n normalizeText(context.sourceCode.getText(matched.optional)) ===\\n normalizeText(context.sourceCode.getText(target.optional))\\n );\\n}\\n\\nfunction traverseAst(node: TSESTree.Node, handleNode: (node: TSESTree.Node) => boolean | void): boolean {\\n if (handleNode(node)) {\\n return true;\\n }\\n\\n switch (node.type) {\\n case ruleConstants.nodeTypes.blockStatement:\\n return node.body.some((stmt) => traverseAst(stmt, handleNode));\\n\\n case ruleConstants.nodeTypes.ifStatement:\\n return (\\n traverseAst(node.consequent, handleNode) ||\\n (node.alternate ? traverseAst(node.alternate, handleNode) : false)\\n );\\n\\n case ruleConstants.nodeTypes.expressionStatement:\\n return traverseAst(node.expression, handleNode);\\n\\n case ruleConstants.nodeTypes.returnStatement:\\n return node.argument ? traverseAst(node.argument, handleNode) : false;\\n\\n case ruleConstants.nodeTypes.arrowFuncExpression:\\n case ruleConstants.nodeTypes.funcExpression:\\n return traverseAst(node.body, handleNode);\\n\\n case ruleConstants.nodeTypes.callExpression:\\n return (\\n traverseAst(node.callee, handleNode) ||\\n node.arguments.some((arg) => traverseAst(arg, handleNode))\\n );\\n\\n case ruleConstants.nodeTypes.memberExpression:\\n return traverseAst(node.object, handleNode) || traverseAst(node.property, handleNode);\\n\\n default:\\n return false;\\n }\\n}\\n\\nfunction findEventListeners(node: TSESTree.Node, eventListeners: EventListenerInfo[]): void {\\n traverseAst(node, (currentNode) => {\\n const result = isMatchingEventListenerCall(currentNode, ruleConstants.listenersTypes.add);\\n\\n if (result && isValidCallExpression(currentNode, ruleConstants.listenersTypes.add)) {\\n eventListeners.push({ node: currentNode, ...result });\\n }\\n });\\n}\\n\\nfunction findRemoveEventListeners(\\n context: TSESLint.RuleContext<\\\"mustCleanUpEventListeners\\\", []>,\\n node: TSESTree.Node,\\n target: EventListenerInfo,\\n): boolean {\\n return traverseAst(node, (currentNode) => {\\n const matched = isMatchingEventListenerCall(currentNode, ruleConstants.listenersTypes.remove);\\n return matched ? compareEventListeners(context, matched, target) : false;\\n });\\n}\\n\\nfunction generateRemoveEventListenerCode(\\n eventListener: EventListenerInfo,\\n sourceCode: TSESLint.SourceCode,\\n): string {\\n const callbackCode = sourceCode.getText(eventListener.callback);\\n const code = `${eventListener.element.name}.removeEventListener(\\\"${eventListener.event.value}\\\", ${callbackCode}`;\\n\\n if (!eventListener.optional) return `${code});`;\\n\\n return `${code}, ${sourceCode.getText(eventListener.optional)});`;\\n}\\n\\nfunction handleReturnWithArrowFunction(\\n fixer: TSESLint.RuleFixer,\\n sourceCode: TSESLint.SourceCode,\\n returnStatement: TSESTree.ReturnStatement,\\n removeEventListenerCode: string,\\n tab: string,\\n doubleTab: string,\\n): TSESLint.RuleFix | null {\\n if (\\n !returnStatement.argument ||\\n returnStatement.argument.type !== ruleConstants.nodeTypes.arrowFuncExpression\\n )\\n return null;\\n\\n if (returnStatement.argument.body.type === ruleConstants.nodeTypes.callExpression) {\\n const code = sourceCode.getText(returnStatement.argument.body);\\n const fixedCode = `{\\\\n${doubleTab}${code};\\\\n${doubleTab}${removeEventListenerCode}\\\\n${tab}}`;\\n return fixer.replaceText(returnStatement.argument.body, fixedCode);\\n }\\n\\n if (returnStatement.argument.body.type === ruleConstants.nodeTypes.blockStatement) {\\n const lastToken = sourceCode.getLastToken(returnStatement.argument.body);\\n\\n if (!lastToken || lastToken.value !== \\\"}\\\") return null;\\n\\n const isEmpty = returnStatement.argument.body.body.length === 0;\\n let fixedCode: string;\\n\\n if (!isEmpty) {\\n fixedCode = `${tab}${removeEventListenerCode}\\\\n${tab}`;\\n } else {\\n fixedCode = `\\\\n${doubleTab}${removeEventListenerCode}\\\\n${tab}`;\\n }\\n\\n return fixer.insertTextBefore(lastToken, fixedCode);\\n }\\n\\n return null;\\n}\\n\\nfunction createFix(\\n context: TSESLint.RuleContext<\\\"mustCleanUpEventListeners\\\", []>,\\n fixer: TSESLint.RuleFixer,\\n useEffectBody: TSESTree.BlockStatement,\\n eventListener: EventListenerInfo,\\n): TSESLint.RuleFix | null {\\n const sourceCode = context.sourceCode;\\n const tab = /\\\\n(\\\\s+)/.exec(sourceCode.text)?.[1] ?? \\\" \\\";\\n const doubleTab = tab + tab;\\n const removeEventListenerCode = generateRemoveEventListenerCode(eventListener, sourceCode);\\n\\n const returnStatement = useEffectBody.body.findLast(\\n (statement) => statement.type === ruleConstants.nodeTypes.returnStatement,\\n );\\n\\n if (!returnStatement || returnStatement.type !== ruleConstants.nodeTypes.returnStatement) {\\n const lastToken = sourceCode.getLastToken(useEffectBody);\\n\\n if (!lastToken || lastToken.value !== \\\"}\\\") return null;\\n\\n const fixedCode = `${tab}return () => {\\\\n${doubleTab}${removeEventListenerCode}\\\\n${tab}};\\\\n`;\\n\\n return fixer.insertTextBefore(lastToken, fixedCode);\\n }\\n\\n return handleReturnWithArrowFunction(\\n fixer,\\n sourceCode,\\n returnStatement,\\n removeEventListenerCode,\\n tab,\\n doubleTab,\\n );\\n}\\n\\nfunction checkReturnStatement(\\n context: TSESLint.RuleContext<\\\"mustCleanUpEventListeners\\\", []>,\\n useEffectBody: TSESTree.BlockStatement,\\n eventListener: EventListenerInfo,\\n) {\\n const returnStatement = useEffectBody.body.findLast(\\n (statement) => statement.type === ruleConstants.nodeTypes.returnStatement,\\n );\\n\\n if (!returnStatement || returnStatement.type !== ruleConstants.nodeTypes.returnStatement) return false;\\n\\n if (!returnStatement.argument) return false;\\n\\n if (returnStatement.argument.type !== ruleConstants.nodeTypes.arrowFuncExpression) return false;\\n\\n return findRemoveEventListeners(context, returnStatement.argument.body, eventListener);\\n}\\n\\nfunction getCallbackText(\\n context: TSESLint.RuleContext<\\\"mustCleanUpEventListeners\\\", []>,\\n eventListener: EventListenerInfo,\\n): string {\\n if (eventListener.callback.type === ruleConstants.nodeTypes.identifier)\\n return eventListener.callback.name;\\n\\n return context.sourceCode.getText(eventListener.callback);\\n}\\n\\nfunction checkEarlyReturn(body: TSESTree.BlockStatement, eventListener: EventListenerInfo): boolean {\\n for (const statement of body.body) {\\n if (\\n statement.type === ruleConstants.nodeTypes.ifStatement &&\\n statement.test.type === ruleConstants.nodeTypes.unaryExpression &&\\n statement.test.operator === \\\"!\\\" &&\\n statement.test.argument.type === ruleConstants.nodeTypes.identifier &&\\n statement.test.argument.name === eventListener.element.name\\n ) {\\n if (statement.consequent.type === ruleConstants.nodeTypes.returnStatement) return true;\\n\\n if (statement.consequent.type === ruleConstants.nodeTypes.blockStatement) {\\n return statement.consequent.body.some(\\n (stmt) => stmt.type === ruleConstants.nodeTypes.returnStatement,\\n );\\n }\\n }\\n }\\n\\n return false;\\n}\\n\\nfunction checkArguments(\\n args: TSESTree.CallExpressionArgument[],\\n context: TSESLint.RuleContext<\\\"mustCleanUpEventListeners\\\", []>,\\n) {\\n if (\\n !args[0] ||\\n !args[1] ||\\n args[0].type !== ruleConstants.nodeTypes.arrowFuncExpression ||\\n args[1].type !== ruleConstants.nodeTypes.arrayExpression\\n )\\n return;\\n\\n const useEffectBody = args[0].body;\\n\\n if (useEffectBody.type !== ruleConstants.nodeTypes.blockStatement) return;\\n\\n const eventListeners: EventListenerInfo[] = [];\\n findEventListeners(useEffectBody, eventListeners);\\n\\n for (const eventListener of eventListeners) {\\n const hasEarlyReturn = checkEarlyReturn(useEffectBody, eventListener);\\n const hasRemoveEventListener = checkReturnStatement(context, useEffectBody, eventListener);\\n\\n if (!(hasRemoveEventListener || hasEarlyReturn)) {\\n context.report({\\n node: eventListener.node,\\n messageId: ruleConstants.messageId,\\n data: {\\n element: eventListener.element.name,\\n event: eventListener.event.value,\\n callback: getCallbackText(context, eventListener),\\n },\\n fix: (fixer) => createFix(context, fixer, useEffectBody, eventListener),\\n });\\n }\\n }\\n}\\n\\nconst mustCleanUpEventListeners = createRule({\\n name: ruleConstants.ruleName,\\n meta: {\\n type: \\\"problem\\\",\\n docs: { description: ruleConstants.description },\\n messages: { [ruleConstants.messageId]: ruleConstants.errorMessage },\\n schema: [],\\n fixable: \\\"code\\\",\\n },\\n defaultOptions: [],\\n create: (context) => ({\\n CallExpression(node: TSESTree.CallExpression) {\\n if (node.callee.type !== ruleConstants.nodeTypes.identifier) return;\\n\\n if (node.callee.name === ruleConstants.useEffectTypes.default) {\\n checkArguments(node.arguments, context);\\n }\\n },\\n }),\\n});\\n\\nexport default mustCleanUpEventListeners;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport rule from \\\"@root/rules/must-clean-up-event-listeners\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\nuseEffect(() => {\\n if (!window) return;\\n if (!isEnabled) return;\\n window.addEventListener(\\\"resize\\\", onResize);\\n return () => {\\n window.removeEventListener(\\\"resize\\\", onResize);\\n };\\n}, []);\\n `,\\n },\\n {\\n code: `\\nuseEffect(() => {\\n if (!element) return;\\n element.addEventListener(\\\"resize\\\", onResize);\\n}, [element]);\\n `,\\n },\\n {\\n code: `\\nuseEffect(() => {\\n const handle = () => {};\\n\\n if (condition1) {\\n return;\\n }\\n\\n document.addEventListener(\\\"scroll\\\", handle);\\n return () => {\\n document.removeEventListener(\\\"scroll\\\", handle);\\n };\\n}, []);\\n `,\\n },\\n {\\n code: `\\nuseEffect(() => {\\n if (condition) {\\n window.addEventListener(\\\"resize\\\", onResize);\\n }\\n \\n return () => {\\n if (condition) {\\n window.removeEventListener(\\\"resize\\\", onResize);\\n }\\n };\\n}, [condition]);\\n `,\\n },\\n {\\n code: `window.addEventListener(\\\"resize\\\", onResize);`,\\n },\\n {\\n code: `\\nuseEffect(() => {\\n fetchData();\\n updateUI();\\n return () => {\\n cleanup();\\n };\\n}, []);\\n `,\\n },\\n {\\n code: `\\nuseEffect(() => {\\n element.addEventListener('click', handleClick);\\n window.addEventListener('resize', handleResize);\\n return () => {\\n element.removeEventListener('click', handleClick);\\n window.removeEventListener('resize', handleResize);\\n };\\n}, []);\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\nuseEffect(() => {\\n window.addEventListener(\\\"resize\\\", onResize);\\n}, []);\\n`,\\n errors: [\\n {\\n messageId: \\\"mustCleanUpEventListeners\\\",\\n data: { element: \\\"window\\\", event: \\\"resize\\\", callback: \\\"onResize\\\" },\\n },\\n ],\\n output: `\\nuseEffect(() => {\\n window.addEventListener(\\\"resize\\\", onResize);\\n return () => {\\n window.removeEventListener(\\\"resize\\\", onResize);\\n };\\n}, []);\\n`,\\n },\\n {\\n code: `\\nuseEffect(() => {\\n const fn = () => {};\\n if (!element) return;\\n window.addEventListener(\\\"click\\\", fn);\\n return () => {};\\n}, []);\\n`,\\n errors: [\\n {\\n messageId: \\\"mustCleanUpEventListeners\\\",\\n data: { element: \\\"window\\\", event: \\\"click\\\", callback: \\\"fn\\\" },\\n },\\n ],\\n output: `\\nuseEffect(() => {\\n const fn = () => {};\\n if (!element) return;\\n window.addEventListener(\\\"click\\\", fn);\\n return () => {\\n window.removeEventListener(\\\"click\\\", fn);\\n };\\n}, []);\\n`,\\n },\\n {\\n code: `\\nuseEffect(() => {\\n const fn = () => {};\\n window.addEventListener(\\\"click\\\", fn);\\n return x;\\n}, []);\\n`,\\n errors: [\\n {\\n messageId: \\\"mustCleanUpEventListeners\\\",\\n data: { element: \\\"window\\\", event: \\\"click\\\", callback: \\\"fn\\\" },\\n },\\n ],\\n },\\n {\\n code: `\\nuseEffect(() => {\\n window.addEventListener(\\\"scroll\\\", handleScroll);\\n return () => {\\n window.removeEventListener(\\\"scroll\\\", anotherHandler);\\n };\\n}, []);\\n`,\\n errors: [\\n {\\n messageId: \\\"mustCleanUpEventListeners\\\",\\n data: { element: \\\"window\\\", event: \\\"scroll\\\", callback: \\\"handleScroll\\\" },\\n },\\n ],\\n output: `\\nuseEffect(() => {\\n window.addEventListener(\\\"scroll\\\", handleScroll);\\n return () => {\\n window.removeEventListener(\\\"scroll\\\", anotherHandler);\\n window.removeEventListener(\\\"scroll\\\", handleScroll);\\n };\\n}, []);\\n`,\\n },\\n {\\n code: `\\nuseEffect(() => {\\n window.addEventListener(\\\"resize\\\", onResize);\\n document.addEventListener(\\\"click\\\", onClick);\\n return () => {\\n window.removeEventListener(\\\"resize\\\", onResize);\\n };\\n}, []);\\n`,\\n errors: [\\n {\\n messageId: \\\"mustCleanUpEventListeners\\\",\\n data: { element: \\\"document\\\", event: \\\"click\\\", callback: \\\"onClick\\\" },\\n },\\n ],\\n output: `\\nuseEffect(() => {\\n window.addEventListener(\\\"resize\\\", onResize);\\n document.addEventListener(\\\"click\\\", onClick);\\n return () => {\\n window.removeEventListener(\\\"resize\\\", onResize);\\n document.removeEventListener(\\\"click\\\", onClick);\\n };\\n}, []);\\n`,\\n },\\n {\\n code: `\\nuseEffect(() => {\\n window.addEventListener(\\\"resize\\\", onResize);\\n return () => {\\n window.removeEventListener(\\\"scroll\\\", onResize);\\n };\\n}, []);\\n`,\\n errors: [\\n {\\n messageId: \\\"mustCleanUpEventListeners\\\",\\n data: { element: \\\"window\\\", event: \\\"resize\\\", callback: \\\"onResize\\\" },\\n },\\n ],\\n output: `\\nuseEffect(() => {\\n window.addEventListener(\\\"resize\\\", onResize);\\n return () => {\\n window.removeEventListener(\\\"scroll\\\", onResize);\\n window.removeEventListener(\\\"resize\\\", onResize);\\n };\\n}, []);\\n`,\\n },\\n {\\n code: `\\nuseEffect(() => {\\n window.addEventListener(\\\"resize\\\", onResize);\\n return () => {\\n document.removeEventListener(\\\"resize\\\", onResize);\\n };\\n}, []);\\n`,\\n errors: [\\n {\\n messageId: \\\"mustCleanUpEventListeners\\\",\\n data: { element: \\\"window\\\", event: \\\"resize\\\", callback: \\\"onResize\\\" },\\n },\\n ],\\n output: `\\nuseEffect(() => {\\n window.addEventListener(\\\"resize\\\", onResize);\\n return () => {\\n document.removeEventListener(\\\"resize\\\", onResize);\\n window.removeEventListener(\\\"resize\\\", onResize);\\n };\\n}, []);\\n`,\\n },\\n {\\n code: `\\nuseEffect(() => {\\n window.addEventListener(\\\"resize\\\", onResize);\\n return () => console.log(\\\"Cleanup\\\");\\n}, []);\\n`,\\n errors: [\\n {\\n messageId: \\\"mustCleanUpEventListeners\\\",\\n data: { element: \\\"window\\\", event: \\\"resize\\\", callback: \\\"onResize\\\" },\\n },\\n ],\\n output: `\\nuseEffect(() => {\\n window.addEventListener(\\\"resize\\\", onResize);\\n return () => {\\n console.log(\\\"Cleanup\\\");\\n window.removeEventListener(\\\"resize\\\", onResize);\\n };\\n}, []);\\n`,\\n },\\n {\\n code: `\\nuseEffect(() => {\\n const handler = () => console.log('Resized');\\n window.addEventListener('resize', handler);\\n}, []);\\n `,\\n errors: [\\n {\\n messageId: \\\"mustCleanUpEventListeners\\\",\\n data: { element: \\\"window\\\", event: \\\"resize\\\", callback: \\\"handler\\\" },\\n },\\n ],\\n output: `\\nuseEffect(() => {\\n const handler = () => console.log('Resized');\\n window.addEventListener('resize', handler);\\n return () => {\\n window.removeEventListener(\\\"resize\\\", handler);\\n };\\n}, []);\\n `,\\n },\\n {\\n code: `\\nuseEffect(() => {\\n if (condition) {\\n window.addEventListener(\\\"resize\\\", onResize);\\n }\\n}, [condition]);`,\\n errors: [\\n {\\n messageId: \\\"mustCleanUpEventListeners\\\",\\n data: { element: \\\"window\\\", event: \\\"resize\\\", callback: \\\"onResize\\\" },\\n },\\n ],\\n output: `\\nuseEffect(() => {\\n if (condition) {\\n window.addEventListener(\\\"resize\\\", onResize);\\n }\\n return () => {\\n window.removeEventListener(\\\"resize\\\", onResize);\\n };\\n}, [condition]);`,\\n },\\n ],\\n};\\n\\nconst cases = [validCases, invalidCases];\\n\\nrunTests(\\\"must-clean-up-event-listeners\\\", rule, cases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'must-consolidate-conditional-expressions.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, AST_NODE_TYPES, TSESTree } from \\\"@typescript-eslint/utils\\\";\\nimport { RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\n\\nconst constants = {\\n url: \\\"https://example.com/rules/\\\",\\n ruleName: \\\"must-consolidate-conditional-expressions\\\",\\n messageIds: {\\n mustConsolidateConditionalExpressions: \\\"mustConsolidateConditionalExpressions\\\",\\n },\\n meta: {\\n type: \\\"suggestion\\\",\\n docs: {\\n description: \\\"Avoid nested conditions, combine them with logical operators when possible\\\",\\n },\\n messages: {\\n mustConsolidateConditionalExpressions:\\n \\\"Combine nested conditions using logical operators if possible.\\\",\\n },\\n schema: [],\\n },\\n nodeTypes: {\\n ifStatement: AST_NODE_TYPES.IfStatement,\\n blockStatement: AST_NODE_TYPES.BlockStatement,\\n logicalExpression: AST_NODE_TYPES.LogicalExpression,\\n callExpression: AST_NODE_TYPES.CallExpression,\\n },\\n} as const;\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${constants.url}${ruleName}`);\\n\\nconst mustConsolidateConditionalExpressions = createRule<\\n [],\\n typeof constants.messageIds.mustConsolidateConditionalExpressions\\n>({\\n name: constants.ruleName,\\n meta: constants.meta,\\n defaultOptions: [],\\n\\n create(context: RuleContext) {\\n function hasOnlySingleIfStatement(node: TSESTree.BlockStatement) {\\n return node.body.length === 1 && node.body[0]?.type === constants.nodeTypes.ifStatement;\\n }\\n\\n function hasElseBranch(node: TSESTree.IfStatement) {\\n return node.alternate !== null;\\n }\\n\\n function isComplexCondition(node: TSESTree.Expression) {\\n return (\\n node.type === constants.nodeTypes.logicalExpression ||\\n node.type === constants.nodeTypes.callExpression\\n );\\n }\\n\\n function hasMultipleStatements(node: TSESTree.IfStatement) {\\n if (node.consequent.type !== constants.nodeTypes.blockStatement) {\\n return false;\\n }\\n\\n return node.consequent.body.length > 1;\\n }\\n\\n function isNestedIfCandidate(node: TSESTree.IfStatement) {\\n if (node.consequent.type !== constants.nodeTypes.blockStatement) {\\n return false;\\n }\\n\\n if (hasElseBranch(node)) {\\n return false;\\n }\\n\\n if (isComplexCondition(node.test)) {\\n return false;\\n }\\n\\n return hasOnlySingleIfStatement(node.consequent);\\n }\\n\\n function isInNonCombinableContext(node: TSESTree.Node) {\\n const ancestors = context.sourceCode.getAncestors(node);\\n\\n for (let i = ancestors.length - 1; i >= Math.max(0, ancestors.length - 4); i--) {\\n const ancestor = ancestors[i];\\n\\n if (!ancestor) continue;\\n\\n if (\\n ancestor.type === AST_NODE_TYPES.WhileStatement ||\\n ancestor.type === AST_NODE_TYPES.ForStatement ||\\n ancestor.type === AST_NODE_TYPES.ForInStatement ||\\n ancestor.type === AST_NODE_TYPES.ForOfStatement ||\\n ancestor.type === AST_NODE_TYPES.DoWhileStatement\\n ) {\\n return true;\\n }\\n }\\n\\n return false;\\n }\\n\\n return {\\n [constants.nodeTypes.ifStatement](node: TSESTree.IfStatement) {\\n if (!isNestedIfCandidate(node)) {\\n return;\\n }\\n\\n if (isInNonCombinableContext(node)) {\\n return;\\n }\\n\\n const nestedIf = (node.consequent as TSESTree.BlockStatement).body[0] as TSESTree.IfStatement;\\n\\n if (hasElseBranch(nestedIf)) {\\n return;\\n }\\n\\n if (isComplexCondition(nestedIf.test)) {\\n return;\\n }\\n\\n if (hasMultipleStatements(nestedIf)) {\\n return;\\n }\\n\\n if (nestedIf.consequent.type !== constants.nodeTypes.blockStatement) {\\n return;\\n }\\n\\n context.report({\\n node: node,\\n messageId: constants.messageIds.mustConsolidateConditionalExpressions,\\n });\\n },\\n };\\n },\\n});\\n\\nexport default mustConsolidateConditionalExpressions;\\n\",\"test_code\":\"import { runTests } from \\\"../test-utils/eslint-rule-tester\\\";\\nimport mustConsolidateConditionalExpressions from \\\"../rules/must-consolidate-conditional-expressions\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n if (foo) {\\n console.log(\\\"foo is truthy\\\");\\n }\\n `,\\n },\\n\\n {\\n code: `\\n if (bar) {\\n console.log(\\\"bar is truthy\\\");\\n } else {\\n console.log(\\\"bar is falsy\\\");\\n }\\n `,\\n },\\n\\n {\\n code: `\\n function baz() {\\n if (foo === 0) {\\n return true;\\n }\\n return false;\\n }\\n `,\\n },\\n\\n {\\n code: `\\n if (foo > bar) {\\n console.log(\\\"foo is greater than bar\\\");\\n foo = bar;\\n }\\n `,\\n },\\n\\n {\\n code: `\\n if (foo) {\\n if (bar) {\\n baz();\\n } else {\\n qux();\\n }\\n }\\n `,\\n },\\n\\n {\\n code: `\\n if (foo > 5 || bar < 2) {\\n if (baz > 10) {\\n qux();\\n }\\n }\\n `,\\n },\\n\\n {\\n code: `\\n if (foo > 5) {\\n if (bar > 10 && bar < 20) {\\n baz();\\n }\\n }\\n `,\\n },\\n\\n {\\n code: `\\n if (foo > 5) {\\n if (isValid(foo)) {\\n bar();\\n }\\n }\\n `,\\n },\\n\\n {\\n code: `\\n if (foo) {\\n console.log(\\\"Before nested if\\\");\\n if (bar) {\\n baz();\\n }\\n console.log(\\\"After nested if\\\");\\n }\\n `,\\n },\\n\\n {\\n code: `\\n if (foo) {\\n if (bar) baz();\\n }\\n `,\\n },\\n\\n {\\n code: `\\n if (foo && bar && baz) {\\n qux();\\n }\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n if (foo) {\\n if (bar) {\\n baz();\\n }\\n }\\n `,\\n errors: [{ messageId: \\\"mustConsolidateConditionalExpressions\\\" }],\\n },\\n\\n {\\n code: `\\n if (foo) {\\n if (bar) {\\n if (baz) {\\n qux();\\n }\\n }\\n }\\n `,\\n errors: [\\n { messageId: \\\"mustConsolidateConditionalExpressions\\\" },\\n { messageId: \\\"mustConsolidateConditionalExpressions\\\" },\\n ],\\n },\\n\\n {\\n code: `\\n function qux() {\\n if (foo > 0) {\\n if (bar < 0) {\\n return true;\\n }\\n }\\n return false;\\n }\\n `,\\n errors: [{ messageId: \\\"mustConsolidateConditionalExpressions\\\" }],\\n },\\n ],\\n};\\n\\nconst edgeCases = {\\n valid: [\\n {\\n code: `\\n if (foo) {\\n bar();\\n }\\n if (baz) {\\n qux();\\n }\\n `,\\n },\\n\\n {\\n code: `\\n while (foo) {\\n if (bar > 0) {\\n if (baz > 0) {\\n break;\\n }\\n }\\n }\\n `,\\n errors: [{ messageId: \\\"mustConsolidateConditionalExpressions\\\" }],\\n },\\n ],\\n invalid: [\\n {\\n code: `\\n function test() {\\n if (foo) {\\n if (bar) {\\n return true;\\n }\\n }\\n return false;\\n }\\n `,\\n errors: [{ messageId: \\\"mustConsolidateConditionalExpressions\\\" }],\\n },\\n\\n {\\n code: `\\n if (foo) {\\n if (bar) {\\n baz = 5;\\n }\\n }\\n `,\\n errors: [{ messageId: \\\"mustConsolidateConditionalExpressions\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases, edgeCases];\\nrunTests(\\\"must-consolidate-conditional-expressions\\\", mustConsolidateConditionalExpressions, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'must-create-resources-in-src-dir.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree } from \\\"@typescript-eslint/utils\\\";\\n\\nconst ruleConstants = {\\n ruleName: \\\"must-create-resources-in-src-dir\\\",\\n urlBase: \\\"https://example.com/rules/\\\",\\n description: \\\"Disallow importing *.resource files from @server. Use @/resources instead.\\\",\\n errorMessage: \\\"Must import resources from \\\\\\\"@/resources/...\\\\\\\" instead of \\\\\\\"@server/...\\\\\\\".\\\",\\n messageId: \\\"noServerResourceImports\\\",\\n} as const;\\n\\nconst createRule = ESLintUtils.RuleCreator((name) => `${ruleConstants.urlBase}${name}`);\\n\\nconst noServerResourceImports = createRule({\\n name: ruleConstants.ruleName,\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: ruleConstants.description,\\n },\\n messages: {\\n [ruleConstants.messageId]: ruleConstants.errorMessage,\\n },\\n schema: [],\\n },\\n defaultOptions: [],\\n create(context) {\\n return {\\n ImportDeclaration(node: TSESTree.ImportDeclaration) {\\n const importPath = node.source.value;\\n\\n if (\\n typeof importPath === \\\"string\\\" &&\\n importPath.startsWith(\\\"@server/\\\") &&\\n importPath.endsWith(\\\".resource\\\")\\n ) {\\n context.report({\\n node: node.source,\\n messageId: ruleConstants.messageId,\\n });\\n }\\n },\\n };\\n },\\n});\\n\\nexport default noServerResourceImports;\\n\",\"test_code\":\"import { runTests } from \\\"../test-utils/eslint-rule-tester\\\";\\nimport rule from \\\"../rules/must-create-resources-in-src-dir\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `import { Order } from \\\"@/resources/order/order.resource\\\";`,\\n },\\n {\\n code: `import { something } from \\\"@/meta/decorators/resource-id\\\";`,\\n },\\n {\\n code: `import { Order } from \\\"@common/orders/order-enums\\\";`,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `import { Order } from \\\"@server/orders/order.resource\\\";`,\\n errors: [{ messageId: \\\"noServerResourceImports\\\" }],\\n },\\n {\\n code: `import { Customer } from \\\"@server/customers/customer.resource\\\";`,\\n errors: [{ messageId: \\\"noServerResourceImports\\\" }],\\n },\\n ],\\n};\\n\\nconst cases = [validCases, invalidCases];\\n\\nrunTests(\\\"must-create-resources-in-src-dir\\\", rule, cases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'must-limit-lines-without-comments.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree } from \\\"@typescript-eslint/utils\\\";\\nimport { RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\n\\nconst constants = {\\n url: \\\"https://example.com/rules/\\\",\\n ruleName: \\\"must-limit-lines-without-comments\\\",\\n messageIds: {\\n tooManyLines: \\\"tooManyLines\\\",\\n },\\n meta: {\\n type: \\\"suggestion\\\",\\n docs: {\\n description: \\\"Enforce a maximum number of lines in a file, excluding comments\\\",\\n },\\n messages: {\\n tooManyLines: \\\"File has too many lines ({{lineCount}}). Maximum allowed is {{maxLines}}.\\\",\\n },\\n schema: [\\n {\\n type: \\\"object\\\",\\n properties: {\\n maxLines: {\\n type: \\\"number\\\",\\n minimum: 0,\\n },\\n },\\n additionalProperties: false,\\n },\\n ],\\n },\\n defaultMaxLines: 400,\\n} as const;\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${constants.url}${ruleName}`);\\n\\nconst mustLimitLinesWithoutComments = createRule({\\n name: constants.ruleName,\\n meta: constants.meta,\\n create(context: RuleContext) {\\n const sourceCode = context.sourceCode;\\n const options = context.options[0] || { maxLines: constants.defaultMaxLines };\\n const maxLines = options.maxLines;\\n\\n return {\\n Program(node: TSESTree.Program) {\\n const lines = sourceCode.lines;\\n const comments = sourceCode.getAllComments();\\n const commentLines = new Set();\\n\\n comments.forEach((comment) => {\\n const startLine = comment.loc.start.line;\\n const endLine = comment.loc.end.line;\\n\\n for (let i = startLine; i <= endLine; i++) {\\n commentLines.add(i);\\n }\\n });\\n\\n let nonCommentLines = 0;\\n\\n lines.forEach((line, index) => {\\n const lineNumber = index + 1;\\n\\n if (!commentLines.has(lineNumber) && line.trim()) {\\n nonCommentLines++;\\n }\\n });\\n\\n if (nonCommentLines === 0) {\\n return;\\n }\\n\\n if (nonCommentLines > maxLines) {\\n context.report({\\n node,\\n messageId: constants.messageIds.tooManyLines,\\n data: {\\n lineCount: nonCommentLines,\\n maxLines,\\n },\\n });\\n }\\n },\\n };\\n },\\n\\n defaultOptions: [{ maxLines: constants.defaultMaxLines }],\\n});\\n\\nexport default mustLimitLinesWithoutComments;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport mustLimitLinesWithoutComments from \\\"@root/rules/must-limit-lines-without-comments\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n // This is a comment\\n const foo = 1;\\n const bar = 2;\\n // Another comment\\n const baz = 3;\\n `,\\n options: [{ maxLines: 3 }],\\n },\\n {\\n code: `\\n /* Multiline\\n * comment\\n */\\n const foo = 1;\\n const bar = 2;\\n `,\\n options: [{ maxLines: 2 }],\\n },\\n {\\n code: `\\n // Many comments\\n // Another comment\\n // And one more\\n const foo = 1;\\n const bar = 2;\\n // And again\\n // comments\\n `,\\n options: [{ maxLines: 2 }],\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n // Comment\\n const foo = 1;\\n const bar = 2;\\n const baz = 3;\\n const qux = 4;\\n const quux = 5;\\n // Another comment\\n `,\\n options: [{ maxLines: 3 }],\\n errors: [\\n {\\n messageId: \\\"tooManyLines\\\",\\n data: {\\n lineCount: 5,\\n maxLines: 3,\\n },\\n },\\n ],\\n },\\n {\\n code: `\\n /* Multiline\\n * comment\\n */\\n const foo = 1;\\n const bar = 2;\\n const baz = 3;\\n const qux = 4;\\n const quux = 5;\\n const corge = 6;\\n `,\\n options: [{ maxLines: 4 }],\\n errors: [\\n {\\n messageId: \\\"tooManyLines\\\",\\n data: {\\n lineCount: 6,\\n maxLines: 4,\\n },\\n },\\n ],\\n },\\n ],\\n};\\n\\nconst edgeCases = {\\n valid: [\\n {\\n code: `\\n // Only comments\\n // No code\\n // At all\\n `,\\n options: [{ maxLines: 0 }],\\n },\\n ],\\n invalid: [\\n {\\n code: `\\n // Comment\\n const foo = 1;\\n const bar = 2;\\n const baz = 3;\\n const qux = 4;\\n const quux = 5;\\n const corge = 6;\\n const grault = 7;\\n const garply = 8;\\n const waldo = 9;\\n const fred = 10;\\n // Another comment\\n `,\\n options: [{ maxLines: 5 }],\\n errors: [\\n {\\n messageId: \\\"tooManyLines\\\",\\n data: {\\n lineCount: 10,\\n maxLines: 5,\\n },\\n },\\n ],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases, edgeCases];\\nrunTests(\\\"must-limit-lines-without-comments\\\", mustLimitLinesWithoutComments, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'must-put-empty-line.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESLint, TSESTree } from \\\"@typescript-eslint/utils\\\";\\n\\nconst constants = {\\n urls: {\\n base: \\\"https://example.com/rules/\\\",\\n },\\n nodeTypes: {\\n block: {\\n blockStatement: \\\"BlockStatement\\\",\\n program: \\\"Program\\\",\\n },\\n function: {\\n functionExpression: \\\"FunctionExpression\\\",\\n arrowFunctionExpression: \\\"ArrowFunctionExpression\\\",\\n functionDeclaration: \\\"FunctionDeclaration\\\",\\n },\\n control: {\\n ifStatement: \\\"IfStatement\\\",\\n switchStatement: \\\"SwitchStatement\\\",\\n forStatement: \\\"ForStatement\\\",\\n whileStatement: \\\"WhileStatement\\\",\\n doWhileStatement: \\\"DoWhileStatement\\\",\\n forInStatement: \\\"ForInStatement\\\",\\n forOfStatement: \\\"ForOfStatement\\\",\\n tryStatement: \\\"TryStatement\\\",\\n },\\n class: {\\n methodDefinition: \\\"MethodDefinition\\\",\\n classBody: \\\"ClassBody\\\",\\n classDeclaration: \\\"ClassDeclaration\\\",\\n variableDeclaration: \\\"VariableDeclaration\\\",\\n },\\n },\\n format: {\\n empty: \\\"\\\",\\n newLine: \\\"\\\\n\\\",\\n doubleNewLine: \\\"\\\\n\\\\n\\\",\\n space: \\\" \\\",\\n closeBrace: \\\"}\\\",\\n },\\n regex: {\\n indentation: /^\\\\s*/,\\n camelCase: /([A-Z])/g,\\n },\\n messages: {\\n positions: {\\n above: \\\"above\\\",\\n below: \\\"below\\\",\\n },\\n ids: {\\n emptyLineRequired: \\\"emptyLineRequired\\\",\\n },\\n template: {\\n emptyLineRequired: \\\"Empty line {{position}} {{node}} is required\\\",\\n },\\n },\\n meta: {\\n type: \\\"layout\\\",\\n ruleName: \\\"must-put-empty-line\\\",\\n description: \\\"Enforce empty lines above and below control structures and functions\\\",\\n suggestions: true,\\n },\\n schema: {\\n type: \\\"object\\\",\\n arrayType: \\\"array\\\",\\n stringType: \\\"string\\\",\\n },\\n rules: {\\n fixableType: \\\"whitespace\\\",\\n },\\n validation: {\\n additionalProperties: false,\\n },\\n sourceCode: {\\n tokenOptions: { includeComments: true },\\n },\\n rule: {\\n lineDistances: {\\n adjacent: 1,\\n },\\n },\\n} as const;\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName) => `${constants.urls.base}${ruleName}`);\\n\\ntype Options = [\\n {\\n checkNodeTypes?: string[];\\n },\\n];\\n\\nconst defaultCheckNodeTypes = [\\n constants.nodeTypes.function.functionDeclaration,\\n constants.nodeTypes.control.ifStatement,\\n constants.nodeTypes.control.switchStatement,\\n constants.nodeTypes.control.forStatement,\\n constants.nodeTypes.control.whileStatement,\\n constants.nodeTypes.control.doWhileStatement,\\n constants.nodeTypes.control.forInStatement,\\n constants.nodeTypes.control.forOfStatement,\\n constants.nodeTypes.control.tryStatement,\\n constants.nodeTypes.function.arrowFunctionExpression,\\n constants.nodeTypes.function.functionExpression,\\n constants.nodeTypes.class.methodDefinition,\\n constants.nodeTypes.class.classDeclaration,\\n constants.nodeTypes.class.variableDeclaration,\\n];\\n\\nconst formatNodeType = (type: string) => {\\n return type.replace(constants.regex.camelCase, constants.format.space).trim().toLowerCase();\\n};\\n\\nconst getNodeIndent = (node: TSESTree.Node, sourceCode: Readonly) => {\\n const execResult = constants.regex.indentation.exec(sourceCode.getText(node));\\n return execResult ? execResult[0] : constants.format.empty;\\n};\\n\\nconst isMethodFunction = (node: TSESTree.Node) => {\\n return (\\n node.type === constants.nodeTypes.function.functionExpression &&\\n node.parent?.type === constants.nodeTypes.class.methodDefinition\\n );\\n};\\n\\nconst createFix = (\\n fixer: TSESLint.RuleFixer,\\n startRange: number,\\n endRange: number,\\n beforeNewline: string,\\n indent: string,\\n rest: string[],\\n) => {\\n const newText =\\n beforeNewline + constants.format.doubleNewLine + indent + rest.join(constants.format.newLine);\\n return fixer.replaceTextRange([startRange, endRange], newText);\\n};\\n\\nconst checkEmptyLineBelow = (\\n node: TSESTree.Node,\\n context: TSESLint.RuleContext,\\n sourceCode: Readonly,\\n) => {\\n const nextToken = sourceCode.getTokenAfter(node, constants.sourceCode.tokenOptions);\\n\\n if (!nextToken || nextToken.value === constants.format.closeBrace) return;\\n\\n const startLine = node.loc.end.line;\\n const endLine = nextToken.loc.start.line;\\n const distance = endLine - startLine;\\n\\n if (distance === constants.rule.lineDistances.adjacent) {\\n const indent = getNodeIndent(node, sourceCode);\\n const existingText = sourceCode.getText().slice(node.range[1], nextToken.range[0]);\\n const [beforeNewline = constants.format.empty, ...rest] = existingText.split(\\n constants.format.newLine,\\n );\\n\\n context.report({\\n node,\\n messageId: constants.messages.ids.emptyLineRequired,\\n data: {\\n position: constants.messages.positions.below,\\n node: formatNodeType(node.type),\\n },\\n fix: (fixer) => createFix(fixer, node.range[1], nextToken.range[0], beforeNewline, indent, rest),\\n });\\n }\\n};\\n\\nconst checkEmptyLineAbove = (\\n node: TSESTree.Node,\\n siblings: TSESTree.Statement[],\\n methodSiblings: TSESTree.Node[],\\n context: TSESLint.RuleContext,\\n sourceCode: Readonly,\\n) => {\\n const isClassMethod =\\n node.type === constants.nodeTypes.class.methodDefinition &&\\n node.parent?.type === constants.nodeTypes.class.classBody;\\n\\n const currentIndex = isClassMethod\\n ? methodSiblings.indexOf(node)\\n : siblings.findIndex((sibling) => sibling === node);\\n\\n const prevSibling =\\n currentIndex > 0\\n ? isClassMethod\\n ? methodSiblings[currentIndex - 1]\\n : siblings[currentIndex - 1]\\n : null;\\n\\n if (!prevSibling) return;\\n\\n const startLine = prevSibling.loc.end.line;\\n const endLine = node.loc.start.line;\\n const distance = endLine - startLine;\\n\\n if (distance === constants.rule.lineDistances.adjacent) {\\n const indent = isClassMethod\\n ? getNodeIndent(node.parent?.parent || node, sourceCode)\\n : getNodeIndent(node, sourceCode);\\n\\n const existingText = sourceCode.getText().slice(prevSibling.range[1], node.range[0]);\\n const [beforeNewline = constants.format.empty, ...rest] = existingText.split(\\n constants.format.newLine,\\n );\\n\\n context.report({\\n node,\\n messageId: constants.messages.ids.emptyLineRequired,\\n data: {\\n position: constants.messages.positions.above,\\n node: formatNodeType(node.type),\\n },\\n fix: (fixer) =>\\n createFix(fixer, prevSibling.range[1], node.range[0], beforeNewline, indent, rest),\\n });\\n }\\n};\\n\\nconst checkAround = (\\n node: TSESTree.Node,\\n context: TSESLint.RuleContext,\\n sourceCode: Readonly,\\n siblings: TSESTree.Statement[] = [],\\n methodSiblings: TSESTree.Node[] = [],\\n) => {\\n checkEmptyLineAbove(node, siblings, methodSiblings, context, sourceCode);\\n checkEmptyLineBelow(node, context, sourceCode);\\n};\\n\\nconst isFunctionOrArrowType = (type: string) => {\\n return (\\n type === constants.nodeTypes.function.functionExpression ||\\n type === constants.nodeTypes.function.arrowFunctionExpression\\n );\\n};\\n\\nconst checkEmptyLines = (\\n node: TSESTree.Node,\\n context: TSESLint.RuleContext,\\n sourceCode: Readonly,\\n) => {\\n const parent = node.parent;\\n\\n if (!parent) return;\\n\\n if (parent.type === constants.nodeTypes.class.classBody) {\\n const siblings = parent.body;\\n checkAround(node, context, sourceCode, [], siblings);\\n return;\\n }\\n\\n if (parent.type === constants.nodeTypes.block.program) {\\n const siblings = parent.body;\\n checkAround(node, context, sourceCode, siblings, []);\\n return;\\n }\\n\\n if (parent.type === constants.nodeTypes.block.blockStatement) {\\n const grandParent = parent.parent;\\n\\n if (!grandParent) return;\\n\\n if (grandParent.type === constants.nodeTypes.class.classBody) {\\n const siblings = grandParent.body;\\n checkAround(node, context, sourceCode, [], siblings);\\n return;\\n }\\n\\n const siblings = parent.body;\\n checkAround(node, context, sourceCode, siblings, []);\\n }\\n};\\n\\nconst mustPutEmptyLine = createRule({\\n name: constants.meta.ruleName,\\n meta: {\\n type: constants.meta.type,\\n docs: {\\n description: constants.meta.description,\\n },\\n fixable: constants.rules.fixableType,\\n hasSuggestions: constants.meta.suggestions,\\n schema: [\\n {\\n type: constants.schema.type,\\n properties: {\\n checkNodeTypes: {\\n type: constants.schema.arrayType,\\n items: { type: constants.schema.stringType },\\n },\\n },\\n additionalProperties: constants.validation.additionalProperties,\\n },\\n ],\\n messages: {\\n [constants.messages.ids.emptyLineRequired]: constants.messages.template.emptyLineRequired,\\n },\\n },\\n defaultOptions: [{ checkNodeTypes: defaultCheckNodeTypes }],\\n create: (context, [options]) => {\\n const { sourceCode } = context;\\n const checkNodeTypes = options.checkNodeTypes ?? defaultCheckNodeTypes;\\n\\n const listeners: TSESLint.RuleListener = {};\\n\\n for (const type of checkNodeTypes) {\\n if (type === constants.nodeTypes.class.methodDefinition) {\\n listeners[type] = (node: TSESTree.MethodDefinition) => {\\n checkEmptyLines(node, context, sourceCode);\\n };\\n } else if (type === constants.nodeTypes.function.functionExpression) {\\n listeners[type] = (node: TSESTree.FunctionExpression) => {\\n if (!isMethodFunction(node)) {\\n checkEmptyLines(node, context, sourceCode);\\n }\\n };\\n } else if (type === constants.nodeTypes.class.variableDeclaration) {\\n listeners[type] = (node: TSESTree.VariableDeclaration) => {\\n const init = node.declarations[0]?.init;\\n\\n if (init?.type && isFunctionOrArrowType(init.type)) {\\n checkEmptyLines(node, context, sourceCode);\\n }\\n };\\n } else {\\n listeners[type] = (node: TSESTree.Node) => {\\n checkEmptyLines(node, context, sourceCode);\\n };\\n }\\n }\\n\\n return listeners;\\n },\\n});\\n\\nexport default mustPutEmptyLine;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport ruleMustPutEmptyLine from \\\"@root/rules/must-put-empty-line\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `const variable = 5;\\n const variable2 = 10;`,\\n },\\n {\\n code: `const bar = foo();\\n \\n if(condition()){\\n baz();\\n }`,\\n },\\n {\\n code: `const bar = foo();\\n \\n try {\\n baz();\\n } catch(error) {\\n qux(error);\\n }`,\\n },\\n {\\n code: `function foo() {};\\n \\n function bar() {};`,\\n },\\n {\\n code: `function foo() {};\\n \\n if (true) {\\n console.log(\\\"Hello!\\\");\\n }`,\\n },\\n {\\n code: `function foo() {};\\n \\n try {\\n baz();\\n } catch(error) {\\n qux(error);\\n }`,\\n },\\n {\\n code: `function foo() {};\\n \\n switch (\\\"test\\\") {\\n case \\\"test\\\":\\n console.log(\\\"test\\\");\\n break;\\n default:\\n break;\\n }`,\\n },\\n {\\n code: `for (const item of [1, 2, 3]) {\\n console.log(item);\\n }\\n \\n for (const item of [1, 2, 3]) {\\n console.log(item);\\n }`,\\n },\\n {\\n code: `function foo() {};\\n \\n for (const item of [1, 2, 3]) {\\n console.log(item);\\n }`,\\n },\\n {\\n code: `if (true) {\\n console.log(\\\"Testing if statement\\\");\\n \\n function insideIf() {\\n console.log(\\\"inside if\\\");\\n }\\n \\n const arrowInIf = () => {\\n console.log(\\\"arrow in if\\\");\\n };\\n }`,\\n },\\n {\\n code: `for (let i = 0; i < 5; i++) {\\n for (const item of [1, 2, 3]) {\\n console.log(item);\\n }\\n \\n console.log(i);\\n }`,\\n },\\n {\\n code: `try {\\n try {\\n throw new Error(\\\"test\\\");\\n } catch (error) {\\n console.log(error);\\n }\\n \\n throw new Error(\\\"test\\\");\\n \\n function insideTry() {\\n console.log(\\\"inside try\\\");\\n }\\n } catch (error) {\\n console.log(error);\\n \\n function insideCatch() {\\n console.log(\\\"inside catch\\\");\\n }\\n }`,\\n },\\n {\\n code: `class TestClass {\\n constructor() {\\n console.log(\\\"constructor\\\");\\n }\\n \\n testMethod() {\\n console.log(\\\"method\\\");\\n }\\n \\n testMethod2() {\\n console.log(\\\"method\\\");\\n }\\n }`,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `const bar = foo();\\nif(condition()){\\n baz();\\n}`,\\n errors: [{ messageId: \\\"emptyLineRequired\\\" }],\\n output: `const bar = foo();\\n\\nif(condition()){\\n baz();\\n}`,\\n },\\n {\\n code: `const bar = foo();\\ntry {\\n baz();\\n} catch(error) {\\n qux(error);\\n}`,\\n errors: [{ messageId: \\\"emptyLineRequired\\\" }],\\n output: `const bar = foo();\\n\\ntry {\\n baz();\\n} catch(error) {\\n qux(error);\\n}`,\\n },\\n {\\n code: `function foo() {};\\nfunction bar() {};`,\\n errors: [{ messageId: \\\"emptyLineRequired\\\" }],\\n output: `function foo() {};\\n\\nfunction bar() {};`,\\n },\\n {\\n code: `function foo() {};\\nif (true) {\\n console.log(\\\"Hello!\\\");\\n}`,\\n errors: [{ messageId: \\\"emptyLineRequired\\\" }],\\n output: `function foo() {};\\n\\nif (true) {\\n console.log(\\\"Hello!\\\");\\n}`,\\n },\\n {\\n code: `function foo() {};\\ntry {\\n baz();\\n} catch(error) {\\n qux(error);\\n}`,\\n errors: [{ messageId: \\\"emptyLineRequired\\\" }],\\n output: `function foo() {};\\n\\ntry {\\n baz();\\n} catch(error) {\\n qux(error);\\n}`,\\n },\\n {\\n code: `function foo() {};\\nswitch (\\\"test\\\") {\\n case \\\"test\\\":\\n console.log(\\\"test\\\");\\n break;\\n default:\\n break;\\n}`,\\n errors: [{ messageId: \\\"emptyLineRequired\\\" }],\\n output: `function foo() {};\\n\\nswitch (\\\"test\\\") {\\n case \\\"test\\\":\\n console.log(\\\"test\\\");\\n break;\\n default:\\n break;\\n}`,\\n },\\n {\\n code: `for (const item of [1, 2, 3]) {\\n console.log(item);\\n}\\nfor (const item of [1, 2, 3]) {\\n console.log(item);\\n}`,\\n errors: [{ messageId: \\\"emptyLineRequired\\\" }, { messageId: \\\"emptyLineRequired\\\" }],\\n output: `for (const item of [1, 2, 3]) {\\n console.log(item);\\n}\\n\\nfor (const item of [1, 2, 3]) {\\n console.log(item);\\n}`,\\n },\\n {\\n code: `function foo() {};\\nfor (const item of [1, 2, 3]) {\\n console.log(item);\\n}`,\\n errors: [{ messageId: \\\"emptyLineRequired\\\" }],\\n output: `function foo() {};\\n\\nfor (const item of [1, 2, 3]) {\\n console.log(item);\\n}`,\\n },\\n {\\n code: `if (true) {\\n console.log(\\\"Testing if statement\\\");\\n function insideIf() {\\n console.log(\\\"inside if\\\");\\n }\\n const arrowInIf = () => {\\n console.log(\\\"arrow in if\\\");\\n };\\n}`,\\n errors: [\\n { messageId: \\\"emptyLineRequired\\\" },\\n { messageId: \\\"emptyLineRequired\\\" },\\n { messageId: \\\"emptyLineRequired\\\" },\\n ],\\n output: `if (true) {\\n console.log(\\\"Testing if statement\\\");\\n\\n function insideIf() {\\n console.log(\\\"inside if\\\");\\n }\\n\\n const arrowInIf = () => {\\n console.log(\\\"arrow in if\\\");\\n };\\n}`,\\n },\\n {\\n code: `for (let i = 0; i < 5; i++) {\\n for (const item of [1, 2, 3]) {\\n console.log(item);\\n }\\nconsole.log(i);\\n}`,\\n errors: [{ messageId: \\\"emptyLineRequired\\\" }],\\n output: `for (let i = 0; i < 5; i++) {\\n for (const item of [1, 2, 3]) {\\n console.log(item);\\n }\\n\\nconsole.log(i);\\n}`,\\n },\\n {\\n code: `try {\\n try {\\n throw new Error(\\\"test\\\");\\n } catch (error) {\\n console.log(error);\\n }\\n throw new Error(\\\"test\\\");\\n function insideTry() {\\n console.log(\\\"inside try\\\");\\n }\\n} catch (error) {\\n console.log(error);\\n function insideCatch() {\\n console.log(\\\"inside catch\\\");\\n }\\n}`,\\n errors: [\\n { messageId: \\\"emptyLineRequired\\\" },\\n { messageId: \\\"emptyLineRequired\\\" },\\n { messageId: \\\"emptyLineRequired\\\" },\\n ],\\n output: `try {\\n try {\\n throw new Error(\\\"test\\\");\\n } catch (error) {\\n console.log(error);\\n }\\n\\n throw new Error(\\\"test\\\");\\n\\n function insideTry() {\\n console.log(\\\"inside try\\\");\\n }\\n} catch (error) {\\n console.log(error);\\n\\n function insideCatch() {\\n console.log(\\\"inside catch\\\");\\n }\\n}`,\\n },\\n {\\n code: `class TestClass {\\n constructor() {\\n console.log(\\\"constructor\\\");\\n }\\n testMethod() {\\n console.log(\\\"method\\\");\\n }\\n testMethod2() {\\n console.log(\\\"method\\\");\\n }\\n}`,\\n errors: [\\n { messageId: \\\"emptyLineRequired\\\" },\\n { messageId: \\\"emptyLineRequired\\\" },\\n { messageId: \\\"emptyLineRequired\\\" },\\n { messageId: \\\"emptyLineRequired\\\" },\\n ],\\n output: `class TestClass {\\n constructor() {\\n console.log(\\\"constructor\\\");\\n }\\n\\n testMethod() {\\n console.log(\\\"method\\\");\\n }\\n\\n testMethod2() {\\n console.log(\\\"method\\\");\\n }\\n}`,\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\n\\nrunTests(\\\"must-put-empty-line\\\", ruleMustPutEmptyLine, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'must-use-example-domain.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree } from \\\"@typescript-eslint/utils\\\";\\nimport { RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\n\\nconst constants = {\\n url: \\\"https://example.com/rules/\\\",\\n ruleName: \\\"must-use-example-domain\\\",\\n messageIds: {\\n invalidEmailDomain: \\\"invalidEmailDomain\\\",\\n },\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Test email addresses must use @example.com domain\\\",\\n },\\n messages: {\\n invalidEmailDomain: \\\"Email address must use @example.com domain: '{{ email }}'\\\",\\n },\\n schema: [],\\n },\\n email: {\\n requiredDomain: \\\"@example.com\\\",\\n atSymbol: \\\"@\\\",\\n },\\n regex: {\\n allAtSymbols: /@/g,\\n },\\n testFilePattern: /(?:\\\\.test|\\\\.spec)\\\\.(ts|tsx|js|jsx)$/,\\n types: {\\n string: \\\"string\\\",\\n },\\n nodeKeys: {\\n value: \\\"value\\\",\\n },\\n} as const;\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${constants.url}${ruleName}`);\\n\\nconst mustUseExampleDomain = createRule<[], typeof constants.messageIds.invalidEmailDomain>({\\n name: constants.ruleName,\\n meta: constants.meta,\\n defaultOptions: [],\\n\\n create(context: RuleContext) {\\n const filename = context.filename;\\n\\n if (!constants.testFilePattern.test(filename)) {\\n return {};\\n }\\n\\n function reportInvalidEmails(email: string, node: TSESTree.Node) {\\n const atSymbolCount = email.split(constants.regex.allAtSymbols).length - 1;\\n\\n if (atSymbolCount !== 1) {\\n return;\\n }\\n\\n if (email.startsWith(constants.email.atSymbol)) {\\n return;\\n }\\n\\n if (!email.endsWith(constants.email.requiredDomain)) {\\n context.report({\\n node,\\n messageId: constants.messageIds.invalidEmailDomain,\\n data: { email },\\n });\\n }\\n }\\n\\n return {\\n Literal(node: TSESTree.Literal) {\\n const value = node[constants.nodeKeys.value];\\n\\n if (typeof value === \\\"string\\\") {\\n reportInvalidEmails(value, node);\\n }\\n },\\n };\\n },\\n});\\n\\nexport default mustUseExampleDomain;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport mustUseExampleDomain from \\\"@root/rules/must-use-example-domain\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `const foo = \\\"test@example.com\\\";`,\\n filename: \\\"foo.spec.ts\\\",\\n },\\n {\\n code: `const bar = \\\"john.doe@example.com\\\";`,\\n filename: \\\"bar.test.ts\\\",\\n },\\n {\\n code: `const baz = \\\"just some string\\\";`,\\n filename: \\\"baz.spec.ts\\\",\\n },\\n {\\n code: `const qux = \\\"not@a@real@email\\\";`,\\n filename: \\\"qux.test.ts\\\",\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `const foo = \\\"user@gmail.com\\\";`,\\n errors: [\\n {\\n messageId: \\\"invalidEmailDomain\\\",\\n\\n // eslint-disable-next-line custom-eslint-rules/must-use-example-domain\\n data: { email: \\\"user@gmail.com\\\" },\\n },\\n ],\\n filename: \\\"foo.spec.ts\\\",\\n },\\n {\\n code: `const bar = \\\"someone@protonmail.com\\\";`,\\n errors: [\\n {\\n messageId: \\\"invalidEmailDomain\\\",\\n\\n // eslint-disable-next-line custom-eslint-rules/must-use-example-domain\\n data: { email: \\\"someone@protonmail.com\\\" },\\n },\\n ],\\n filename: \\\"bar.test.ts\\\",\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\n\\nrunTests(\\\"must-use-example-domain\\\", mustUseExampleDomain, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'must-use-function-for-component.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree, TSESLint } from \\\"@typescript-eslint/utils\\\";\\n\\nconst url = \\\"https://example.com/rules/\\\";\\nconst createRule = ESLintUtils.RuleCreator((ruleName) => `${url}${ruleName}`);\\n\\nfunction reportArrowComponent(\\n node: TSESTree.Node,\\n reportedNodes: Set,\\n context: TSESLint.RuleContext<\\\"mustUseFunctionForComponent\\\", []>,\\n) {\\n if (!reportedNodes.has(node)) {\\n reportedNodes.add(node);\\n context.report({\\n node,\\n messageId: \\\"mustUseFunctionForComponent\\\",\\n });\\n }\\n}\\n\\nfunction isReactFC(typeNode?: TSESTree.TypeNode): typeNode is TSESTree.TSTypeReference {\\n if (!typeNode) return false;\\n\\n if (typeNode.type === \\\"TSTypeReference\\\") {\\n const typeName = typeNode.typeName;\\n\\n if (\\n (typeName.type === \\\"TSQualifiedName\\\" &&\\n typeName.left.type === \\\"Identifier\\\" &&\\n typeName.left.name === \\\"React\\\" &&\\n typeName.right.type === \\\"Identifier\\\" &&\\n typeName.right.name === \\\"FC\\\") ||\\n (typeName.type === \\\"Identifier\\\" && typeName.name === \\\"FC\\\")\\n ) {\\n return true;\\n }\\n }\\n\\n return false;\\n}\\n\\nfunction isJSXNode(node?: TSESTree.Node): node is TSESTree.JSXElement | TSESTree.JSXFragment {\\n return !!node && (node.type === \\\"JSXElement\\\" || node.type === \\\"JSXFragment\\\");\\n}\\n\\ntype ChildGetter = (node: TSESTree.Node) => (TSESTree.Node | null | undefined)[];\\n\\nconst CHILDREN_MAP: Record = {\\n BlockStatement: (node) => (node.type === \\\"BlockStatement\\\" ? node.body : []),\\n ReturnStatement: (node) => (node.type === \\\"ReturnStatement\\\" ? [node.argument] : []),\\n ConditionalExpression: (node) =>\\n node.type === \\\"ConditionalExpression\\\" ? [node.test, node.consequent, node.alternate] : [],\\n LogicalExpression: (node) => (node.type === \\\"LogicalExpression\\\" ? [node.left, node.right] : []),\\n BinaryExpression: (node) => (node.type === \\\"BinaryExpression\\\" ? [node.left, node.right] : []),\\n CallExpression: (node) =>\\n node.type === \\\"CallExpression\\\"\\n ? node.arguments.filter((arg): arg is TSESTree.Expression => arg.type !== \\\"SpreadElement\\\")\\n : [],\\n ArrowFunctionExpression: (node) => (node.type === \\\"ArrowFunctionExpression\\\" ? [node.body] : []),\\n FunctionExpression: (node) => (node.type === \\\"FunctionExpression\\\" ? [node.body] : []),\\n IfStatement: (node) => (node.type === \\\"IfStatement\\\" ? [node.test, node.consequent, node.alternate] : []),\\n ExpressionStatement: (node) => (node.type === \\\"ExpressionStatement\\\" ? [node.expression] : []),\\n};\\n\\nfunction containsJSX(node?: TSESTree.Node, depth = 0): boolean {\\n if (!node || depth > 20) return false;\\n\\n if (isJSXNode(node)) return true;\\n\\n const getter = CHILDREN_MAP[node.type];\\n\\n if (!getter) return false;\\n\\n return Boolean(getter(node).some((child) => child && containsJSX(child, depth + 1)));\\n}\\n\\nfunction returnsJSX(node: TSESTree.FunctionExpression | TSESTree.ArrowFunctionExpression) {\\n if (node.body.type === \\\"BlockStatement\\\") {\\n return node.body.body.some(\\n (stmt) => stmt.type === \\\"ReturnStatement\\\" && stmt.argument && containsJSX(stmt.argument),\\n );\\n } else {\\n return Boolean(containsJSX(node.body));\\n }\\n}\\n\\nfunction isComponentLike(node: TSESTree.VariableDeclarator) {\\n return node.id.type === \\\"Identifier\\\" && /^[A-Z]/.test(node.id.name);\\n}\\n\\nfunction isReactMemoOrForwardRefCall(node: TSESTree.CallExpression) {\\n return (\\n node.callee.type === \\\"MemberExpression\\\" &&\\n node.callee.object.type === \\\"Identifier\\\" &&\\n node.callee.object.name === \\\"React\\\" &&\\n node.callee.property.type === \\\"Identifier\\\" &&\\n (node.callee.property.name === \\\"memo\\\" || node.callee.property.name === \\\"forwardRef\\\")\\n );\\n}\\n\\nfunction isTypedReactFC(node: TSESTree.VariableDeclarator) {\\n return !!node.id.typeAnnotation && isReactFC(node.id.typeAnnotation.typeAnnotation);\\n}\\n\\nfunction isArrowFunctionComponent(node: TSESTree.VariableDeclarator) {\\n if (!node.init) return false;\\n\\n return node.init.type === \\\"ArrowFunctionExpression\\\" && isComponentLike(node) && returnsJSX(node.init);\\n}\\n\\nfunction isReactMemoOrForwardRefComponent(node: TSESTree.VariableDeclarator) {\\n if (!node.init || node.init.type !== \\\"CallExpression\\\") return false;\\n\\n if (!isReactMemoOrForwardRefCall(node.init)) return false;\\n\\n const firstArg = node.init.arguments[0];\\n\\n return (\\n !!firstArg &&\\n (firstArg.type === \\\"ArrowFunctionExpression\\\" || firstArg.type === \\\"FunctionExpression\\\") &&\\n returnsJSX(firstArg)\\n );\\n}\\n\\nfunction isFunctionExpressionComponent(node: TSESTree.VariableDeclarator) {\\n if (!node.init || node.init.type !== \\\"FunctionExpression\\\") return false;\\n\\n if (node.init.id?.name) return false;\\n\\n return isComponentLike(node) && returnsJSX(node.init);\\n}\\n\\nfunction checkVariableDeclarator(\\n node: TSESTree.VariableDeclarator,\\n reportedNodes: Set,\\n context: TSESLint.RuleContext<\\\"mustUseFunctionForComponent\\\", []>,\\n) {\\n if (isTypedReactFC(node)) {\\n reportArrowComponent(node, reportedNodes, context);\\n return;\\n }\\n\\n if (isArrowFunctionComponent(node)) {\\n reportArrowComponent(node.init!, reportedNodes, context);\\n return;\\n }\\n\\n if (isReactMemoOrForwardRefComponent(node)) {\\n const init = node.init;\\n\\n if (init && init.type === \\\"CallExpression\\\") {\\n const firstArg = init.arguments[0];\\n\\n if (firstArg) {\\n reportArrowComponent(firstArg, reportedNodes, context);\\n }\\n }\\n }\\n\\n if (isFunctionExpressionComponent(node)) {\\n reportArrowComponent(node.init!, reportedNodes, context);\\n }\\n}\\n\\nconst mustUseFunctionForComponent = createRule({\\n name: \\\"must-use-function-for-component\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"React components must be declared using function declarations\\\",\\n },\\n messages: {\\n mustUseFunctionForComponent: \\\"React components must be declared using function declarations.\\\",\\n },\\n schema: [],\\n },\\n defaultOptions: [],\\n create(context) {\\n const reportedNodes = new Set();\\n return {\\n VariableDeclarator(node) {\\n checkVariableDeclarator(node, reportedNodes, context);\\n },\\n ExportNamedDeclaration(node) {\\n if (node.declaration && node.declaration.type === \\\"VariableDeclaration\\\") {\\n for (const decl of node.declaration.declarations) {\\n if (decl.type === \\\"VariableDeclarator\\\") {\\n checkVariableDeclarator(decl, reportedNodes, context);\\n }\\n }\\n }\\n },\\n };\\n },\\n});\\nexport default mustUseFunctionForComponent;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport rule from \\\"@root/rules/must-use-function-for-component\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\nfunction Foo() {\\n return
Bar
;\\n};\\n `,\\n },\\n {\\n code: `\\nconst Foo = function AnotherComponent() {\\n return
Bar
;\\n};\\n `,\\n },\\n {\\n code: `\\nfunction NotAComponent() {\\n const data = {\\n a: {\\n b: {\\n c: {\\n d: {\\n e: {\\n f: {\\n g: {\\n h: {\\n i: {\\n j: {\\n k: null\\n }\\n }\\n }\\n }\\n }\\n }\\n }\\n }\\n }\\n }\\n };\\n return null;\\n};\\n `,\\n },\\n {\\n code: `\\n function Foo() {\\n function Inner() {\\n return
Inner
;\\n }\\n return ;\\n }\\n `,\\n },\\n {\\n code: `\\n export function Foo() {\\n return
Bar
;\\n }\\n `,\\n },\\n {\\n code: `\\n function Foo() {\\n return
Foo
;\\n }\\n const MemoFoo = React.memo(Foo);\\n `,\\n },\\n {\\n code: `\\n function Foo({ value }: { value: T }) {\\n return
{String(value)}
;\\n }\\n `,\\n },\\n {\\n code: `\\n export default function Foo() {\\n return
Bar
;\\n }\\n `,\\n },\\n {\\n code: `\\n function Foo() {\\n if (true) {\\n return
If JSX
;\\n }\\n return null;\\n }\\n `,\\n },\\n {\\n code: `\\n function Foo() {\\n
Expression JSX
;\\n return null;\\n }\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\nconst Foo = () => {\\n return
Bar
;\\n};\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\nconst Foo: React.FC = () => {\\n return
Bar
;\\n};\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\nexport const Foo = () => {\\n return
Bar
;\\n};\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\nfunction Foo() {\\n const InnerComponent = () =>
Bar
;\\n return null;\\n}\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\nconst Foo = React.memo(() =>
Bar
);\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\nconst Foo = React.forwardRef((props, ref) =>
);\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\n function Foo() {\\n const Inner = () =>
Inner
;\\n return ;\\n }\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\n export const Foo = () => {\\n return
Bar
;\\n };\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\n const Foo = React.memo(() =>
Bar
);\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\n const Foo = ({ value }: { value: T }) => {\\n return
{String(value)}
;\\n };\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\n const Foo = React.forwardRef((props, ref) => {\\n return
Ref
;\\n });\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\n\\nrunTests(\\\"must-use-function-for-component\\\", rule, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'must-use-interface-for-props.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree, AST_NODE_TYPES } from \\\"@typescript-eslint/utils\\\";\\n\\nfunction isReactFCType(typeRef: TSESTree.TSTypeReference): boolean {\\n return (\\n typeRef.type === ruleConstants.nodeTypes.typeReference &&\\n typeRef.typeName.type === ruleConstants.nodeTypes.qualifiedName &&\\n typeRef.typeName.left.type === ruleConstants.nodeTypes.identifier &&\\n typeRef.typeName.left.name === ruleConstants.react.namespace &&\\n typeRef.typeName.right.name === ruleConstants.react.fcComponent\\n );\\n}\\n\\nconst ruleConstants = {\\n ruleName: \\\"must-use-interface-for-props\\\",\\n urlBase: \\\"https://example.com/rules/\\\",\\n description: \\\"Enforce using interfaces for React component props\\\",\\n errorMessage: \\\"Use interface instead of type alias for React component props\\\",\\n messageId: \\\"useInterface\\\",\\n nodeTypes: {\\n typeReference: AST_NODE_TYPES.TSTypeReference,\\n qualifiedName: AST_NODE_TYPES.TSQualifiedName,\\n identifier: AST_NODE_TYPES.Identifier,\\n typeAlias: AST_NODE_TYPES.TSTypeAliasDeclaration,\\n },\\n react: {\\n namespace: \\\"React\\\",\\n fcComponent: \\\"FC\\\",\\n },\\n} as const;\\n\\ntype MessageIds = typeof ruleConstants.messageId;\\ntype Options = [];\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName) => `${ruleConstants.urlBase}${ruleName}`);\\n\\nconst mustUseInterfaceForProps = createRule({\\n name: ruleConstants.ruleName,\\n meta: {\\n type: \\\"suggestion\\\",\\n docs: {\\n description: ruleConstants.description,\\n },\\n messages: {\\n [ruleConstants.messageId]: ruleConstants.errorMessage,\\n },\\n schema: [],\\n },\\n defaultOptions: [],\\n create: (context) => {\\n const findTypeDefinition = (identifier: string, node: TSESTree.Node) => {\\n const scope = context.sourceCode.getScope(node);\\n const variable = scope.variables.find((v) => v.name === identifier);\\n return variable?.defs[0]?.node;\\n };\\n\\n return {\\n VariableDeclarator(node) {\\n if (!node.id?.typeAnnotation?.typeAnnotation) return;\\n\\n const typeRef = node.id.typeAnnotation.typeAnnotation;\\n\\n if (typeRef.type !== ruleConstants.nodeTypes.typeReference) return;\\n\\n if (!isReactFCType(typeRef)) return;\\n\\n const typeParams = typeRef.typeArguments?.params;\\n\\n if (typeParams?.[0]?.type === ruleConstants.nodeTypes.typeReference) {\\n const propType = typeParams[0];\\n\\n if (propType.typeName.type === ruleConstants.nodeTypes.identifier) {\\n const definition = findTypeDefinition(propType.typeName.name, node);\\n\\n if (definition?.type === ruleConstants.nodeTypes.typeAlias) {\\n context.report({\\n node: propType,\\n messageId: ruleConstants.messageId,\\n });\\n context.report({\\n node: definition,\\n messageId: ruleConstants.messageId,\\n });\\n }\\n }\\n }\\n },\\n };\\n },\\n});\\n\\nexport default mustUseInterfaceForProps;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport rule from \\\"@root/rules/must-use-interface-for-props\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `interface MyComponentPropsInterface {\\n title: string;\\n description: string;\\n}\\n\\nexport const MyComponentInterface: React.FC = ({ title, description }) => {\\n return (\\n
\\n

{title}

\\n

{description}

\\n
\\n );\\n};\\n`,\\n },\\n {\\n code: `type NonPropsType = {\\n name: string;\\n};\\n\\nconst data: NonPropsType = { name: \\\"Test\\\" };\\n`,\\n },\\n {\\n code: `interface GenericProps {\\n data: T;\\n onUpdate: (data: T) => void;\\n}\\n\\nconst GenericComponent: React.FC> = ({ data, onUpdate }) => {\\n return
{data}
;\\n};\\n`,\\n },\\n {\\n code: `interface BaseProps {\\n className?: string;\\n}\\n\\ninterface ButtonProps extends BaseProps {\\n onClick: () => void;\\n}\\n\\nconst Button: React.FC = ({ onClick, className }) => {\\n return ;\\n};\\n`,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `type MyComponentPropsType = {\\n title: string;\\n description: string;\\n};\\n\\nexport const MyComponentType: React.FC = ({ title, description }) => {\\n return (\\n
\\n

{title}

\\n

{description}

\\n
\\n );\\n};\\n`,\\n errors: [{ messageId: \\\"useInterface\\\" }, { messageId: \\\"useInterface\\\" }],\\n },\\n {\\n code: `type GenericPropsType = {\\n data: T;\\n onUpdate: (data: T) => void;\\n};\\n\\nconst GenericComponent: React.FC> = ({ data, onUpdate }) => {\\n return
{data}
;\\n};\\n`,\\n errors: [{ messageId: \\\"useInterface\\\" }, { messageId: \\\"useInterface\\\" }],\\n },\\n {\\n code: `type StyleProps = {\\n className?: string;\\n style?: React.CSSProperties;\\n};\\n\\ntype ButtonProps = StyleProps & {\\n onClick: () => void;\\n};\\n\\nconst Button: React.FC = (props) => {\\n return ;\\n};\\n`,\\n errors: [{ messageId: \\\"useInterface\\\" }, { messageId: \\\"useInterface\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\n\\nrunTests(\\\"must-use-interface-for-props\\\", rule, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'must-use-nameof-for-props.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree, AST_NODE_TYPES } from \\\"@typescript-eslint/utils\\\";\\nimport { RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\n\\nconst constants = {\\n url: \\\"https://example.com/rules/\\\",\\n ruleName: \\\"must-use-nameof-for-props\\\",\\n messageIds: {\\n mustUseNameOf: \\\"mustUseNameOf\\\",\\n },\\n meta: {\\n type: \\\"suggestion\\\",\\n docs: {\\n description: \\\"Enforce the use of nameOf function for Props objects\\\",\\n },\\n messages: {\\n mustUseNameOf: \\\"Must use nameOf function for Props object property '{{propertyName}}'\\\",\\n },\\n schema: [],\\n },\\n nodeTypes: {\\n objectExpression: AST_NODE_TYPES.ObjectExpression,\\n property: AST_NODE_TYPES.Property,\\n identifier: AST_NODE_TYPES.Identifier,\\n literal: AST_NODE_TYPES.Literal,\\n callExpression: AST_NODE_TYPES.CallExpression,\\n variableDeclaration: AST_NODE_TYPES.VariableDeclaration,\\n variableDeclarator: AST_NODE_TYPES.VariableDeclarator,\\n exportNamedDeclaration: AST_NODE_TYPES.ExportNamedDeclaration,\\n exportDefaultDeclaration: AST_NODE_TYPES.ExportDefaultDeclaration,\\n asExpression: AST_NODE_TYPES.TSAsExpression,\\n },\\n suffixes: {\\n props: \\\"Props\\\",\\n },\\n properties: {\\n name: \\\"name\\\",\\n id: \\\"id\\\",\\n value: \\\"value\\\",\\n callee: \\\"callee\\\",\\n object: \\\"object\\\",\\n },\\n types: {\\n string: \\\"string\\\",\\n },\\n functions: {\\n nameOf: \\\"nameOf\\\",\\n },\\n} as const;\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${constants.url}${ruleName}`);\\n\\nfunction getVariableNameFromDeclarator(declarator: TSESTree.VariableDeclarator): string {\\n return declarator.id.type === constants.nodeTypes.identifier ? declarator.id.name : \\\"\\\";\\n}\\n\\nfunction checkVariableDeclarator(declarator: TSESTree.VariableDeclarator): boolean {\\n const variableName = getVariableNameFromDeclarator(declarator);\\n return variableName.endsWith(constants.suffixes.props);\\n}\\n\\nfunction isPropsObjectDeclaration(node: TSESTree.ObjectExpression) {\\n const parent = node.parent;\\n\\n if (parent?.type === constants.nodeTypes.variableDeclarator) {\\n return checkVariableDeclarator(parent);\\n }\\n\\n if (parent?.type === constants.nodeTypes.asExpression) {\\n const grandParent = parent.parent;\\n\\n if (grandParent?.type === constants.nodeTypes.variableDeclarator) {\\n return checkVariableDeclarator(grandParent);\\n }\\n }\\n\\n return false;\\n}\\n\\nfunction isNameOfCall(node: TSESTree.Node) {\\n return (\\n node.type === constants.nodeTypes.callExpression &&\\n node.callee.type === constants.nodeTypes.identifier &&\\n node.callee.name === constants.functions.nameOf\\n );\\n}\\n\\nfunction checkPropsObject(\\n node: TSESTree.ObjectExpression,\\n context: RuleContext,\\n) {\\n for (const property of node.properties) {\\n if (property.type === constants.nodeTypes.property) {\\n const propertyValue = property.value;\\n const propertyKey = property.key;\\n\\n let propertyName = \\\"\\\";\\n\\n if (propertyKey.type === constants.nodeTypes.identifier) {\\n propertyName = propertyKey.name;\\n } else if (\\n propertyKey.type === constants.nodeTypes.literal &&\\n typeof propertyKey.value === constants.types.string\\n ) {\\n propertyName = String(propertyKey.value);\\n }\\n\\n if (!isNameOfCall(propertyValue)) {\\n context.report({\\n node: property,\\n messageId: constants.messageIds.mustUseNameOf,\\n data: { propertyName },\\n });\\n }\\n }\\n }\\n}\\n\\nconst mustUseNameOfForProps = createRule<[], typeof constants.messageIds.mustUseNameOf>({\\n name: constants.ruleName,\\n meta: constants.meta,\\n defaultOptions: [],\\n create(context) {\\n return {\\n [constants.nodeTypes.objectExpression](node: TSESTree.ObjectExpression) {\\n if (!isPropsObjectDeclaration(node)) return;\\n\\n checkPropsObject(node, context);\\n },\\n };\\n },\\n});\\n\\nexport default mustUseNameOfForProps;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport mustUseNameOfForProps from \\\"@root/rules/must-use-nameof-for-props\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n export const nameOf = (key) => key.toString(); \\n export const fooProps = {\\n id: nameOf(\\\"id\\\"),\\n permission: nameOf(\\\"permission\\\"),\\n } as const;\\n `,\\n },\\n {\\n code: `\\n const nameOf = (key) => key.toString(); \\n const barProps = {\\n type: nameOf(\\\"type\\\"),\\n size: nameOf(\\\"size\\\"),\\n };\\n `,\\n },\\n {\\n code: `\\n function nameOf(key) { return key.toString(); } \\n export const bazProps = {\\n name: nameOf(\\\"name\\\"),\\n email: nameOf(\\\"email\\\"),\\n } as const;\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n export const nameOf = (key) => key.toString(); \\n export const fooProps = {\\n id: \\\"id\\\",\\n permission: nameOf(\\\"permission\\\"),\\n } as const;\\n `,\\n errors: [{ messageId: \\\"mustUseNameOf\\\", data: { propertyName: \\\"id\\\" } }],\\n },\\n {\\n code: `\\n const nameOf = (key) => key.toString();\\n const barProps = {\\n type: \\\"type\\\",\\n size: nameOf(\\\"size\\\"),\\n };\\n `,\\n errors: [{ messageId: \\\"mustUseNameOf\\\", data: { propertyName: \\\"type\\\" } }],\\n },\\n {\\n code: `\\n const nameOf = (key) => key.toString(); \\n const bazProps = {\\n name: \\\"name\\\", \\n email: \\\"email\\\", \\n } as const;\\n `,\\n errors: [\\n { messageId: \\\"mustUseNameOf\\\", data: { propertyName: \\\"name\\\" } },\\n { messageId: \\\"mustUseNameOf\\\", data: { propertyName: \\\"email\\\" } },\\n ],\\n },\\n ],\\n};\\n\\nconst edgeCases = {\\n valid: [\\n {\\n code: `\\n const nameOf = (key) => key.toString();\\n const regularObject = {\\n id: \\\"id\\\", \\n name: \\\"name\\\"\\n };\\n `,\\n },\\n ],\\n invalid: [\\n {\\n code: `\\n const nameOf = (key) => key.toString(); \\n const quxProps = {\\n id: nameOf(\\\"id\\\"),\\n columns: nameOf(\\\"columns\\\"), \\n sortKey: \\\"name\\\"\\n };\\n `,\\n errors: [{ messageId: \\\"mustUseNameOf\\\", data: { propertyName: \\\"sortKey\\\" } }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases, edgeCases];\\nrunTests(\\\"must-use-nameof-for-props\\\", mustUseNameOfForProps, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'must-use-native-private.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree } from \\\"@typescript-eslint/utils\\\";\\nimport { RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\n\\nconst constants = {\\n url: \\\"https://example.com/rules/\\\",\\n ruleName: \\\"must-use-native-private\\\",\\n messageIds: {\\n mustUseNativePrivate: \\\"mustUseNativePrivate\\\",\\n },\\n meta: {\\n type: \\\"suggestion\\\",\\n docs: {\\n description: \\\"Disallow the use of 'private' modifier in favor of '#privateField'.\\\",\\n },\\n messages: {\\n mustUseNativePrivate: \\\"Use private fields with '#' instead of 'private'.\\\",\\n },\\n schema: [],\\n },\\n nodeTypes: {\\n propertyDefinition: TSESTree.AST_NODE_TYPES.PropertyDefinition,\\n methodDefinition: TSESTree.AST_NODE_TYPES.MethodDefinition,\\n TSParameterProperty: TSESTree.AST_NODE_TYPES.TSParameterProperty,\\n identifier: TSESTree.AST_NODE_TYPES.Identifier,\\n classDeclaration: TSESTree.AST_NODE_TYPES.ClassDeclaration,\\n classExpression: TSESTree.AST_NODE_TYPES.ClassExpression,\\n program: TSESTree.AST_NODE_TYPES.Program,\\n },\\n accessModifiers: {\\n private: \\\"private\\\",\\n },\\n} as const;\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${constants.url}${ruleName}`);\\n\\nfunction isNodeInsideDeclaredClass(node: TSESTree.Node) {\\n let currentNode: TSESTree.Node | undefined = node.parent;\\n\\n while (currentNode) {\\n if (\\n currentNode.type === constants.nodeTypes.classDeclaration ||\\n currentNode.type === constants.nodeTypes.classExpression\\n ) {\\n return !!currentNode.declare;\\n }\\n\\n if (currentNode.type === constants.nodeTypes.program) {\\n break;\\n }\\n\\n currentNode = currentNode.parent;\\n }\\n\\n return false;\\n}\\n\\nconst mustUseNativePrivate = createRule<[], typeof constants.messageIds.mustUseNativePrivate>({\\n name: constants.ruleName,\\n meta: constants.meta,\\n defaultOptions: [],\\n\\n create(context: RuleContext) {\\n return {\\n [constants.nodeTypes.propertyDefinition](node: TSESTree.PropertyDefinition) {\\n if (node.declare || isNodeInsideDeclaredClass(node)) {\\n return;\\n }\\n\\n if (\\n node.key.type === constants.nodeTypes.identifier &&\\n node.accessibility === constants.accessModifiers.private\\n ) {\\n context.report({\\n node: node.key,\\n messageId: constants.messageIds.mustUseNativePrivate,\\n });\\n }\\n },\\n\\n [constants.nodeTypes.methodDefinition](node: TSESTree.MethodDefinition) {\\n if (isNodeInsideDeclaredClass(node)) {\\n return;\\n }\\n\\n if (\\n node.key.type === constants.nodeTypes.identifier &&\\n node.accessibility === constants.accessModifiers.private\\n ) {\\n context.report({\\n node: node.key,\\n messageId: constants.messageIds.mustUseNativePrivate,\\n });\\n }\\n },\\n\\n [constants.nodeTypes.TSParameterProperty](node: TSESTree.TSParameterProperty) {\\n if (isNodeInsideDeclaredClass(node)) {\\n return;\\n }\\n\\n if (\\n node.accessibility === constants.accessModifiers.private &&\\n node.parameter &&\\n node.parameter.type === constants.nodeTypes.identifier\\n ) {\\n context.report({\\n node: node.parameter,\\n messageId: constants.messageIds.mustUseNativePrivate,\\n });\\n }\\n },\\n };\\n },\\n});\\n\\nexport default mustUseNativePrivate;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport mustUseNativePrivate from \\\"@root/rules/must-use-native-private\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n class Foo {\\n #bar: string;\\n #baz = 42;\\n constructor(bar: string) {\\n this.#bar = bar;\\n }\\n #qux() { return 'ok'; }\\n getBar() {\\n return this.#bar;\\n }\\n }\\n `,\\n filename: \\\"example.ts\\\",\\n },\\n {\\n code: `\\n class Baz {\\n public qux = 0;\\n protected zap() {}\\n readonly type = \\\"baz\\\";\\n }\\n `,\\n filename: \\\"example.ts\\\",\\n },\\n {\\n code: `\\n declare class Lib {\\n private _foo: number;\\n private _bar(data: string): void;\\n constructor(key: string);\\n }\\n `,\\n filename: \\\"lib.d.ts\\\",\\n },\\n {\\n code: `\\n declare class Declared {\\n private _a: object;\\n private _b(): void;\\n constructor(config: object);\\n }\\n `,\\n filename: \\\"module.ts\\\",\\n },\\n {\\n code: `\\n class NoPrivate {\\n foo: string;\\n bar() {}\\n }\\n `,\\n filename: \\\"example.ts\\\",\\n },\\n {\\n code: `\\n abstract class AbstractFoo {\\n abstract doStuff(): void;\\n #state = {};\\n }\\n `,\\n filename: \\\"example.ts\\\",\\n },\\n {\\n code: `\\n declare abstract class AbstractLib {\\n private abstract run(): void;\\n private abstract data: string;\\n }\\n `,\\n filename: \\\"example.ts\\\",\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n class Foo {\\n private bar: string;\\n }\\n `,\\n errors: [{ messageId: \\\"mustUseNativePrivate\\\", line: 3, column: 23 }],\\n filename: \\\"example.ts\\\",\\n },\\n {\\n code: `\\n class Baz {\\n private qux(): void {}\\n }\\n `,\\n errors: [{ messageId: \\\"mustUseNativePrivate\\\", line: 3, column: 23 }],\\n filename: \\\"example.ts\\\",\\n },\\n {\\n code: `\\n class Qux {\\n constructor(private bar: string, readonly id: number) {}\\n }\\n `,\\n errors: [{ messageId: \\\"mustUseNativePrivate\\\", line: 3, column: 35 }],\\n filename: \\\"example.ts\\\",\\n },\\n {\\n code: `\\n class Bar {\\n constructor(private foo: number, private baz: string) {}\\n }\\n `,\\n errors: [\\n { messageId: \\\"mustUseNativePrivate\\\", line: 3, column: 35 },\\n { messageId: \\\"mustUseNativePrivate\\\", line: 3, column: 56 },\\n ],\\n filename: \\\"example.ts\\\",\\n },\\n {\\n code: `\\n class Singleton {\\n private static instance: Singleton;\\n }\\n `,\\n errors: [{ messageId: \\\"mustUseNativePrivate\\\", line: 3, column: 30 }],\\n filename: \\\"example.ts\\\",\\n },\\n {\\n code: `\\n class Logger {\\n private static log(message: string): void {}\\n }\\n `,\\n errors: [{ messageId: \\\"mustUseNativePrivate\\\", line: 3, column: 30 }],\\n filename: \\\"example.ts\\\",\\n },\\n {\\n code: `\\n class Circle {\\n private _radius: number = 0;\\n private get radius(): number { return this._radius; }\\n }\\n `,\\n errors: [\\n { messageId: \\\"mustUseNativePrivate\\\", line: 3, column: 23 },\\n { messageId: \\\"mustUseNativePrivate\\\", line: 4, column: 27 },\\n ],\\n filename: \\\"example.ts\\\",\\n },\\n {\\n code: `\\n class Box {\\n private _size: number = 0;\\n private set size(value: number) { this._size = value; }\\n }\\n `,\\n errors: [\\n { messageId: \\\"mustUseNativePrivate\\\", line: 3, column: 23 },\\n { messageId: \\\"mustUseNativePrivate\\\", line: 4, column: 27 },\\n ],\\n filename: \\\"example.ts\\\",\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"must-use-native-private\\\", mustUseNativePrivate, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'must-use-plural-enum-const-and-singular-type.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree } from \\\"@typescript-eslint/utils\\\";\\nimport { RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\n\\nconst constants = {\\n ruleName: \\\"must-use-plural-enum-const-and-singular-type\\\",\\n url: \\\"https://example.com/rules/\\\",\\n messageIds: {\\n pluralEnumConst: \\\"pluralEnumConst\\\",\\n singularEnumType: \\\"singularEnumType\\\",\\n mustUseIntegers: \\\"mustUseIntegers\\\",\\n },\\n meta: {\\n type: \\\"suggestion\\\",\\n docs: {\\n description: \\\"Enforce plural enum constant names, singular type names, and integer enum values\\\",\\n },\\n messages: {\\n pluralEnumConst: \\\"Enum constant '{{constName}}' should be in plural form.\\\",\\n singularEnumType: \\\"Type alias '{{typeName}}' should be in singular form.\\\",\\n mustUseIntegers: \\\"Enum constant '{{key}}' should have an integer value instead of '{{value}}'.\\\",\\n },\\n schema: [],\\n },\\n regexPatterns: {\\n plural: /(s|es|ies)$/i,\\n },\\n types: {\\n number: \\\"number\\\",\\n },\\n nodeTypes: {\\n property: \\\"Property\\\",\\n identifier: \\\"Identifier\\\",\\n literal: \\\"Literal\\\",\\n objectExpression: \\\"ObjectExpression\\\",\\n tsAsExpression: \\\"TSAsExpression\\\",\\n },\\n nodeKeys: {\\n name: \\\"name\\\",\\n expression: \\\"expression\\\",\\n properties: \\\"properties\\\",\\n key: \\\"key\\\",\\n value: \\\"value\\\",\\n },\\n} as const;\\n\\ntype MessageIds = keyof typeof constants.messageIds;\\ntype RuleOptions = [];\\n\\nfunction getObjectExpression(initNode?: TSESTree.Expression): TSESTree.ObjectExpression | undefined {\\n if (!initNode) return undefined;\\n\\n if (initNode.type === constants.nodeTypes.objectExpression) {\\n return initNode as TSESTree.ObjectExpression;\\n }\\n\\n if (initNode.type === constants.nodeTypes.tsAsExpression) {\\n const inner = (initNode as TSESTree.TSAsExpression)[constants.nodeKeys.expression];\\n\\n if (inner.type === constants.nodeTypes.objectExpression) {\\n return inner as TSESTree.ObjectExpression;\\n }\\n }\\n\\n return undefined;\\n}\\n\\nfunction isTypeAliasKeyofTypeQuery(typeAnn?: TSESTree.TypeNode): typeAnn is TSESTree.TSTypeOperator & {\\n typeAnnotation: TSESTree.TSTypeQuery & { exprName: TSESTree.Identifier };\\n} {\\n return (\\n !!typeAnn &&\\n typeAnn.type === \\\"TSTypeOperator\\\" &&\\n typeAnn.operator === \\\"keyof\\\" &&\\n !!typeAnn.typeAnnotation &&\\n typeAnn.typeAnnotation.type === \\\"TSTypeQuery\\\" &&\\n \\\"exprName\\\" in typeAnn.typeAnnotation &&\\n (typeAnn.typeAnnotation as TSESTree.TSTypeQuery).exprName.type === \\\"Identifier\\\"\\n );\\n}\\n\\nfunction isTypeAliasIndexedAccessType(typeAnn?: TSESTree.TypeNode): {\\n isMatch: boolean;\\n enumName?: string;\\n} {\\n if (\\n !typeAnn ||\\n typeAnn.type !== \\\"TSIndexedAccessType\\\" ||\\n !typeAnn.objectType ||\\n typeAnn.objectType.type !== \\\"TSTypeQuery\\\" ||\\n !typeAnn.indexType ||\\n typeAnn.indexType.type !== \\\"TSTypeOperator\\\" ||\\n typeAnn.indexType.operator !== \\\"keyof\\\"\\n ) {\\n return { isMatch: false };\\n }\\n\\n const objectTypeQuery = typeAnn.objectType as TSESTree.TSTypeQuery;\\n const indexTypeOperator = typeAnn.indexType as TSESTree.TSTypeOperator;\\n\\n // Check if object type is `typeof enumName`\\n if (\\n objectTypeQuery.exprName &&\\n objectTypeQuery.exprName.type === \\\"Identifier\\\" &&\\n indexTypeOperator.typeAnnotation &&\\n indexTypeOperator.typeAnnotation.type === \\\"TSTypeQuery\\\" &&\\n (indexTypeOperator.typeAnnotation as TSESTree.TSTypeQuery).exprName &&\\n (indexTypeOperator.typeAnnotation as TSESTree.TSTypeQuery).exprName.type === \\\"Identifier\\\"\\n ) {\\n const objectEnumName = objectTypeQuery.exprName.name;\\n const indexEnumName = (\\n (indexTypeOperator.typeAnnotation as TSESTree.TSTypeQuery).exprName as TSESTree.Identifier\\n ).name;\\n\\n // Both should reference the same enum\\n if (objectEnumName === indexEnumName) {\\n return { isMatch: true, enumName: objectEnumName };\\n }\\n }\\n\\n return { isMatch: false };\\n}\\n\\nfunction validateEnumConstName(node: TSESTree.Identifier, context: RuleContext<\\\"pluralEnumConst\\\", []>) {\\n const constName = node.name;\\n\\n if (!constants.regexPatterns.plural.test(constName)) {\\n context.report({\\n node,\\n messageId: constants.messageIds.pluralEnumConst,\\n data: { constName },\\n });\\n }\\n}\\n\\nfunction validateEnumProperties(\\n objectExpressionNode: TSESTree.ObjectExpression,\\n context: RuleContext,\\n) {\\n for (const prop of objectExpressionNode.properties) {\\n if (prop.type === constants.nodeTypes.property && prop.key.type === constants.nodeTypes.identifier) {\\n const valueNode = prop.value;\\n\\n if (valueNode.type === constants.nodeTypes.literal) {\\n const literalValue = valueNode.value;\\n\\n if (typeof literalValue !== constants.types.number) {\\n context.report({\\n node: valueNode,\\n messageId: constants.messageIds.mustUseIntegers,\\n data: {\\n key: context.sourceCode.getText(prop.key),\\n value: String(literalValue),\\n },\\n });\\n }\\n }\\n }\\n }\\n}\\n\\nfunction handleVariableDeclarator(\\n node: TSESTree.VariableDeclarator,\\n enumCandidates: { idNode: TSESTree.Identifier; objectExpr?: TSESTree.ObjectExpression }[],\\n) {\\n if (node.id.type === \\\"Identifier\\\") {\\n enumCandidates.push({\\n idNode: node.id,\\n objectExpr: getObjectExpression(node.init ?? undefined),\\n });\\n }\\n}\\n\\nfunction handleTypeAliasDeclaration(\\n node: TSESTree.TSTypeAliasDeclaration,\\n typeAliases: { node: TSESTree.TSTypeAliasDeclaration; typeName: string; enumName?: string }[],\\n) {\\n const typeName = node.id.name;\\n let enumName: string | undefined;\\n const typeAnn = node.typeAnnotation;\\n\\n if (isTypeAliasKeyofTypeQuery(typeAnn)) {\\n enumName = typeAnn.typeAnnotation.exprName.name;\\n } else {\\n const indexedAccessResult = isTypeAliasIndexedAccessType(typeAnn);\\n\\n if (indexedAccessResult.isMatch) {\\n enumName = indexedAccessResult.enumName;\\n }\\n }\\n\\n typeAliases.push({ node, typeName, enumName });\\n}\\n\\nfunction handleProgramExit(\\n enumCandidates: { idNode: TSESTree.Identifier; objectExpr?: TSESTree.ObjectExpression }[],\\n typeAliases: { node: TSESTree.TSTypeAliasDeclaration; typeName: string; enumName?: string }[],\\n context: RuleContext,\\n) {\\n for (const alias of typeAliases) {\\n if (alias.enumName) {\\n const found = enumCandidates.find((c) => c.idNode.name === alias.enumName && c.objectExpr);\\n\\n const objectExpr = found?.objectExpr;\\n\\n if (objectExpr) {\\n validateEnumConstName(found.idNode, context);\\n validateEnumProperties(objectExpr, context);\\n\\n if (constants.regexPatterns.plural.test(alias.typeName)) {\\n context.report({\\n node: alias.node.id,\\n messageId: constants.messageIds.singularEnumType,\\n data: { typeName: alias.typeName },\\n });\\n }\\n }\\n }\\n }\\n}\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName) => `${constants.url}${ruleName}`);\\n\\nconst mustUsePluralEnumConstAndSingularType = createRule({\\n name: constants.ruleName,\\n meta: constants.meta,\\n defaultOptions: [],\\n create(context) {\\n const enumCandidates: {\\n idNode: TSESTree.Identifier;\\n objectExpr?: TSESTree.ObjectExpression;\\n }[] = [];\\n const typeAliases: {\\n node: TSESTree.TSTypeAliasDeclaration;\\n typeName: string;\\n enumName?: string;\\n }[] = [];\\n\\n return {\\n VariableDeclarator(node: TSESTree.VariableDeclarator) {\\n handleVariableDeclarator(node, enumCandidates);\\n },\\n TSTypeAliasDeclaration(node: TSESTree.TSTypeAliasDeclaration) {\\n handleTypeAliasDeclaration(node, typeAliases);\\n },\\n \\\"Program:exit\\\"() {\\n handleProgramExit(enumCandidates, typeAliases, context);\\n },\\n };\\n },\\n});\\n\\nexport default mustUsePluralEnumConstAndSingularType;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport mustUsePluralEnumConstAndSingularType from \\\"@root/rules/must-use-plural-enum-const-and-singular-type\\\";\\n\\nconst validCases = {\\n valid: [\\n { code: `const nodeTypeIdentifiers = { foo: \\\"bar\\\", baz: \\\"qux\\\" };` },\\n { code: `const whatever = { foo: \\\"a\\\", bar: 1 };` },\\n { code: `export const foo = { bar: \\\"baz\\\", qux: 42 };` },\\n {\\n code: `\\n const nodeTypeIdentifiers = {\\n callExpression: \\\"CallExpression\\\",\\n identifier: \\\"Identifier\\\",\\n resourceId: \\\"resourceId\\\",\\n } as const;\\n `,\\n },\\n {\\n code: `\\n export const fooTypes = {\\n a: \\\"a\\\",\\n b: \\\"b\\\"\\n } as const;\\n `,\\n },\\n {\\n code: `\\n export const values = { foo: \\\"a\\\", bar: 1 } as const;\\n `,\\n },\\n {\\n code: `\\n export const value = { foo: 1, bar: 2 } as const;\\n `,\\n },\\n {\\n code: `\\n export const relationTypes = {\\n oneToOne: 0,\\n oneToMany: 1,\\n };\\n export type RelationType = (typeof relationTypes)[keyof typeof relationTypes];\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n export const values = { foo: \\\"a\\\", bar: 1 } as const;\\n export type Values = keyof typeof values;\\n `,\\n errors: [\\n { messageId: \\\"mustUseIntegers\\\", data: { key: \\\"foo\\\", value: \\\"a\\\" } },\\n { messageId: \\\"singularEnumType\\\", data: { typeName: \\\"Values\\\" } },\\n ],\\n },\\n {\\n code: `\\n export const value = { foo: 1, bar: 2 } as const;\\n export type Value = keyof typeof value;\\n `,\\n errors: [{ messageId: \\\"pluralEnumConst\\\", data: { constName: \\\"value\\\" } }],\\n },\\n {\\n code: `\\n export const values = { foo: 1, bar: 2 } as const;\\n export type Values = keyof typeof values;\\n `,\\n errors: [{ messageId: \\\"singularEnumType\\\", data: { typeName: \\\"Values\\\" } }],\\n },\\n {\\n code: `\\n export const bars = { foo: \\\"a\\\", bar: 1 } as const;\\n export type Bars = keyof typeof bars;\\n `,\\n errors: [\\n { messageId: \\\"mustUseIntegers\\\", data: { key: \\\"foo\\\", value: \\\"a\\\" } },\\n { messageId: \\\"singularEnumType\\\", data: { typeName: \\\"Bars\\\" } },\\n ],\\n },\\n {\\n code: `\\n export const relationTypes = {\\n oneToMany: 0,\\n manyToOne: 1,\\n manyToMany: 2,\\n };\\n export type RelationTypes = (typeof relationTypes)[keyof typeof relationTypes];\\n `,\\n errors: [{ messageId: \\\"singularEnumType\\\", data: { typeName: \\\"RelationTypes\\\" } }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\n\\nrunTests(\\\"must-use-plural-enum-const-and-singular-type\\\", mustUsePluralEnumConstAndSingularType, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'must-use-single-return-in-function.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree, AST_NODE_TYPES } from \\\"@typescript-eslint/utils\\\";\\nimport type { RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\n\\nconst constants = {\\n url: \\\"https://example.com/rules/\\\",\\n ruleName: \\\"must-use-single-return-in-function\\\",\\n\\n messageIds: {\\n singleReturn: \\\"singleReturn\\\",\\n },\\n\\n meta: {\\n type: \\\"suggestion\\\",\\n docs: {\\n description:\\n \\\"Functions must use a single return at the end, except for early parameter validation or switch-case.\\\",\\n },\\n messages: {\\n singleReturn: `Functions must use a single return at the end. \\n Refactor this function to use a variable to store the result \\n instead of multiple returns.`,\\n },\\n schema: [],\\n },\\n\\n objectKeys: {\\n parent: \\\"parent\\\",\\n type: \\\"type\\\",\\n },\\n} as const;\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${constants.url}${ruleName}`);\\n\\nfunction findParentIfStatement(returnStmt: TSESTree.ReturnStatement, functionBody: TSESTree.BlockStatement) {\\n let currentNode: TSESTree.Node | undefined = returnStmt;\\n let result: TSESTree.IfStatement | undefined;\\n\\n while (currentNode && currentNode !== functionBody) {\\n if (currentNode.type === AST_NODE_TYPES.IfStatement) {\\n result = currentNode;\\n break;\\n }\\n\\n currentNode = currentNode.parent;\\n }\\n\\n return result;\\n}\\n\\nfunction countNonValidationStatements(statements: TSESTree.Statement[], endIndex: number) {\\n let count = 0;\\n\\n for (let i = 0; i < endIndex; i++) {\\n const stmt = statements[i];\\n const isValidationStatement =\\n stmt?.type === AST_NODE_TYPES.VariableDeclaration ||\\n stmt?.type === AST_NODE_TYPES.ExpressionStatement ||\\n stmt?.type === AST_NODE_TYPES.IfStatement;\\n\\n if (!isValidationStatement) {\\n count++;\\n }\\n }\\n\\n return count;\\n}\\n\\nfunction isEarlyParameterValidation(\\n returnStmt: TSESTree.ReturnStatement,\\n functionBody: TSESTree.BlockStatement,\\n) {\\n const parentIfStatement = findParentIfStatement(returnStmt, functionBody);\\n let result = false;\\n\\n if (parentIfStatement && !parentIfStatement.alternate) {\\n const bodyStatements = functionBody.body;\\n const parentIfIndex = bodyStatements.findIndex((stmt) => stmt === parentIfStatement);\\n\\n if (parentIfIndex >= 0) {\\n const nonValidationCount = countNonValidationStatements(bodyStatements, parentIfIndex);\\n result = nonValidationCount <= 2;\\n }\\n }\\n\\n return result;\\n}\\n\\nfunction isInsideSwitchCase(returnStmt: TSESTree.ReturnStatement) {\\n let current: TSESTree.Node | undefined = returnStmt;\\n let result = false;\\n\\n while (current && !result) {\\n if (current.type === AST_NODE_TYPES.SwitchCase) {\\n result = true;\\n } else if (\\n current.type === AST_NODE_TYPES.FunctionDeclaration ||\\n current.type === AST_NODE_TYPES.FunctionExpression ||\\n current.type === AST_NODE_TYPES.ArrowFunctionExpression\\n ) {\\n break;\\n }\\n\\n current = current.parent;\\n }\\n\\n return result;\\n}\\n\\nfunction visitIfStatement(node: TSESTree.IfStatement, returns: TSESTree.ReturnStatement[]) {\\n visit(returns, node.test);\\n visit(returns, node.consequent);\\n visit(returns, node.alternate ?? undefined);\\n}\\n\\nfunction visitBlockStatement(node: TSESTree.BlockStatement, returns: TSESTree.ReturnStatement[]) {\\n for (const statement of node.body) {\\n visit(returns, statement);\\n }\\n}\\n\\nfunction visit(returns: TSESTree.ReturnStatement[], node?: TSESTree.Node) {\\n if (!node) {\\n return;\\n } else if (node.type === AST_NODE_TYPES.ReturnStatement) {\\n returns.push(node);\\n } else if (node.type === AST_NODE_TYPES.IfStatement) {\\n visitIfStatement(node, returns);\\n } else if (node.type === AST_NODE_TYPES.BlockStatement) {\\n visitBlockStatement(node, returns);\\n } else {\\n visitChildren(node, returns);\\n }\\n}\\n\\nfunction visitChildren(node: TSESTree.Node, returns: TSESTree.ReturnStatement[]) {\\n const record = node as unknown as Record;\\n\\n for (const key in record) {\\n if (key !== constants.objectKeys.parent) {\\n const child = record[key];\\n\\n if (child && typeof child === \\\"object\\\") {\\n if (Array.isArray(child)) {\\n child.forEach((item) => {\\n if (item && typeof item === \\\"object\\\" && constants.objectKeys.type in item) {\\n visit(returns, item as TSESTree.Node);\\n }\\n });\\n } else if (constants.objectKeys.type in child) {\\n visit(returns, child as TSESTree.Node);\\n }\\n }\\n }\\n }\\n}\\n\\nfunction findAllReturnStatements(node: TSESTree.Node) {\\n const returns: TSESTree.ReturnStatement[] = [];\\n visit(returns, node);\\n return returns;\\n}\\n\\nfunction isInNestedFunction(node: TSESTree.Node, functionBody: TSESTree.BlockStatement) {\\n let current: TSESTree.Node | undefined = node.parent;\\n let result = false;\\n\\n while (current && current !== functionBody && !result) {\\n if (\\n current.type === AST_NODE_TYPES.FunctionDeclaration ||\\n current.type === AST_NODE_TYPES.FunctionExpression ||\\n current.type === AST_NODE_TYPES.ArrowFunctionExpression\\n ) {\\n result = true;\\n }\\n\\n current = current.parent;\\n }\\n\\n return result;\\n}\\n\\nfunction splitReturns(returns: TSESTree.ReturnStatement[], functionBody: TSESTree.BlockStatement) {\\n const earlyReturns: TSESTree.ReturnStatement[] = [];\\n const regularReturns: TSESTree.ReturnStatement[] = [];\\n\\n for (const returnStmt of returns) {\\n if (!isInsideSwitchCase(returnStmt)) {\\n if (isEarlyParameterValidation(returnStmt, functionBody)) {\\n earlyReturns.push(returnStmt);\\n } else {\\n regularReturns.push(returnStmt);\\n }\\n }\\n }\\n\\n return { earlyReturns, regularReturns };\\n}\\n\\nfunction reportMultipleReturns(\\n returns: TSESTree.ReturnStatement[],\\n context: RuleContext,\\n) {\\n for (let i = 0; i < returns.length - 1; i++) {\\n const returnNode = returns[i];\\n\\n if (returnNode) {\\n context.report({\\n node: returnNode,\\n messageId: constants.messageIds.singleReturn,\\n });\\n }\\n }\\n}\\n\\nfunction analyzeFunction(\\n node: TSESTree.FunctionDeclaration | TSESTree.FunctionExpression | TSESTree.ArrowFunctionExpression,\\n context: RuleContext,\\n) {\\n if (node.body.type !== AST_NODE_TYPES.BlockStatement) {\\n return;\\n }\\n\\n const functionBody = node.body;\\n const allReturns = findAllReturnStatements(functionBody);\\n const directReturns = allReturns.filter((ret) => !isInNestedFunction(ret, functionBody));\\n\\n if (directReturns.length <= 1) return;\\n\\n const { earlyReturns, regularReturns } = splitReturns(directReturns, functionBody);\\n\\n if (earlyReturns.length > 1) {\\n for (let i = 1; i < earlyReturns.length; i++) {\\n const returnNode = earlyReturns[i];\\n\\n if (returnNode) {\\n context.report({\\n node: returnNode,\\n messageId: constants.messageIds.singleReturn,\\n });\\n }\\n }\\n }\\n\\n if (regularReturns.length > 1) {\\n reportMultipleReturns(regularReturns, context);\\n }\\n}\\n\\nconst mustUseSingleReturnInFunction = createRule<[], typeof constants.messageIds.singleReturn>({\\n name: constants.ruleName,\\n meta: constants.meta,\\n defaultOptions: [],\\n\\n create(context: RuleContext) {\\n return {\\n FunctionDeclaration(node) {\\n analyzeFunction(node, context);\\n },\\n FunctionExpression(node) {\\n analyzeFunction(node, context);\\n },\\n ArrowFunctionExpression(node) {\\n analyzeFunction(node, context);\\n },\\n };\\n },\\n});\\n\\nexport default mustUseSingleReturnInFunction;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport rule from \\\"@root/rules/must-use-single-return-in-function\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n function foo() {\\n const bar = getBaz();\\n let result = bar.qux;\\n if (bar.type === bar.baz) {\\n result = bar.baz;\\n }\\n if (bar.type === bar.qux) {\\n result = bar.qux;\\n }\\n \\n return result;\\n }\\n `,\\n },\\n\\n {\\n code: `\\n function foo(bar) {\\n if (!bar) {\\n return undefined; \\n }\\n \\n const result = doBaz(bar);\\n return result;\\n }\\n `,\\n },\\n\\n {\\n code: `\\n const foo = () => {\\n const bar = getBaz();\\n return bar;\\n };\\n `,\\n },\\n\\n {\\n code: `\\n const foo = () => getBaz();\\n `,\\n },\\n\\n {\\n code: `\\n function foo(bar) {\\n \\n if (typeof bar !== 'object') {\\n return undefined;\\n }\\n \\n const baz = doQux(bar);\\n let result = defaultVal;\\n \\n \\n if (baz.condition) {\\n result = baz.value;\\n }\\n \\n return result;\\n }\\n `,\\n },\\n\\n {\\n code: `\\n function foo() {\\n \\n function bar() {\\n if (condition) {\\n return true;\\n }\\n return false;\\n }\\n \\n const result = bar();\\n return result;\\n }\\n `,\\n },\\n {\\n code: `\\n function foo(bar) {\\n if (!bar) return \\\"missing\\\";\\n let result = bar.value;\\n if (bar.ok) result = bar.ok;\\n return result;\\n }\\n `,\\n },\\n {\\n code: `\\n function get(oDataConfig: ODataConfig) {\\n const dashboardReportId = getFilterValue(oDataConfig, dashboardDataProps.dashboardReportId);\\n switch (dashboardReportId) {\\n case reportIds.report1:\\n return getReportData1(dashboardReportId);\\n case reportIds.report2:\\n return getReportData2(dashboardReportId);\\n default:\\n throw createError(\\\"Dashboard report is not found\\\");\\n }\\n }\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n function foo() {\\n const bar = getBaz();\\n if (bar.type === bar.baz) {\\n return bar.baz;\\n }\\n if (bar.type === bar.qux) {\\n return bar.qux;\\n }\\n \\n return bar.quux;\\n }\\n `,\\n errors: [{ messageId: \\\"singleReturn\\\" }, { messageId: \\\"singleReturn\\\" }],\\n },\\n\\n {\\n code: `\\n const foo = (bar) => {\\n if (bar > 10) {\\n return \\\"baz\\\";\\n } else if (bar > 5) {\\n return \\\"qux\\\";\\n } else {\\n return \\\"quux\\\";\\n }\\n };\\n `,\\n errors: [{ messageId: \\\"singleReturn\\\" }, { messageId: \\\"singleReturn\\\" }],\\n },\\n\\n {\\n code: `\\n function foo(bar) {\\n const baz = doQux(bar);\\n \\n if (baz.type === \\\"A\\\") {\\n return doA(baz);\\n }\\n \\n if (baz.type === \\\"B\\\") {\\n return doB(baz);\\n }\\n \\n return doDefault(baz);\\n }\\n `,\\n errors: [{ messageId: \\\"singleReturn\\\" }, { messageId: \\\"singleReturn\\\" }],\\n },\\n\\n {\\n code: `\\n function foo(bar) {\\n if (!bar) {\\n return undefined; \\n }\\n \\n if (bar.invalid) {\\n return false; \\n }\\n \\n const result = doBaz(bar);\\n return result;\\n }\\n `,\\n errors: [{ messageId: \\\"singleReturn\\\" }],\\n },\\n {\\n code: `\\n function foo(bar) {\\n if (bar === \\\"a\\\") {\\n return \\\"A\\\";\\n } else if (bar === \\\"b\\\") {\\n return \\\"B\\\";\\n } else {\\n return \\\"C\\\";\\n }\\n }\\n `,\\n errors: [{ messageId: \\\"singleReturn\\\" }, { messageId: \\\"singleReturn\\\" }],\\n },\\n {\\n code: `\\n function foo(bar) {\\n const result = compute(bar);\\n if (bar.extra) return bar.extra;\\n return result;\\n }\\n `,\\n errors: [{ messageId: \\\"singleReturn\\\" }],\\n },\\n {\\n code: `\\n export const GET = httpApiWrapper(async () => {\\n const resourceNames = Array.from(getSearchableResources().keys());\\n if (!resourceNames) return apiBadRequestResponse([]);\\n return apiOkResponse(resourceNames);\\n });\\n `,\\n errors: [{ messageId: \\\"singleReturn\\\" }],\\n },\\n {\\n code: `\\n function getOAuthProvider(searchParams: URLSearchParams, customOAuthLoginConfigs: OAuthLoginConfig[]) {\\n const oAuthProvider = searchParams.get(authParam);\\n \\n if (oAuthProvider) return oAuthProvider;\\n \\n for (const customOAuthLoginConfig of customOAuthLoginConfigs) {\\n if (customOAuthLoginConfig.oAuthProviderUrlParam) {\\n const customOAuthProvider = searchParams.get(customOAuthLoginConfig.oAuthProviderUrlParam);\\n if (customOAuthProvider) return customOAuthProvider;\\n }\\n }\\n \\n return null;\\n }\\n `,\\n errors: [{ messageId: \\\"singleReturn\\\" }, { messageId: \\\"singleReturn\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"must-use-single-return-in-function\\\", rule, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'must-use-test-comments.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree, AST_NODE_TYPES } from \\\"@typescript-eslint/utils\\\";\\nimport { RuleContext, SourceCode } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\n\\nconst constants = {\\n url: \\\"https://example.com/rules/\\\",\\n ruleName: \\\"must-use-test-comments\\\",\\n messageIds: {\\n missingArrange: \\\"missingArrange\\\",\\n missingAct: \\\"missingAct\\\",\\n missingAssert: \\\"missingAssert\\\",\\n unnecessaryArrange: \\\"unnecessaryArrange\\\",\\n },\\n meta: {\\n type: \\\"suggestion\\\",\\n docs: {\\n description:\\n \\\"Require Act and Assert comments in tests. Arrange is required only if setup code exists before Act.\\\",\\n },\\n messages: {\\n missingArrange: \\\"You must add Arrange comment to the test\\\",\\n missingAct: \\\"You must add Act comment to the test\\\",\\n missingAssert: \\\"You must add Assert comment to the test\\\",\\n unnecessaryArrange: \\\"Arrange comment is unnecessary when there is no preparation code\\\",\\n },\\n schema: [],\\n },\\n nodeTypes: {\\n callExpression: AST_NODE_TYPES.CallExpression,\\n identifier: AST_NODE_TYPES.Identifier,\\n memberExpression: AST_NODE_TYPES.MemberExpression,\\n functionDeclaration: AST_NODE_TYPES.FunctionDeclaration,\\n arrowFunctionExpression: AST_NODE_TYPES.ArrowFunctionExpression,\\n functionExpression: AST_NODE_TYPES.FunctionExpression,\\n },\\n testNamePattern: /test$/i,\\n itFunctionName: \\\"it\\\",\\n commentInfo: {\\n arrange: {\\n pattern: /\\\\bArrange\\\\b/i,\\n text: \\\"// Arrange\\\\n\\\",\\n },\\n act: {\\n pattern: /\\\\bAct\\\\b/i,\\n text: \\\"// Act\\\\n\\\",\\n },\\n assert: {\\n pattern: /\\\\bAssert\\\\b/i,\\n text: \\\"// Assert\\\\n\\\",\\n },\\n },\\n} as const;\\n\\ntype MessageIds =\\n | typeof constants.messageIds.missingArrange\\n | typeof constants.messageIds.missingAct\\n | typeof constants.messageIds.missingAssert\\n | typeof constants.messageIds.unnecessaryArrange;\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${constants.url}${ruleName}`);\\n\\nfunction isTestFunction(node: TSESTree.CallExpression) {\\n const { callee } = node;\\n\\n if (callee.type === constants.nodeTypes.identifier) {\\n return constants.testNamePattern.test(callee.name) || callee.name === constants.itFunctionName;\\n }\\n\\n if (callee.type === constants.nodeTypes.memberExpression) {\\n const property = callee.property;\\n\\n if (property.type === constants.nodeTypes.identifier) {\\n return constants.testNamePattern.test(property.name);\\n }\\n }\\n\\n return false;\\n}\\n\\nfunction isInNestedFunction(node: TSESTree.CallExpression, sourceCode: SourceCode) {\\n const ancestors = sourceCode.getAncestors(node);\\n let insideTestFunction = false;\\n let nestedFunctionCount = 0;\\n\\n for (const ancestor of ancestors) {\\n if (ancestor.type === constants.nodeTypes.callExpression && isTestFunction(ancestor)) {\\n insideTestFunction = true;\\n }\\n\\n if (\\n insideTestFunction &&\\n (ancestor.type === constants.nodeTypes.functionDeclaration ||\\n ancestor.type === constants.nodeTypes.arrowFunctionExpression ||\\n ancestor.type === constants.nodeTypes.functionExpression)\\n ) {\\n nestedFunctionCount++;\\n\\n if (nestedFunctionCount > 1) {\\n return true;\\n }\\n }\\n }\\n\\n return false;\\n}\\n\\nfunction getTestBodyNode(node: TSESTree.CallExpression) {\\n if (node.arguments.length < 2) {\\n return null;\\n }\\n\\n const testCallback = node.arguments[1];\\n\\n if (!testCallback) {\\n return undefined;\\n }\\n\\n if (\\n testCallback.type === constants.nodeTypes.arrowFunctionExpression ||\\n testCallback.type === constants.nodeTypes.functionExpression\\n ) {\\n const { body } = testCallback;\\n\\n if (body.type === AST_NODE_TYPES.BlockStatement) {\\n return body;\\n }\\n }\\n\\n return null;\\n}\\n\\nfunction getActComment(comments: TSESTree.Comment[]) {\\n return comments.find((comment) => constants.commentInfo.act.pattern.test(comment.value.trim()));\\n}\\n\\nfunction hasSetupCodeBeforeAct(statementsBeforeAct: TSESTree.Statement[]) {\\n return statementsBeforeAct.some((statement) => statement.type !== AST_NODE_TYPES.EmptyStatement);\\n}\\n\\nfunction checkCommentsInTest(\\n node: TSESTree.CallExpression,\\n context: RuleContext,\\n sourceCode: SourceCode,\\n) {\\n if (isInNestedFunction(node, sourceCode)) {\\n return;\\n }\\n\\n const testBody = getTestBodyNode(node);\\n\\n if (!testBody) return;\\n\\n const comments = sourceCode.getCommentsInside\\n ? sourceCode.getCommentsInside(testBody)\\n : sourceCode\\n .getAllComments()\\n .filter(\\n (c: TSESTree.Comment) => c.range[0] >= testBody.range[0] && c.range[1] <= testBody.range[1],\\n );\\n\\n const actComment = getActComment(comments);\\n\\n if (!actComment) {\\n context.report({ node, messageId: constants.messageIds.missingAct });\\n return;\\n }\\n\\n const commentTexts = comments.map((c: TSESTree.Comment) => c.value.trim());\\n const hasArrange = commentTexts.some((text: string) => constants.commentInfo.arrange.pattern.test(text));\\n const hasAssert = commentTexts.some((text: string) => constants.commentInfo.assert.pattern.test(text));\\n\\n const arrangeActInSameComment = commentTexts.some(\\n (text: string) =>\\n constants.commentInfo.arrange.pattern.test(text) && constants.commentInfo.act.pattern.test(text),\\n );\\n\\n const statementsBeforeAct = testBody.body.filter((stmt) => stmt.range[1] < actComment.range[0]);\\n const hasRealSetupCode = hasSetupCodeBeforeAct(statementsBeforeAct);\\n\\n if (arrangeActInSameComment) {\\n if (!hasAssert) {\\n context.report({ node, messageId: constants.messageIds.missingAssert });\\n }\\n return;\\n }\\n\\n if (hasArrange && !hasRealSetupCode) {\\n context.report({ node, messageId: constants.messageIds.unnecessaryArrange });\\n }\\n\\n if (!hasArrange && hasRealSetupCode) {\\n context.report({ node, messageId: constants.messageIds.missingArrange });\\n }\\n\\n if (!hasAssert) {\\n context.report({ node, messageId: constants.messageIds.missingAssert });\\n }\\n}\\n\\nconst mustUseTestComments = createRule<[], MessageIds>({\\n name: constants.ruleName,\\n meta: constants.meta,\\n defaultOptions: [],\\n\\n create(context: RuleContext) {\\n const sourceCode = context.sourceCode;\\n return {\\n CallExpression(node: TSESTree.CallExpression) {\\n if (isTestFunction(node)) {\\n checkCommentsInTest(node, context, sourceCode);\\n }\\n },\\n };\\n },\\n});\\n\\nexport default mustUseTestComments;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport mustUseTestComments from \\\"@root/rules/must-use-test-comments\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n test(\\\"valid arrange\\\", () => {\\n // Arrange\\n const foo = 5;\\n // Act\\n const bar = doSomething(foo);\\n // Assert\\n expect(bar).toBe(10);\\n });\\n `,\\n },\\n {\\n code: `\\n test(\\\"no arrange, no prep code\\\", () => {\\n // Act\\n const bar = doSomething();\\n // Assert\\n expect(bar).toBe(10);\\n });\\n `,\\n },\\n {\\n code: `\\n test(\\\"should do something\\\", () => {\\n // Arrange\\n const foo = 5;\\n \\n // Act\\n const bar = doSomething(foo);\\n \\n // Assert\\n expect(bar).toBe(10);\\n });\\n `,\\n },\\n {\\n code: `\\n test(\\\"should do something\\\", () => {\\n // Arrange\\n const foo = 5;\\n\\n // Act\\n const bar = doSomething(foo);\\n\\n // Assert\\n expect(bar).toBe(10);\\n });\\n\\n `,\\n },\\n {\\n code: `\\n it.test(\\\"should do something\\\", () => {\\n // Arrange\\n const foo = 5;\\n \\n // Act\\n const bar = doSomething(foo);\\n \\n // Assert\\n expect(bar).toBe(10);\\n });\\n `,\\n },\\n {\\n code: `\\n test(\\\"outer test\\\", () => {\\n // Arrange\\n function innerFoo() {\\n test(\\\"not checked\\\")\\n return 5\\n }\\n // Act\\n const bar = innerFoo()\\n \\n // Assert\\n expect(bar).toBe(5)\\n })\\n `,\\n },\\n {\\n code: `\\n describe(\\\"test suite\\\", () => {\\n // This is not a test function\\n const foo = () => {};\\n });\\n `,\\n },\\n {\\n code: `\\n test(\\\"should ignore combined comments\\\", () => {\\n // Arrange, Act\\n const foo = 5;\\n const bar = doSomething(foo);\\n // Assert\\n expect(bar).toBe(10);\\n });\\n `,\\n },\\n {\\n code: `\\n test(\\\"should ignore comments with extra text\\\", () => {\\n // Arrange some setup\\n const foo = 5;\\n // Act when calling function\\n const bar = doSomething(foo);\\n // Assert the result\\n expect(bar).toBe(10);\\n });\\n `,\\n },\\n {\\n code: `\\n test(\\\"should ignore spaced combined comments\\\", () => {\\n // Arrange, Act\\n const foo = 5;\\n const bar = doSomething(foo);\\n // Assert\\n expect(bar).toBe(10);\\n });\\n `,\\n },\\n {\\n code: `\\n test(\\\"comments with extra text should be valid\\\", () => {\\n // Arrange some data\\n const foo = 5;\\n // Act on data\\n const bar = doSomething(foo);\\n // Assert results\\n expect(bar).toBe(10);\\n });\\n `,\\n },\\n {\\n code: `\\n test(\\\"combined comments should be valid\\\", () => {\\n // Arrange, Act\\n const foo = 5;\\n const bar = doSomething(foo);\\n // Assert\\n expect(bar).toBe(10);\\n });\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n test(\\\"unnecessary arrange comment\\\", () => {\\n // Arrange\\n // Act\\n doSomething();\\n // Assert\\n expect(true).toBe(true);\\n });\\n `,\\n errors: [{ messageId: \\\"unnecessaryArrange\\\" }],\\n },\\n {\\n code: `\\n test(\\\"missing arrange comment\\\", () => {\\n const foo = 5;\\n // Act\\n const bar = doSomething(foo);\\n // Assert\\n expect(bar).toBe(10);\\n });\\n `,\\n errors: [{ messageId: \\\"missingArrange\\\" }],\\n },\\n {\\n code: `\\n test(\\\"should do something else\\\", () => {\\n // Arrange\\n const foo = 5;\\n \\n // Act\\n const bar = doSomething(foo);\\n });\\n `,\\n errors: [{ messageId: \\\"missingAssert\\\" }],\\n },\\n {\\n code: `\\n it(\\\"should do something else\\\", () => {\\n // Arrange\\n const foo = 5;\\n });\\n `,\\n errors: [{ messageId: \\\"missingAct\\\" }],\\n },\\n {\\n code: `\\n test(\\\"no comments at all\\\", () => {\\n const foo = 5;\\n const bar = doSomething(foo);\\n expect(bar).toBe(10);\\n });\\n `,\\n errors: [{ messageId: \\\"missingAct\\\" }],\\n },\\n {\\n code: `\\n it.test(\\\"should do something\\\", () => {\\n // Some other comment\\n const foo = 5;\\n const bar = doSomething(foo);\\n expect(bar).toBe(10);\\n });\\n `,\\n errors: [{ messageId: \\\"missingAct\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"must-use-test-comments\\\", mustUseTestComments, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'must-use-usecallback-entry-shortcut.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESLint, TSESTree } from \\\"@typescript-eslint/utils\\\";\\n\\nconst ruleConstants = {\\n ruleName: \\\"must-use-usecallback-entry-shortcut\\\",\\n urlBase: \\\"https://example.com/rules/\\\",\\n description: \\\"Detects unnecessary useCallback wrappers around function calls\\\",\\n errorMessage: `Must use useCallback entry shortcut. \\n Avoid unnecessary arrow functions in useCallback; pass the function reference directly.\\n `,\\n messageId: \\\"useCallbackInUseCallback\\\",\\n nodeTypes: {\\n blockStatement: \\\"BlockStatement\\\",\\n expression: \\\"ExpressionStatement\\\",\\n arrayExpression: \\\"ArrayExpression\\\",\\n arrowFuncExpression: \\\"ArrowFunctionExpression\\\",\\n callExpression: \\\"CallExpression\\\",\\n identifier: \\\"Identifier\\\",\\n },\\n} as const;\\n\\ntype MessageIds = typeof ruleConstants.messageId;\\ntype Options = [];\\n\\nconst createRule = ESLintUtils.RuleCreator((name: string) => `${ruleConstants.urlBase}${name}`);\\n\\nconst useCallbackWithShortcut = createRule({\\n name: ruleConstants.ruleName,\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: ruleConstants.description,\\n },\\n messages: {\\n [ruleConstants.messageId]: ruleConstants.errorMessage,\\n },\\n schema: [],\\n },\\n defaultOptions: [],\\n create: (context) => {\\n return {\\n CallExpression(node: TSESTree.CallExpression) {\\n if (!isUseCallbackWithAtLeastTwoArgs(node)) {\\n return;\\n }\\n\\n const [callbackFn, depsArray] = node.arguments;\\n\\n if (\\n callbackFn?.type !== ruleConstants.nodeTypes.arrowFuncExpression ||\\n depsArray?.type !== ruleConstants.nodeTypes.arrayExpression ||\\n depsArray.elements.length === 0 ||\\n depsArray.elements.length > 1\\n ) {\\n return;\\n }\\n\\n checkCallbackBody(node, callbackFn, depsArray, context);\\n },\\n };\\n },\\n});\\n\\nexport default useCallbackWithShortcut;\\n\\nfunction isDirectFunctionCall(\\n functionBody: TSESTree.CallExpression,\\n dependencyArray: TSESTree.ArrayExpression,\\n) {\\n const firstElement = dependencyArray.elements[0];\\n\\n if (\\n functionBody.callee.type !== ruleConstants.nodeTypes.identifier ||\\n !firstElement ||\\n firstElement.type !== ruleConstants.nodeTypes.identifier\\n ) {\\n return false;\\n }\\n\\n return functionBody.callee.name === firstElement.name;\\n}\\n\\nfunction isBlockWithSingleFunctionCall(\\n blockStatement: TSESTree.BlockStatement,\\n dependencyArray: TSESTree.ArrayExpression,\\n) {\\n const statements = blockStatement.body;\\n\\n if (statements.length !== 1) {\\n return false;\\n }\\n\\n const firstStatement = statements[0];\\n\\n const firstElement = dependencyArray.elements[0];\\n\\n if (\\n firstStatement?.type !== ruleConstants.nodeTypes.expression ||\\n firstStatement.expression.type !== ruleConstants.nodeTypes.callExpression ||\\n firstStatement.expression.callee.type !== ruleConstants.nodeTypes.identifier ||\\n !firstElement ||\\n firstElement.type !== ruleConstants.nodeTypes.identifier\\n ) {\\n return false;\\n }\\n\\n return firstStatement.expression.callee.name === firstElement.name;\\n}\\n\\nfunction isArgumentsChanged(\\n callbackParams: TSESTree.Parameter[],\\n functionArgs: (TSESTree.Expression | TSESTree.SpreadElement)[],\\n) {\\n if (callbackParams.length !== functionArgs.length) {\\n return true;\\n }\\n\\n return callbackParams.some((param, index) => {\\n const arg = functionArgs[index];\\n\\n return !(\\n param.type === ruleConstants.nodeTypes.identifier &&\\n arg?.type === ruleConstants.nodeTypes.identifier &&\\n param.name === arg.name\\n );\\n });\\n}\\n\\nfunction isUseCallbackWithAtLeastTwoArgs(node: TSESTree.CallExpression): boolean {\\n return (\\n node.callee.type === ruleConstants.nodeTypes.identifier &&\\n node.callee.name === \\\"useCallback\\\" &&\\n node.arguments.length >= 2\\n );\\n}\\n\\nfunction checkCallbackBody(\\n node: TSESTree.CallExpression,\\n callbackFn: TSESTree.ArrowFunctionExpression,\\n depsArray: TSESTree.ArrayExpression,\\n context: Readonly>,\\n) {\\n if (callbackFn.body.type === ruleConstants.nodeTypes.callExpression) {\\n if (\\n isDirectFunctionCall(callbackFn.body, depsArray) &&\\n !isArgumentsChanged(callbackFn.params, callbackFn.body.arguments)\\n ) {\\n context.report({\\n node,\\n messageId: ruleConstants.messageId,\\n });\\n }\\n } else if (callbackFn.body.type === ruleConstants.nodeTypes.blockStatement) {\\n if (\\n isBlockWithSingleFunctionCall(callbackFn.body, depsArray) &&\\n callbackFn.body.body[0]?.type === ruleConstants.nodeTypes.expression &&\\n callbackFn.body.body[0].expression.type === ruleConstants.nodeTypes.callExpression &&\\n !isArgumentsChanged(callbackFn.params, callbackFn.body.body[0].expression.arguments)\\n ) {\\n context.report({\\n node,\\n messageId: ruleConstants.messageId,\\n });\\n }\\n }\\n}\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport rule from \\\"@root/rules/must-use-usecallback-entry-shortcut\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `useCallback(foo, [foo]);`,\\n },\\n {\\n code: `useCallback(myFunction, func)`,\\n },\\n {\\n code: `\\nconst sendAnalyticsEvent = (id: string) => {\\n return id;\\n}\\nconst handleClick = useCallback(sendAnalyticsEvent, [sendAnalyticsEvent]);\\n\\n;\\n}\\n `,\\n },\\n {\\n code: `\\nconst ComponentWithHandler = () => (\\n
\\n console.log(e.target.value)} />\\n
\\n);\\n `,\\n },\\n // Components using React hooks\\n {\\n code: `\\nfunction ComponentWithHooks() {\\n const [state, setState] = useState(0);\\n return
{state}
;\\n}\\n `,\\n },\\n {\\n code: `\\nconst ComponentWithHooks = () => {\\n const effect = useEffect(() => {}, []);\\n return
Hello
;\\n};\\n `,\\n },\\n // Components with hooks in conditional blocks\\n {\\n code: `\\nfunction ComponentWithConditionalHook() {\\n if (condition) {\\n const [state] = useState(0);\\n }\\n return
Hello
;\\n}\\n `,\\n },\\n // Components using browser APIs\\n {\\n code: `\\nfunction ComponentWithBrowserAPI() {\\n const data = localStorage.getItem('key');\\n return
{data}
;\\n}\\n `,\\n },\\n {\\n code: `\\nconst ComponentWithBrowserAPI = () => {\\n window.addEventListener('scroll', () => {});\\n return
Hello
;\\n};\\n `,\\n },\\n // Already async components\\n {\\n code: `\\nasync function AlreadyAsync() {\\n return
Already async
;\\n}\\n `,\\n },\\n {\\n code: `\\nconst AlreadyAsync = async () =>
Already async
;\\n `,\\n },\\n // Non-component functions (lowercase names)\\n {\\n code: `\\nfunction normalFunction() {\\n return \\\"Not a component\\\";\\n}\\n `,\\n },\\n {\\n code: `\\nconst normalFunction = () => {\\n return
lowercase name
;\\n};\\n `,\\n },\\n // Functions not returning JSX\\n {\\n code: `\\nfunction UtilFunction() {\\n return \\\"string value\\\";\\n}\\n `,\\n },\\n {\\n code: `\\nfunction DataProcessor() {\\n return { data: \\\"object\\\" };\\n}\\n `,\\n },\\n // Components with nested event handlers in children\\n {\\n code: `\\nfunction ComponentWithNestedHandlers() {\\n return (\\n
\\n Text\\n \\n
\\n );\\n}\\n `,\\n },\\n // Components using console API\\n {\\n code: `\\nfunction ComponentWithConsole() {\\n console.log('Debug message');\\n return
Hello
;\\n}\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n // Simple server components that should be async\\n {\\n code: `\\nfunction ServerComponent() {\\n return
Hello Server
;\\n}\\n `,\\n errors: [{ messageId: \\\"addAsync\\\" }],\\n output: `\\nasync function ServerComponent() {\\n return
Hello Server
;\\n}\\n `,\\n },\\n {\\n code: `\\nconst ServerComponent = () =>
Hello
;\\n `,\\n errors: [{ messageId: \\\"addAsync\\\" }],\\n output: `\\nconst ServerComponent = async () =>
Hello
;\\n `,\\n },\\n // Function expression components\\n {\\n code: `\\nconst ServerComponent = function() {\\n return
Hello Server
;\\n};\\n `,\\n errors: [{ messageId: \\\"addAsync\\\" }],\\n output: `\\nconst ServerComponent = async function() {\\n return
Hello Server
;\\n};\\n `,\\n },\\n // Components with React.createElement\\n {\\n code: `\\nfunction ServerComponent() {\\n return React.createElement('div', null, 'Hello');\\n}\\n `,\\n errors: [{ messageId: \\\"addAsync\\\" }],\\n output: `\\nasync function ServerComponent() {\\n return React.createElement('div', null, 'Hello');\\n}\\n `,\\n },\\n // Components with JSX fragments\\n {\\n code: `\\nfunction ServerComponent() {\\n return (\\n <>\\n
First
\\n
Second
\\n \\n );\\n}\\n `,\\n errors: [{ messageId: \\\"addAsync\\\" }],\\n output: `\\nasync function ServerComponent() {\\n return (\\n <>\\n
First
\\n
Second
\\n \\n );\\n}\\n `,\\n },\\n // Exported components\\n {\\n code: `\\nexport function ServerComponent() {\\n return
Exported component
;\\n}\\n `,\\n errors: [{ messageId: \\\"addAsync\\\" }],\\n output: `\\nexport async function ServerComponent() {\\n return
Exported component
;\\n}\\n `,\\n },\\n {\\n code: `\\nexport default function ServerComponent() {\\n return
Default export
;\\n}\\n `,\\n errors: [{ messageId: \\\"addAsync\\\" }],\\n output: `\\nexport default async function ServerComponent() {\\n return
Default export
;\\n}\\n `,\\n },\\n // Components with conditional returns\\n {\\n code: `\\nfunction ServerComponent() {\\n if (condition) {\\n return
Conditional JSX
;\\n }\\n return
Default JSX
;\\n}\\n `,\\n errors: [{ messageId: \\\"addAsync\\\" }],\\n output: `\\nasync function ServerComponent() {\\n if (condition) {\\n return
Conditional JSX
;\\n }\\n return
Default JSX
;\\n}\\n `,\\n },\\n // Components with complex JSX\\n {\\n code: `\\nfunction ComplexServerComponent() {\\n const data = processData();\\n return (\\n
\\n

Title

\\n

Content: {data}

\\n
    \\n {items.map(item =>
  • {item.name}
  • )}\\n
\\n
\\n );\\n}\\n `,\\n errors: [{ messageId: \\\"addAsync\\\" }],\\n output: `\\nasync function ComplexServerComponent() {\\n const data = processData();\\n return (\\n
\\n

Title

\\n

Content: {data}

\\n
    \\n {items.map(item =>
  • {item.name}
  • )}\\n
\\n
\\n );\\n}\\n `,\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\n\\nrunTests(\\\"server-component-must-be-async\\\", rule, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'use-function-without-parameter-shortcut.ts' and a test for it.\",\"rule_code\":\"import { TSESTree, ESLintUtils } from \\\"@typescript-eslint/utils\\\";\\nimport { RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\n\\nconst url = \\\"https://example.com/rules/\\\"; \\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${url}${ruleName}`);\\n\\nconst nodeTypeIdentifiers = {\\n identifier: \\\"Identifier\\\",\\n callExpression: \\\"CallExpression\\\",\\n blockStatement: \\\"BlockStatement\\\",\\n returnStatement: \\\"ReturnStatement\\\",\\n} as const;\\n\\ntype FunctionNode =\\n | TSESTree.FunctionExpression\\n | TSESTree.FunctionDeclaration\\n | TSESTree.ArrowFunctionExpression;\\n\\nconst useFunctionWithoutParameterShortcut = createRule({\\n name: \\\"use-function-without-parameter-shortcut\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Must use function without parameter shortcut\\\",\\n },\\n messages: {\\n useFunctionWithoutParameterShortcut: \\\"Must use function without parameter shortcut\\\",\\n },\\n schema: [],\\n },\\n create(context: RuleContext<\\\"useFunctionWithoutParameterShortcut\\\", []>) {\\n function isNestedFunction(node: FunctionNode): boolean {\\n const parent = node.parent;\\n if (!parent) return false;\\n\\n const functionTypes = new Set([\\n \\\"FunctionExpression\\\",\\n \\\"FunctionDeclaration\\\",\\n \\\"ArrowFunctionExpression\\\",\\n ]);\\n\\n let current = parent;\\n while (current) {\\n if (functionTypes.has(current.type)) {\\n return true;\\n }\\n if (current.type === \\\"Program\\\") break;\\n current = current.parent!;\\n }\\n\\n return false;\\n }\\n\\n function checkFunction(node: FunctionNode) {\\n if (node.params.length !== 1) return;\\n\\n const param = node.params[0];\\n if (!param || param.type !== nodeTypeIdentifiers.identifier) return;\\n\\n const paramName = param.name;\\n const body = node.body;\\n\\n if (!isNestedFunction(node)) {\\n return;\\n }\\n\\n if (\\n body.type === nodeTypeIdentifiers.callExpression &&\\n body.arguments.length === 1 &&\\n body.arguments[0]?.type === nodeTypeIdentifiers.identifier\\n ) {\\n const argIdentifier = body.arguments[0] as TSESTree.Identifier;\\n if (argIdentifier.name === paramName) {\\n context.report({\\n node,\\n messageId: \\\"useFunctionWithoutParameterShortcut\\\",\\n });\\n }\\n }\\n\\n if (\\n body.type === nodeTypeIdentifiers.blockStatement &&\\n body.body.length === 1 &&\\n body.body[0]?.type === nodeTypeIdentifiers.returnStatement\\n ) {\\n const returnArg = body.body[0].argument;\\n if (\\n returnArg &&\\n returnArg.type === nodeTypeIdentifiers.callExpression &&\\n returnArg.arguments.length === 1 &&\\n returnArg.arguments[0]?.type === nodeTypeIdentifiers.identifier\\n ) {\\n const argIdentifier = returnArg.arguments[0] as TSESTree.Identifier;\\n if (argIdentifier.name === paramName) {\\n context.report({\\n node,\\n messageId: \\\"useFunctionWithoutParameterShortcut\\\",\\n });\\n }\\n }\\n }\\n }\\n\\n return {\\n ArrowFunctionExpression: checkFunction,\\n FunctionExpression: checkFunction,\\n FunctionDeclaration: checkFunction,\\n };\\n },\\n defaultOptions: [],\\n});\\n\\nexport default useFunctionWithoutParameterShortcut;\",\"test_code\":\"import { runTests } from \\\"../test-utils/eslint-rule-tester\\\";\\nimport useFunctionWithoutParameterShortcut from \\\"../rules/use-function-without-parameter-shortcut\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: \\\"function foo(bar) {}\\\",\\n },\\n {\\n code: \\\"const foo = (value) => bar(value, 1);\\\",\\n },\\n {\\n code: \\\"const foo = (value) => { return bar(); }\\\",\\n },\\n {\\n code: \\\"const foo = (value, other) => bar(value);\\\",\\n },\\n {\\n code: \\\"const foo = value => { const x = value + 1; return bar(x); }\\\",\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: \\\"const foo = (value) => bar(value);\\\",\\n errors: [{ messageId: \\\"useFunctionWithoutParameterShortcut\\\" }],\\n },\\n {\\n code: \\\"const foo = function(value) { return bar(value); }\\\",\\n errors: [{ messageId: \\\"useFunctionWithoutParameterShortcut\\\" }],\\n },\\n {\\n code: \\\"function foo(value) { return bar(value); }\\\",\\n errors: [{ messageId: \\\"useFunctionWithoutParameterShortcut\\\" }],\\n },\\n {\\n code: \\\"const foo = (value) => { return bar(value); }\\\",\\n errors: [{ messageId: \\\"useFunctionWithoutParameterShortcut\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"use-function-without-parameter-shortcut\\\", useFunctionWithoutParameterShortcut, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'use-nullish-coalescing-for-default.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree, TSESLint } from \\\"@typescript-eslint/utils\\\";\\n\\nconst ruleConstants = {\\n ruleName: \\\"use-nullish-coalescing-for-default\\\",\\n urlBase: \\\"https://example.com/rules/\\\",\\n description:\\n \\\"Prefer using the nullish coalescing operator (??) instead of logical AND with null/undefined checks\\\",\\n errorMessage: \\\"Use nullish coalescing operator (??) instead of logical AND with null/undefined checks\\\",\\n messageId: \\\"useNullishCoalescing\\\",\\n nodeTypes: {\\n conditional: \\\"ConditionalExpression\\\",\\n logical: \\\"LogicalExpression\\\",\\n binary: \\\"BinaryExpression\\\",\\n literal: \\\"Literal\\\",\\n identifier: \\\"Identifier\\\",\\n },\\n} as const;\\n\\ntype MessageIds = typeof ruleConstants.messageId;\\ntype Options = [];\\n\\nconst createRule = ESLintUtils.RuleCreator((name: string) => `${ruleConstants.urlBase}${name}`);\\n\\nfunction getCheckedIdentifierName(node: TSESTree.BinaryExpression) {\\n if (node.left.type !== ruleConstants.nodeTypes.identifier) {\\n return undefined;\\n }\\n\\n return node.left.name;\\n}\\n\\nfunction getComparedValue(node: TSESTree.BinaryExpression): unknown {\\n if (node.right.type === ruleConstants.nodeTypes.literal) {\\n return node.right.value;\\n }\\n\\n if (node.right.type === ruleConstants.nodeTypes.identifier && node.right.name === \\\"undefined\\\") {\\n return undefined;\\n }\\n\\n return undefined;\\n}\\n\\nfunction isNullishAndExpression(node: TSESTree.LogicalExpression) {\\n if (node.operator !== \\\"&&\\\") {\\n return false;\\n }\\n\\n const leftSide = node.left;\\n const rightSide = node.right;\\n\\n if (leftSide.type !== ruleConstants.nodeTypes.binary || rightSide.type !== leftSide.type) {\\n return false;\\n }\\n\\n const leftName = getCheckedIdentifierName(leftSide);\\n const rightName = getCheckedIdentifierName(rightSide);\\n\\n if (leftName !== rightName) return false;\\n\\n const validOperators = [\\\"!==\\\"];\\n\\n if (!validOperators.includes(leftSide.operator) || !validOperators.includes(rightSide.operator)) {\\n return false;\\n }\\n\\n const leftValue = getComparedValue(leftSide);\\n const rightValue = getComparedValue(rightSide);\\n\\n const isNullish = (value: unknown) => value === null || value === undefined;\\n\\n return isNullish(leftValue) && isNullish(rightValue) && leftValue !== rightValue;\\n}\\n\\nfunction fixUseNullishCoalescing(\\n fixer: TSESLint.RuleFixer,\\n node: TSESTree.ConditionalExpression,\\n context: TSESLint.RuleContext,\\n) {\\n const sourceCode = context.sourceCode;\\n const consequentText = sourceCode.getText(node.consequent);\\n const alternateText = sourceCode.getText(node.alternate);\\n\\n return fixer.replaceText(node, `${consequentText} ?? ${alternateText}`);\\n}\\n\\nconst useNullishCoalescing = createRule({\\n name: ruleConstants.ruleName,\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: ruleConstants.description,\\n },\\n messages: {\\n [ruleConstants.messageId]: ruleConstants.errorMessage,\\n },\\n schema: [],\\n fixable: \\\"code\\\",\\n },\\n defaultOptions: [],\\n create: (context) => {\\n return {\\n ConditionalExpression(node: TSESTree.ConditionalExpression) {\\n const testNode = node.test;\\n const consequentNode = node.consequent;\\n\\n if (\\n testNode.type !== ruleConstants.nodeTypes.logical ||\\n consequentNode.type !== ruleConstants.nodeTypes.identifier\\n ) {\\n return;\\n }\\n\\n if (!isNullishAndExpression(testNode)) {\\n return;\\n }\\n\\n let searchName: string | undefined;\\n\\n if (testNode.left.type === ruleConstants.nodeTypes.binary) {\\n searchName = getCheckedIdentifierName(testNode.left);\\n }\\n\\n if (consequentNode.name === searchName) {\\n context.report({\\n node,\\n messageId: ruleConstants.messageId,\\n fix(fixer: TSESLint.RuleFixer) {\\n return fixUseNullishCoalescing(fixer, node, context);\\n },\\n });\\n }\\n },\\n };\\n },\\n});\\n\\nexport default useNullishCoalescing;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport rule from \\\"@root/rules/use-nullish-coalescing-for-default\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `const foo = bar ?? baz;`,\\n },\\n {\\n code: `const result = value ?? defaultValue;`,\\n },\\n {\\n code: `const a = x ?? y;`,\\n },\\n {\\n code: `const z = condition ? a : b;`,\\n },\\n {\\n code: `const value = x !== null && y !== undefined ? x : y;`,\\n },\\n {\\n code: `const value = x != null ? x : y;`,\\n },\\n {\\n code: `foo(x != null ? x : y);`,\\n },\\n {\\n code: `function foo(x, y){\\n return x != null ? x : y;\\n }`,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `const foo = bar !== null && bar !== undefined ? bar : baz;`,\\n output: `const foo = bar ?? baz;`,\\n errors: [{ messageId: \\\"useNullishCoalescing\\\" }],\\n },\\n {\\n code: `const value = user !== null && user !== undefined ? user : getDefault();`,\\n output: `const value = user ?? getDefault();`,\\n errors: [{ messageId: \\\"useNullishCoalescing\\\" }],\\n },\\n {\\n code: `const a = abc !== null && abc !== undefined ? abc : def;`,\\n output: `const a = abc ?? def;`,\\n errors: [{ messageId: \\\"useNullishCoalescing\\\" }],\\n },\\n {\\n code: `const item = val !== undefined && val !== null ? val : fallback;`,\\n output: `const item = val ?? fallback;`,\\n errors: [{ messageId: \\\"useNullishCoalescing\\\" }],\\n },\\n {\\n code: `const result = myVar !== null && myVar !== undefined ? myVar : otherVar;`,\\n output: `const result = myVar ?? otherVar;`,\\n errors: [{ messageId: \\\"useNullishCoalescing\\\" }],\\n },\\n {\\n code: `const config = config !== null && config !== undefined ? config : {};`,\\n output: `const config = config ?? {};`,\\n errors: [{ messageId: \\\"useNullishCoalescing\\\" }],\\n },\\n {\\n code: `const foo = foo !== null && foo !== undefined ? foo : \\\"default\\\";`,\\n output: `const foo = foo ?? \\\"default\\\";`,\\n errors: [{ messageId: \\\"useNullishCoalescing\\\" }],\\n },\\n {\\n code: `const foo = bar !== undefined && bar !== null ? bar : baz;`,\\n output: `const foo = bar ?? baz;`,\\n errors: [{ messageId: \\\"useNullishCoalescing\\\" }],\\n },\\n {\\n code: `const a = (x !== null && x !== undefined) ? x : y;`,\\n output: `const a = x ?? y;`,\\n errors: [{ messageId: \\\"useNullishCoalescing\\\" }],\\n },\\n {\\n code: `const message = msg !== null && msg !== undefined ? msg : \\\"no message\\\";`,\\n output: `const message = msg ?? \\\"no message\\\";`,\\n errors: [{ messageId: \\\"useNullishCoalescing\\\" }],\\n },\\n {\\n code: `foo(x !== null && x !== undefined ? x : y);`,\\n output: `foo(x ?? y);`,\\n errors: [{ messageId: \\\"useNullishCoalescing\\\" }],\\n },\\n {\\n code: `function foo(x, y){\\n return x !== null && x !== undefined ? x : y;\\n }`,\\n output: `function foo(x, y){\\n return x ?? y;\\n }`,\\n errors: [{ messageId: \\\"useNullishCoalescing\\\" }],\\n },\\n {\\n code: `const arr = arrOther.map(x => x !== null && x !== undefined ? x : y);`,\\n output: `const arr = arrOther.map(x => x ?? y);`,\\n errors: [{ messageId: \\\"useNullishCoalescing\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"use-nullish-coalescing-for-default\\\", rule, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'use-on-prefix.ts' and a test for it.\",\"rule_code\":\"import { TSESTree, ESLintUtils } from \\\"@typescript-eslint/utils\\\";\\nimport { RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\n\\nconst url = \\\"https://example.com/rules/\\\";\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${url}${ruleName}`);\\n\\nfunction collectPropNamesFromParams(params: TSESTree.Parameter[], propNames: Set) {\\n const firstParam = params[0];\\n if (firstParam && firstParam.type === \\\"ObjectPattern\\\") {\\n for (const prop of firstParam.properties) {\\n if (prop.type === \\\"Property\\\" && prop.key.type === \\\"Identifier\\\") {\\n propNames.add(prop.key.name);\\n }\\n }\\n }\\n}\\n\\nconst UseOnPrefix = createRule({\\n name: \\\"use-on-prefix\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Allows only 'on' prefix for event handlers\\\",\\n },\\n messages: {\\n useOnPrefix: \\\"Use on prefix for event handlers\\\",\\n },\\n schema: [],\\n },\\n create(context: RuleContext<\\\"useOnPrefix\\\", []>) {\\n const propNames: Set = new Set();\\n\\n return {\\n FunctionDeclaration(node) {\\n collectPropNamesFromParams(node.params, propNames);\\n },\\n FunctionExpression(node) {\\n collectPropNamesFromParams(node.params, propNames);\\n },\\n ArrowFunctionExpression(node) {\\n collectPropNamesFromParams(node.params, propNames);\\n },\\n JSXAttribute(node) {\\n if (node.name.type === \\\"JSXIdentifier\\\" && node.value?.type === \\\"JSXExpressionContainer\\\") {\\n const expression = node.value.expression;\\n if (\\n expression.type === \\\"Identifier\\\" &&\\n propNames.has(expression.name) &&\\n !expression.name.startsWith(\\\"on\\\")\\n ) {\\n context.report({\\n node,\\n messageId: \\\"useOnPrefix\\\",\\n data: {\\n name: expression.name,\\n },\\n });\\n }\\n }\\n },\\n };\\n },\\n\\n defaultOptions: [],\\n});\\n\\nexport default UseOnPrefix;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport UseOnPrefix from \\\"@root/rules/use-on-prefix\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n const Button = ({ onClick }) => (\\n \\n );\\n `,\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n function Button({ onClick }) {\\n return ;\\n }\\n `,\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n const Button = function({ onClick }) {\\n return ;\\n };\\n `,\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n export default function Button({ onClick }) {\\n return ;\\n }\\n `,\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n someWrapper(function({ onClick }) {\\n return ;\\n });\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n const Button = ({ handleClick }) => (\\n \\n );\\n `,\\n errors: [{ messageId: \\\"useOnPrefix\\\" }],\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n function Button({ handleClick }) {\\n return ;\\n }\\n `,\\n errors: [{ messageId: \\\"useOnPrefix\\\" }],\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n const Button = function({ handleClick }) {\\n return ;\\n };\\n `,\\n errors: [{ messageId: \\\"useOnPrefix\\\" }],\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n export default function Button({ handleClick }) {\\n return ;\\n }\\n `,\\n errors: [{ messageId: \\\"useOnPrefix\\\" }],\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n someWrapper(function({ handleClick }) {\\n return ;\\n });\\n `,\\n errors: [{ messageId: \\\"useOnPrefix\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"use-on-prefix\\\", UseOnPrefix, testCases);\\n\"}"}