Download data.jsonl from fernir/eslint-rules-instruction-dataset: direct link, hf CLI and curl.
- Browser
- Download file 428 kB
-
https://huggingface.co/datasets/fernir/eslint-rules-instruction-dataset/resolve/main/data.jsonl
- Command line
-
hf download hf://datasets/fernir/eslint-rules-instruction-dataset/data.jsonl
-
curl -L -o data.jsonl https://huggingface.co/datasets/fernir/eslint-rules-instruction-dataset/resolve/main/data.jsonl
428 kB
| {"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 <div>{oneLineFunc()}</div>;\\n };\\n `,\\n },\\n {\\n code: `\\n export const Component2 = () => <div>Hello</div>;\\n `,\\n },\\n {\\n code: `\\n export const Component3 = () => {\\n function oneLineFunc() {\\n return 10;\\n }\\n\\n return <div>{oneLineFunc()}</div>;\\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 <div>{outsideFunc()}</div>;\\n };\\n `,\\n },\\n {\\n code: `\\n const Component5 = () => {\\n const [a, setA] = useState();\\n const [b, setB] = useState();\\n return <div />;\\n };\\n `,\\n },\\n {\\n code: `\\n const Component6 = () => {\\n const handleClick = () => alert('test');\\n return <div onClick={handleClick} />;\\n };\\n `,\\n },\\n {\\n code: `\\n function Component7() {\\n return <div>Valid function component</div>;\\n }\\n `,\\n },\\n {\\n code: `\\n export function Component8() {\\n return <div>Exported valid component</div>;\\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 <div>{multiLineFunc()}</div>;\\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 <div>{complexFunc()}</div>;\\n };\\n `,\\n errors: [{ messageId: \\\"componentFunctionMaxLines\\\" }],\\n },\\n {\\n code: `\\n export const InvalidComponent3 = () => {\\n return (\\n <div>\\n {(() => {\\n const y = 3;\\n return y + 4;\\n })()}\\n </div>\\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 <div onClick={handleSubmit} />;\\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 <div>{complexFunc()}</div>;\\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 <div>{complexFunc()}</div>;\\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<typeof constants.messageIds.missingSpace, []>) {\\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: `/// <reference path=\\\"baz/path\\\" />`,\\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<Options, MessageIds>({\\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<typeof constants.messageIds.mustConsolidateConditionalExpressions, []>) {\\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<typeof constants.messageIds.tooManyLines, [{ maxLines: number }]>) {\\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<number>();\\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<TSESLint.SourceCode>) => {\\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<string, Options>,\\n sourceCode: Readonly<TSESLint.SourceCode>,\\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<string, Options>,\\n sourceCode: Readonly<TSESLint.SourceCode>,\\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<string, Options>,\\n sourceCode: Readonly<TSESLint.SourceCode>,\\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<string, Options>,\\n sourceCode: Readonly<TSESLint.SourceCode>,\\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<Options, typeof constants.messages.ids.emptyLineRequired>({\\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<typeof constants.messageIds.invalidEmailDomain, []>) {\\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<TSESTree.Node>,\\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<string, ChildGetter> = {\\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<TSESTree.Node>,\\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<TSESTree.Node>();\\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 <div>Bar</div>;\\n};\\n `,\\n },\\n {\\n code: `\\nconst Foo = function AnotherComponent() {\\n return <div>Bar</div>;\\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 <div>Inner</div>;\\n }\\n return <Inner />;\\n }\\n `,\\n },\\n {\\n code: `\\n export function Foo() {\\n return <div>Bar</div>;\\n }\\n `,\\n },\\n {\\n code: `\\n function Foo() {\\n return <div>Foo</div>;\\n }\\n const MemoFoo = React.memo(Foo);\\n `,\\n },\\n {\\n code: `\\n function Foo<T>({ value }: { value: T }) {\\n return <div>{String(value)}</div>;\\n }\\n `,\\n },\\n {\\n code: `\\n export default function Foo() {\\n return <div>Bar</div>;\\n }\\n `,\\n },\\n {\\n code: `\\n function Foo() {\\n if (true) {\\n return <div>If JSX</div>;\\n }\\n return null;\\n }\\n `,\\n },\\n {\\n code: `\\n function Foo() {\\n <div>Expression JSX</div>;\\n return null;\\n }\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\nconst Foo = () => {\\n return <div>Bar</div>;\\n};\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\nconst Foo: React.FC = () => {\\n return <div>Bar</div>;\\n};\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\nexport const Foo = () => {\\n return <div>Bar</div>;\\n};\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\nfunction Foo() {\\n const InnerComponent = () => <div>Bar</div>;\\n return null;\\n}\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\nconst Foo = React.memo(() => <div>Bar</div>);\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\nconst Foo = React.forwardRef((props, ref) => <div ref={ref} />);\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\n function Foo() {\\n const Inner = () => <div>Inner</div>;\\n return <Inner />;\\n }\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\n export const Foo = () => {\\n return <div>Bar</div>;\\n };\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\n const Foo = React.memo(() => <div>Bar</div>);\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\n const Foo = <T,>({ value }: { value: T }) => {\\n return <div>{String(value)}</div>;\\n };\\n `,\\n errors: [{ messageId: \\\"mustUseFunctionForComponent\\\" }],\\n },\\n {\\n code: `\\n const Foo = React.forwardRef<HTMLDivElement>((props, ref) => {\\n return <div ref={ref}>Ref</div>;\\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<Options, MessageIds>({\\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<MyComponentPropsInterface> = ({ title, description }) => {\\n return (\\n <div>\\n <h1>{title}</h1>\\n <p>{description}</p>\\n </div>\\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<T> {\\n data: T;\\n onUpdate: (data: T) => void;\\n}\\n\\nconst GenericComponent: React.FC<GenericProps<string>> = ({ data, onUpdate }) => {\\n return <div>{data}</div>;\\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<ButtonProps> = ({ onClick, className }) => {\\n return <button className={className} onClick={onClick}>Click me</button>;\\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<MyComponentPropsType> = ({ title, description }) => {\\n return (\\n <div>\\n <h1>{title}</h1>\\n <p>{description}</p>\\n </div>\\n );\\n};\\n`,\\n errors: [{ messageId: \\\"useInterface\\\" }, { messageId: \\\"useInterface\\\" }],\\n },\\n {\\n code: `type GenericPropsType<T> = {\\n data: T;\\n onUpdate: (data: T) => void;\\n};\\n\\nconst GenericComponent: React.FC<GenericPropsType<string>> = ({ data, onUpdate }) => {\\n return <div>{data}</div>;\\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<ButtonProps> = (props) => {\\n return <button {...props}>Click me</button>;\\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<typeof constants.messageIds.mustUseNameOf, []>,\\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<typeof constants.messageIds.mustUseNativePrivate, []>) {\\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<MessageIds, []>,\\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<MessageIds, []>,\\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<RuleOptions, MessageIds>({\\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<string, unknown>;\\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<typeof constants.messageIds.singleReturn, []>,\\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<typeof constants.messageIds.singleReturn, []>,\\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<typeof constants.messageIds.singleReturn, []>) {\\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<string>(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<MessageIds, []>,\\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<MessageIds, []>) {\\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<Options, MessageIds>({\\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<TSESLint.RuleContext<MessageIds, Options>>,\\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<Button onClick={() => handleClick(\\\"click-123\\\")} />\\n`,\\n },\\n {\\n code: `\\nuseCallback((a, b) => foo(b, a), [foo]);\\nuseCallback((a) => foo(a + 1), [foo]);\\nuseCallback((a, b) => foo(a), [foo]);\\n`,\\n },\\n {\\n code: `useCallback((value) => foo(value), [foo, bar]);`,\\n },\\n ],\\n};\\n\\nconst errorCases = {\\n invalid: [\\n {\\n code: `\\nconst fooo = useCallback((bar: string) => foo(bar), [foo]);\\nuseCallback((id: string) => bar(id), [bar]);\\n`,\\n errors: [{ messageId: \\\"useCallbackInUseCallback\\\" }, { messageId: \\\"useCallbackInUseCallback\\\" }],\\n },\\n {\\n code: `\\nconst handleClick = useCallback((id: string) => {\\n sendAnalyticsEvent(id);\\n}, [sendAnalyticsEvent]);\\n\\n<Button onClick={() => handleClick(\\\"click-123\\\")} />\\n`,\\n errors: [{ messageId: \\\"useCallbackInUseCallback\\\" }],\\n },\\n {\\n code: `\\nfunction foo(a: number, b: number){\\n return a * b;\\n}\\n \\nconst memoFunc = useCallback((a: number, b: number) => foo(a, b), [foo]);\\n`,\\n errors: [{ messageId: \\\"useCallbackInUseCallback\\\" }],\\n },\\n ],\\n};\\n\\nconst cases = [validCases, errorCases];\\n\\nrunTests(\\\"must-use-usecallback-entry-shortcut\\\", rule, cases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-array-return-many-values.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 maxArrayLength = 3;\\n\\nconst noArrayReturnManyValues = createRule({\\n name: \\\"no-array-return-many-values\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: `Prevent functions from returning arrays with more than ${maxArrayLength} values`,\\n },\\n messages: {\\n noArrayReturnManyValues: `Functions should not return arrays with more than ${maxArrayLength} values`,\\n },\\n schema: [],\\n },\\n create(context: RuleContext<\\\"noArrayReturnManyValues\\\", []>) {\\n function checkReturnedArray(arrayExpr: TSESTree.ArrayExpression) {\\n if (arrayExpr.elements.length > maxArrayLength) {\\n context.report({\\n node: arrayExpr,\\n messageId: \\\"noArrayReturnManyValues\\\",\\n });\\n }\\n }\\n\\n return {\\n ReturnStatement(node) {\\n if (node.argument && node.argument.type === \\\"ArrayExpression\\\") {\\n checkReturnedArray(node.argument);\\n }\\n },\\n ArrowFunctionExpression(node: TSESTree.ArrowFunctionExpression) {\\n if (node.expression && node.body.type === \\\"ArrayExpression\\\") {\\n checkReturnedArray(node.body);\\n }\\n },\\n };\\n },\\n defaultOptions: [],\\n});\\n\\nexport default noArrayReturnManyValues;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noArrayReturnManyValues from \\\"@root/rules/no-array-return-many-values\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n function Foo() {\\n return [];\\n }\\n `,\\n },\\n {\\n code: `\\n function Bar() {\\n const a = 1;\\n return [a];\\n }\\n `,\\n },\\n {\\n code: `\\n function Baz() {\\n const a = 1, b = 2;\\n return [a, b];\\n }\\n `,\\n },\\n {\\n code: `\\n function FooBar() {\\n const a = 1, b = 2, c = 3;\\n return [a, b, c];\\n }\\n `,\\n },\\n {\\n code: `\\n function FooBaz() {\\n const bar = 1, baz = 2;\\n return { bar, baz };\\n }\\n `,\\n },\\n {\\n code: `const foo = () => [1,2,3];`,\\n },\\n {\\n code: `const foo = () => {\\n return [1,2,3];\\n };`,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n function Foo() {\\n const a = 1, b = 2, c = 3, d = 4;\\n return [a, b, c, d];\\n }\\n `,\\n errors: [{ messageId: \\\"noArrayReturnManyValues\\\" }],\\n },\\n {\\n code: `\\n function Bar() {\\n return [1, 2, 3, 4];\\n }\\n `,\\n errors: [{ messageId: \\\"noArrayReturnManyValues\\\" }],\\n },\\n {\\n code: `\\n function Baz() {\\n const a = 1;\\n return [a, a, a, a, a];\\n }\\n `,\\n errors: [{ messageId: \\\"noArrayReturnManyValues\\\" }],\\n },\\n {\\n code: `export const getArr = () => [1, 2, 3, 4];`,\\n errors: [{ messageId: \\\"noArrayReturnManyValues\\\" }],\\n },\\n {\\n code: `const getArrWithBlock = () => {\\n return [1, 2, 3, 4];\\n };`,\\n errors: [{ messageId: \\\"noArrayReturnManyValues\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"no-array-return-many-values\\\", noArrayReturnManyValues, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-conditional-expressions.ts' and a test for it.\",\"rule_code\":\"import type { TSESTree, TSESLint } from \\\"@typescript-eslint/utils\\\";\\n\\nconst noConditionalExpressions = {\\n meta: {\\n type: \\\"suggestion\\\",\\n docs: {\\n description: \\\"Avoid nested conditions, combine them with logical operators when possible\\\",\\n },\\n fixable: \\\"code\\\",\\n schema: [],\\n messages: {\\n nestedConditions:\\n \\\"Combine nested conditions using logical operators. \\\" +\\n \\\"Consider: 'if ({{outerCondition}} && {{innerCondition}})'\\\",\\n },\\n } as const,\\n defaultOptions: [],\\n create(context: Readonly<TSESLint.RuleContext<\\\"nestedConditions\\\", []>>) {\\n return {\\n IfStatement(node: TSESTree.IfStatement) {\\n if (\\n node.consequent &&\\n node.consequent.type === \\\"BlockStatement\\\" &&\\n node.consequent.body.length === 1\\n ) {\\n const nestedIfNode = node.consequent.body[0];\\n\\n if (!nestedIfNode || nestedIfNode.type !== \\\"IfStatement\\\") {\\n return;\\n }\\n\\n const nestedIf = nestedIfNode;\\n\\n if (nestedIf.alternate) {\\n return;\\n }\\n\\n if (\\n node.test.type === \\\"LogicalExpression\\\" ||\\n nestedIf.test.type === \\\"LogicalExpression\\\"\\n ) {\\n return;\\n }\\n\\n const sourceCode = context.sourceCode;\\n const outerCondition = sourceCode.getText(node.test);\\n const innerCondition = sourceCode.getText(nestedIf.test);\\n\\n context.report({\\n node,\\n messageId: \\\"nestedConditions\\\",\\n data: {\\n outerCondition,\\n innerCondition,\\n },\\n fix(fixer) {\\n const combinedCondition = `${outerCondition} && ${innerCondition}`;\\n\\n if (nestedIf.consequent.type === \\\"BlockStatement\\\") {\\n const bodyText = nestedIf.consequent.body\\n .map((stmt) => sourceCode.getText(stmt))\\n .join(\\\"\\\\n\\\");\\n const newCode = `if (${combinedCondition}) {\\\\n${bodyText}\\\\n}`;\\n return fixer.replaceText(node, newCode);\\n } else {\\n const bodyText = sourceCode.getText(nestedIf.consequent);\\n const newCode = `if (${combinedCondition}) ${bodyText}`;\\n return fixer.replaceText(node, newCode);\\n }\\n },\\n });\\n }\\n },\\n };\\n },\\n};\\n\\nexport default noConditionalExpressions;\\n\",\"test_code\":\"import noConditionalExpressions from \\\"@root/rules/no-conditional-expressions\\\";\\nimport { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n if (a) {\\n someFunction();\\n };\\n `,\\n },\\n {\\n code: `\\n if (a && b) {\\n someFunction();\\n };\\n `,\\n },\\n {\\n code: `\\n if (a) {\\n someFunction();\\n } else {\\n doAnother() \\n };\\n `,\\n },\\n {\\n code: `\\n if (a) {\\n if (b) {\\n doSomething();\\n } else {\\n doSomethingElse();\\n }\\n }\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n if (a) {\\n if (b) {\\n someFunction();\\n }\\n }\\n `,\\n errors: [{ messageId: \\\"nestedConditions\\\" }],\\n output: `\\n if (a && b) {\\nsomeFunction();\\n}\\n `,\\n },\\n {\\n code: `\\n if (a) {\\n if (b) logWelcome();\\n }\\n `,\\n errors: [{ messageId: \\\"nestedConditions\\\" }],\\n output: `\\n if (a && b) logWelcome();\\n `,\\n },\\n {\\n code: `\\n if (user.isActive) {\\n if (user.hasPermission) {\\n processUser(user);\\n }\\n }\\n `,\\n errors: [{ messageId: \\\"nestedConditions\\\" }],\\n output: `\\n if (user.isActive && user.hasPermission) {\\nprocessUser(user);\\n}\\n `,\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"no-conditional-expressions\\\", noConditionalExpressions, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-conflicting-props.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree } from \\\"@typescript-eslint/utils\\\";\\n\\nconst url = \\\"https://example.com/rules/\\\";\\nconst createRule = ESLintUtils.RuleCreator((ruleName) => `${url}${ruleName}`);\\nconst suffix = \\\"Prop\\\";\\n\\nconst noConflictingProps = createRule({\\n name: \\\"no-conflicting-props\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: `Must use suffix ${suffix} for the name props in conflict.`,\\n },\\n schema: [],\\n messages: {\\n conflictingProp: `Property '{{name}}' conflicts with another property. Use '{{name}}${suffix}' instead.`,\\n },\\n fixable: \\\"code\\\",\\n },\\n defaultOptions: [],\\n create(context) {\\n function checkForConflicts(propNames: Set<string>, propName: string, node: TSESTree.Node) {\\n if (propNames.has(propName) && !propName.endsWith(suffix)) {\\n context.report({\\n node,\\n messageId: \\\"conflictingProp\\\",\\n data: {\\n name: propName,\\n },\\n fix(fixer) {\\n const newKeyName = `${propName}${suffix}`;\\n return fixer.replaceText(node, newKeyName);\\n },\\n });\\n } else {\\n propNames.add(propName);\\n }\\n }\\n\\n return {\\n JSXOpeningElement(node: TSESTree.JSXOpeningElement) {\\n const propNames = new Set<string>();\\n\\n node.attributes.forEach((attribute) => {\\n if (attribute.type === \\\"JSXAttribute\\\" && attribute.name.type === \\\"JSXIdentifier\\\") {\\n checkForConflicts(propNames, attribute.name.name, attribute.name);\\n }\\n });\\n },\\n ObjectExpression(node: TSESTree.ObjectExpression) {\\n const propNames = new Set<string>();\\n\\n node.properties.forEach((property) => {\\n if (property.type === \\\"Property\\\" && property.key.type === \\\"Identifier\\\") {\\n checkForConflicts(propNames, property.key.name, property.key);\\n }\\n });\\n },\\n };\\n },\\n});\\n\\nexport default noConflictingProps;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport rule from \\\"@root/rules/no-conflicting-props\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n const element = <Component title=\\\"first\\\" titleProp=\\\"second\\\" />;\\n `,\\n },\\n {\\n code: `\\n const props = { name: \\\"value\\\", nameProp: \\\"value2\\\" };\\n `,\\n },\\n {\\n code: `\\n interface MyComponentProps {\\n name?: string;\\n nameProp?: string;\\n }\\n\\n const MyComponent: React.FC<MyComponentProps> = ({ name, nameProp }) => {\\n return (\\n <div>\\n <div>Name: {name}</div>\\n <div>NameProp: {nameProp}</div>\\n </div>\\n );\\n };\\n\\n const App = () => {\\n const props = { name: \\\"John\\\", nameProp: \\\"Doe\\\" };\\n\\n return (\\n <div>\\n <MyComponent name=\\\"John\\\" nameProp=\\\"Doe\\\" />\\n <MyComponent {...props} />\\n </div>\\n );\\n };\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n const props = { name: \\\"first\\\", name: \\\"second\\\" };\\n `,\\n errors: [{ messageId: \\\"conflictingProp\\\" }],\\n output: `\\n const props = { name: \\\"first\\\", nameProp: \\\"second\\\" };\\n `,\\n },\\n {\\n code: `\\n const element = <Component title=\\\"first\\\" title=\\\"second\\\" />;\\n `,\\n errors: [{ messageId: \\\"conflictingProp\\\" }],\\n output: `\\n const element = <Component title=\\\"first\\\" titleProp=\\\"second\\\" />;\\n `,\\n },\\n {\\n code: `\\n interface MyComponentProps {\\n name?: string;\\n nameProp?: string;\\n }\\n\\n const MyComponent: React.FC<MyComponentProps> = ({ name, nameProp }) => {\\n return (\\n <div>\\n <div>Name: {name}</div>\\n <div>NameProp: {nameProp}</div>\\n </div>\\n );\\n };\\n\\n const App: React.FC = () => {\\n const props = { name: \\\"John\\\", name: \\\"Doe\\\" };\\n\\n return (\\n <div>\\n <MyComponent name=\\\"John\\\" name=\\\"Doe\\\" />\\n <MyComponent {...props} />\\n </div>\\n );\\n };\\n `,\\n errors: [{ messageId: \\\"conflictingProp\\\" }, { messageId: \\\"conflictingProp\\\" }],\\n output: `\\n interface MyComponentProps {\\n name?: string;\\n nameProp?: string;\\n }\\n\\n const MyComponent: React.FC<MyComponentProps> = ({ name, nameProp }) => {\\n return (\\n <div>\\n <div>Name: {name}</div>\\n <div>NameProp: {nameProp}</div>\\n </div>\\n );\\n };\\n\\n const App: React.FC = () => {\\n const props = { name: \\\"John\\\", nameProp: \\\"Doe\\\" };\\n\\n return (\\n <div>\\n <MyComponent name=\\\"John\\\" nameProp=\\\"Doe\\\" />\\n <MyComponent {...props} />\\n </div>\\n );\\n };\\n `,\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"no-conflicting-props\\\", rule, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-constructor-name-for-resource.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree } from \\\"@typescript-eslint/utils\\\";\\n\\nconst ruleConstants = {\\n ruleName: \\\"no-constructor-name-for-resource\\\",\\n urlBase: \\\"https://example.com/rules/\\\",\\n description: \\\"Disallow usage of .constructor.name in favor of constant resource names.\\\",\\n errorMessage: \\\"Do not use '.constructor.name'. Use a constant from 'resourceNames' instead.\\\",\\n messageId: \\\"noUseConstructorName\\\",\\n nodeTypes: {\\n memberExpression: \\\"MemberExpression\\\",\\n identifier: \\\"Identifier\\\",\\n },\\n} as const;\\n\\ntype MessageIds = typeof ruleConstants.messageId;\\ntype Options = [];\\n\\nconst excludedDecoratorPath = \\\"meta/decorators\\\";\\n\\nconst createRule = ESLintUtils.RuleCreator((name: string) => `${ruleConstants.urlBase}${name}`);\\n\\nconst noUseConstructorName = createRule<Options, MessageIds>({\\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 const filename = context.filename ?? \\\"\\\";\\n\\n if (filename.includes(excludedDecoratorPath)) {\\n return {};\\n }\\n\\n return {\\n MemberExpression(node: TSESTree.MemberExpression) {\\n if (node.object.type === ruleConstants.nodeTypes.memberExpression) {\\n const memberObject = node.object;\\n\\n if (\\n (memberObject.object.type === ruleConstants.nodeTypes.identifier ||\\n memberObject.object.type === ruleConstants.nodeTypes.memberExpression) &&\\n memberObject.property.type === ruleConstants.nodeTypes.identifier &&\\n memberObject.property.name === \\\"constructor\\\" &&\\n node.property.type === ruleConstants.nodeTypes.identifier &&\\n node.property.name === \\\"name\\\"\\n ) {\\n context.report({\\n node,\\n messageId: ruleConstants.messageId,\\n });\\n }\\n }\\n },\\n };\\n },\\n});\\n\\nexport default noUseConstructorName;\\n\",\"test_code\":\"import { runTests } from \\\"../test-utils/eslint-rule-tester\\\";\\nimport rule from \\\"../rules/no-constructor-name-for-resource\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `const resourceName = resourceNames.foo;`,\\n },\\n {\\n code: `const name = \\\"Order\\\";`,\\n },\\n {\\n code: `const name = foo.constructor.name;`,\\n filename: \\\"src/meta/decorators/custom.ts\\\",\\n },\\n {\\n code: `console.log(bar.constructor.name);`,\\n filename: \\\"/absolute/path/meta/decorators/another-decorator.ts\\\",\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `const name = foo.constructor.name;`,\\n errors: [{ messageId: \\\"noUseConstructorName\\\" }],\\n },\\n {\\n code: `const name = some.obj.constructor.name;`,\\n errors: [{ messageId: \\\"noUseConstructorName\\\" }],\\n },\\n {\\n code: `console.log(bar.constructor.name);`,\\n errors: [{ messageId: \\\"noUseConstructorName\\\" }],\\n },\\n {\\n code: `return x.constructor.name;`,\\n errors: [{ messageId: \\\"noUseConstructorName\\\" }],\\n },\\n ],\\n};\\n\\nconst cases = [validCases, invalidCases];\\n\\nrunTests(\\\"no-constructor-name-for-resource\\\", rule, cases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-default-props.ts' and a test for it.\",\"rule_code\":\"import { 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 noDefaultProps = createRule({\\n name: \\\"no-default-props\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Disallow default values in props destructuring; use optional props instead.\\\",\\n },\\n messages: {\\n noDefaultProps: \\\"Use operator '?' for props instead of default values\\\",\\n },\\n schema: [],\\n },\\n create(context: RuleContext<\\\"noDefaultProps\\\", []>) {\\n return {\\n FunctionDeclaration(node) {\\n if (!node.params?.[0]) return;\\n\\n const param = node.params[0];\\n\\n if (\\n param?.type === \\\"ObjectPattern\\\" &&\\n param.properties.some(\\n (prop) => prop.type === \\\"Property\\\" && prop.value.type === \\\"AssignmentPattern\\\",\\n )\\n ) {\\n context.report({\\n node: param,\\n messageId: \\\"noDefaultProps\\\",\\n });\\n }\\n },\\n\\n ArrowFunctionExpression(node) {\\n if (!node.params?.[0]) return;\\n\\n const param = node.params[0];\\n\\n if (\\n param?.type === \\\"ObjectPattern\\\" &&\\n param.properties.some(\\n (prop) => prop.type === \\\"Property\\\" && prop.value.type === \\\"AssignmentPattern\\\",\\n )\\n ) {\\n context.report({\\n node: param,\\n messageId: \\\"noDefaultProps\\\",\\n });\\n }\\n },\\n };\\n },\\n defaultOptions: [],\\n});\\n\\nexport default noDefaultProps;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noDefaultProps from \\\"@root/rules/no-default-props\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n interface FooProps2 {\\n bar?: string;\\n }\\n export function Foo2({ bar }: FooProps2) {}\\n `,\\n },\\n {\\n code: `\\n interface Props2 {\\n foo?: number;\\n bar?: string;\\n }\\n\\n const Component2 = ({ foo: foo, bar: bar }: Props) => {\\n return (\\n <div>\\n {foo} {bar}\\n </div>\\n );\\n };\\n `,\\n },\\n {\\n code: `\\n function HelloWorld(props: { name?: string }) {\\n return <div>{props.name}</div>;\\n }\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n interface FooProps {\\n bar: string;\\n }\\n export function Foo({ bar = \\\"default\\\" }: FooProps) {}\\n `,\\n errors: [{ messageId: \\\"noDefaultProps\\\" }],\\n },\\n {\\n code: `\\n interface Props {\\n foo: number;\\n bar: string;\\n }\\n\\n const Component = ({ foo = 1, bar = \\\"abc\\\" }: Props) => {\\n return (\\n <div>\\n {foo} {bar}\\n </div>\\n );\\n };\\n `,\\n errors: [{ messageId: \\\"noDefaultProps\\\" }],\\n },\\n {\\n code: `\\n function Hello({ name = \\\"world\\\" }: { name: string }) {}\\n `,\\n errors: [{ messageId: \\\"noDefaultProps\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"no-default-props\\\", noDefaultProps, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-delays-in-ui-tests.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: \\\"no-delays-in-ui-tests\\\",\\n messageIds: {\\n noDelaysInTests: \\\"noDelaysInTests\\\",\\n },\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description:\\n \\\"Disallow problematic delays and wait methods in Playwright UI tests. \\\" +\\n \\\"Allows valid wait methods like waitForResponse, waitForLoadState, \\\" +\\n \\\"but disallows waitForTimeout, setTimeout, and waitForSelector.\\\",\\n },\\n messages: {\\n noDelaysInTests:\\n \\\"Avoid using problematic delays (setTimeout, waitForTimeout, waitForSelector) \\\" +\\n \\\"in UI tests. Use more reliable waiting mechanisms like waitForResponse, \\\" +\\n \\\"waitForLoadState, or locator assertions instead.\\\",\\n },\\n schema: [],\\n },\\n functionNames: {\\n setTimeout: \\\"setTimeout\\\",\\n page: \\\"page\\\",\\n browser: \\\"browser\\\",\\n promise: \\\"Promise\\\",\\n },\\n playwrightMethods: [\\\"waitForTimeout\\\", \\\"setDefaultTimeout\\\", \\\"waitForSelector\\\"],\\n testPatterns: {\\n testFileExtensions: [\\\".test.\\\", \\\".spec.\\\"],\\n testDirectories: [\\\"/tests/\\\", \\\"/e2e/\\\", \\\"/__tests__/\\\", \\\"/__test__/\\\", \\\"/test/\\\"],\\n },\\n imports: {\\n playwright: \\\"playwright\\\",\\n playwrightTest: \\\"@playwright/test\\\",\\n },\\n testUsages: {\\n testCall: \\\"test(\\\",\\n testProperty: \\\"test.\\\",\\n pageProperty: \\\"page.\\\",\\n browserProperty: \\\"browser.\\\",\\n },\\n delayFunctionPatterns: [\\\"sleep\\\", \\\"delay\\\", \\\"wait\\\", \\\"pause\\\"],\\n promiseStrings: [\\\"setTimeout\\\", \\\"resolve\\\", \\\",\\\"],\\n} as const;\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${constants.url}${ruleName}`);\\n\\ntype FunctionNode =\\n | TSESTree.FunctionDeclaration\\n | TSESTree.ArrowFunctionExpression\\n | TSESTree.FunctionExpression;\\n\\nfunction isPlaywrightWaitMethod(methodName: string): boolean {\\n return constants.playwrightMethods.includes(methodName as (typeof constants.playwrightMethods)[number]);\\n}\\n\\nfunction isTestFile(filename: string): boolean {\\n return (\\n constants.testPatterns.testFileExtensions.some((ext) => filename.includes(ext)) ||\\n constants.testPatterns.testDirectories.some((dir) => filename.includes(dir))\\n );\\n}\\n\\nfunction isPlaywrightImportOrUsage(sourceCodeText: string): boolean {\\n return (\\n sourceCodeText.includes(constants.imports.playwright) ||\\n sourceCodeText.includes(constants.imports.playwrightTest) ||\\n sourceCodeText.includes(constants.testUsages.testCall) ||\\n sourceCodeText.includes(constants.testUsages.testProperty) ||\\n sourceCodeText.includes(constants.testUsages.pageProperty) ||\\n sourceCodeText.includes(constants.testUsages.browserProperty)\\n );\\n}\\n\\nfunction isDirectSetTimeoutCall(node: TSESTree.CallExpression): boolean {\\n return (\\n node.callee.type === AST_NODE_TYPES.Identifier &&\\n node.callee.name === constants.functionNames.setTimeout\\n );\\n}\\n\\nfunction isPlaywrightWaitCall(node: TSESTree.CallExpression): boolean {\\n return (\\n node.callee.type === AST_NODE_TYPES.MemberExpression &&\\n node.callee.property.type === AST_NODE_TYPES.Identifier &&\\n isPlaywrightWaitMethod(node.callee.property.name)\\n );\\n}\\n\\nfunction isBrowserTimeoutCall(node: TSESTree.CallExpression): boolean {\\n if (node.callee.type !== AST_NODE_TYPES.MemberExpression) return false;\\n\\n if (node.callee.property.type !== AST_NODE_TYPES.Identifier) return false;\\n\\n const isPageOrBrowser =\\n node.callee.object.type === AST_NODE_TYPES.Identifier &&\\n (node.callee.object.name === constants.functionNames.page ||\\n node.callee.object.name === constants.functionNames.browser);\\n\\n return isPageOrBrowser && node.callee.property.name === \\\"setDefaultTimeout\\\";\\n}\\n\\nfunction isWithinReportedParent(node: TSESTree.Node, reportedNodes: Set<TSESTree.Node>) {\\n let current: TSESTree.Node | undefined = node.parent;\\n\\n while (current) {\\n if (reportedNodes.has(current)) {\\n return true;\\n }\\n\\n current = current.parent;\\n }\\n\\n return false;\\n}\\n\\nfunction containsDelayPattern(node: TSESTree.Node, sourceCodeText?: string): boolean {\\n if (!node) return false;\\n\\n if (node.type === AST_NODE_TYPES.CallExpression) {\\n if (\\n node.callee.type === AST_NODE_TYPES.Identifier &&\\n node.callee.name === constants.functionNames.promise\\n ) {\\n const text = sourceCodeText ?? \\\"\\\";\\n return (\\n text.includes(constants.promiseStrings[0]) ||\\n (text.includes(constants.promiseStrings[1]) && text.includes(constants.promiseStrings[2]))\\n );\\n }\\n\\n if (\\n node.callee.type === AST_NODE_TYPES.Identifier &&\\n node.callee.name === constants.functionNames.setTimeout\\n ) {\\n return true;\\n }\\n\\n if (\\n node.callee.type === AST_NODE_TYPES.MemberExpression &&\\n node.callee.property.type === AST_NODE_TYPES.Identifier &&\\n isPlaywrightWaitMethod(node.callee.property.name)\\n ) {\\n return true;\\n }\\n }\\n\\n return false;\\n}\\n\\nfunction getBodyStatements(fnNode: FunctionNode): TSESTree.Node[] {\\n if (!fnNode.body) return [];\\n\\n if (fnNode.body.type === \\\"BlockStatement\\\") {\\n return fnNode.body.body;\\n }\\n\\n return [fnNode.body];\\n}\\n\\nfunction checkStatementForDelays(node: TSESTree.Node): boolean {\\n switch (node.type) {\\n case \\\"BlockStatement\\\":\\n return node.body.some(checkNodeForDelays);\\n case \\\"ExpressionStatement\\\":\\n return checkNodeForDelays(node.expression);\\n case \\\"ReturnStatement\\\":\\n return node.argument ? checkNodeForDelays(node.argument) : false;\\n case \\\"IfStatement\\\": {\\n const consequentHasDelay = checkNodeForDelays(node.consequent);\\n const alternateHasDelay = node.alternate ? checkNodeForDelays(node.alternate) : false;\\n\\n return consequentHasDelay || alternateHasDelay;\\n }\\n default:\\n return false;\\n }\\n}\\n\\nfunction checkExpressionForDelays(node: TSESTree.Node): boolean {\\n switch (node.type) {\\n case \\\"CallExpression\\\":\\n return containsDelayPattern(node) || node.arguments.some(checkNodeForDelays);\\n case \\\"NewExpression\\\":\\n return containsDelayPattern(node) || (node.arguments?.some(checkNodeForDelays) ?? false);\\n case \\\"ArrowFunctionExpression\\\":\\n case \\\"FunctionExpression\\\":\\n return containsDelayInFunction(node);\\n default:\\n return false;\\n }\\n}\\n\\nfunction checkNodeForDelays(node: TSESTree.Node): boolean {\\n if (containsDelayPattern(node)) {\\n return true;\\n }\\n\\n const statementHasDelay = checkStatementForDelays(node);\\n const expressionHasDelay = checkExpressionForDelays(node);\\n\\n return statementHasDelay || expressionHasDelay;\\n}\\n\\nfunction containsDelayInFunction(fnNode: FunctionNode) {\\n const bodyStatements = getBodyStatements(fnNode);\\n\\n return bodyStatements.some(checkNodeForDelays);\\n}\\n\\nfunction reportOnce(\\n context: RuleContext<typeof constants.messageIds.noDelaysInTests, []>,\\n node: TSESTree.Node,\\n reportedNodes: Set<TSESTree.Node>,\\n) {\\n if (reportedNodes.has(node)) return;\\n\\n reportedNodes.add(node);\\n context.report({\\n node,\\n messageId: constants.messageIds.noDelaysInTests,\\n });\\n}\\n\\nfunction handleCallExpression(\\n node: TSESTree.CallExpression,\\n context: RuleContext<typeof constants.messageIds.noDelaysInTests, []>,\\n isPlaywrightTestFile: boolean,\\n reportedNodes: Set<TSESTree.Node>,\\n) {\\n if (!isPlaywrightTestFile || isWithinReportedParent(node, reportedNodes)) return;\\n\\n if (isDirectSetTimeoutCall(node)) {\\n reportOnce(context, node, reportedNodes);\\n return;\\n }\\n\\n if (isPlaywrightWaitCall(node)) {\\n reportOnce(context, node, reportedNodes);\\n return;\\n }\\n\\n if (isBrowserTimeoutCall(node)) {\\n reportOnce(context, node, reportedNodes);\\n return;\\n }\\n\\n if (\\n node.callee.type === AST_NODE_TYPES.Identifier &&\\n constants.delayFunctionPatterns.some(\\n (name) =>\\n node.callee.type === AST_NODE_TYPES.Identifier &&\\n node.callee.name.toLowerCase().includes(name),\\n )\\n ) {\\n reportOnce(context, node, reportedNodes);\\n }\\n}\\n\\nfunction handleNewExpression(\\n node: TSESTree.NewExpression,\\n context: RuleContext<typeof constants.messageIds.noDelaysInTests, []>,\\n isPlaywrightTestFile: boolean,\\n reportedNodes: Set<TSESTree.Node>,\\n) {\\n if (!isPlaywrightTestFile || isWithinReportedParent(node, reportedNodes)) return;\\n\\n if (\\n node.callee.type === AST_NODE_TYPES.Identifier &&\\n node.callee.name === constants.functionNames.promise\\n ) {\\n const sourceCode = context.sourceCode.getText(node);\\n\\n if (\\n sourceCode.includes(constants.promiseStrings[0]) ||\\n (sourceCode.includes(constants.promiseStrings[1]) &&\\n sourceCode.includes(constants.promiseStrings[2]))\\n ) {\\n reportOnce(context, node, reportedNodes);\\n }\\n }\\n}\\n\\nfunction checkIsPlaywrightFile(context: RuleContext<typeof constants.messageIds.noDelaysInTests, []>) {\\n const filename = context.filename;\\n\\n if (!isTestFile(filename)) {\\n return false;\\n }\\n\\n const sourceCode = context.sourceCode.getText();\\n\\n return isPlaywrightImportOrUsage(sourceCode);\\n}\\n\\nfunction handleFunction(\\n node: FunctionNode,\\n context: RuleContext<typeof constants.messageIds.noDelaysInTests, []>,\\n isPlaywrightTestFile: boolean,\\n reportedNodes: Set<TSESTree.Node>,\\n) {\\n if (!isPlaywrightTestFile || isWithinReportedParent(node, reportedNodes)) {\\n return;\\n }\\n\\n if (containsDelayInFunction(node)) {\\n reportOnce(context, node, reportedNodes);\\n }\\n}\\n\\nfunction handleVariableDeclarator(\\n node: TSESTree.VariableDeclarator,\\n context: RuleContext<typeof constants.messageIds.noDelaysInTests, []>,\\n isPlaywrightTestFile: boolean,\\n reportedNodes: Set<TSESTree.Node>,\\n) {\\n if (\\n !isPlaywrightTestFile ||\\n !node.id ||\\n node.id.type !== AST_NODE_TYPES.Identifier ||\\n isWithinReportedParent(node, reportedNodes)\\n ) {\\n return;\\n }\\n\\n if (\\n constants.delayFunctionPatterns.some(\\n (name) => node.id.type === AST_NODE_TYPES.Identifier && node.id.name.toLowerCase().includes(name),\\n )\\n ) {\\n reportOnce(context, node, reportedNodes);\\n return;\\n }\\n\\n if (\\n node.init &&\\n (node.init.type === \\\"ArrowFunctionExpression\\\" || node.init.type === \\\"FunctionExpression\\\")\\n ) {\\n if (containsDelayInFunction(node.init)) {\\n reportOnce(context, node, reportedNodes);\\n }\\n }\\n}\\n\\nconst noDelaysInUiTests = createRule<[], typeof constants.messageIds.noDelaysInTests>({\\n name: constants.ruleName,\\n meta: constants.meta,\\n defaultOptions: [],\\n\\n create(context: RuleContext<typeof constants.messageIds.noDelaysInTests, []>) {\\n let isPlaywrightTestFile = false;\\n const reportedNodes = new Set<TSESTree.Node>();\\n\\n return {\\n Program() {\\n isPlaywrightTestFile = checkIsPlaywrightFile(context);\\n },\\n\\n CallExpression(node: TSESTree.CallExpression) {\\n handleCallExpression(node, context, isPlaywrightTestFile, reportedNodes);\\n },\\n\\n NewExpression(node) {\\n handleNewExpression(node, context, isPlaywrightTestFile, reportedNodes);\\n },\\n\\n FunctionDeclaration(node: TSESTree.FunctionDeclaration) {\\n handleFunction(node, context, isPlaywrightTestFile, reportedNodes);\\n },\\n\\n ArrowFunctionExpression(node: TSESTree.ArrowFunctionExpression) {\\n handleFunction(node, context, isPlaywrightTestFile, reportedNodes);\\n },\\n\\n FunctionExpression(node: TSESTree.FunctionExpression) {\\n handleFunction(node, context, isPlaywrightTestFile, reportedNodes);\\n },\\n\\n VariableDeclarator(node: TSESTree.VariableDeclarator) {\\n handleVariableDeclarator(node, context, isPlaywrightTestFile, reportedNodes);\\n },\\n };\\n },\\n});\\n\\nexport default noDelaysInUiTests;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noDelaysInUiTests from \\\"@root/rules/no-delays-in-ui-tests\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n import { test, expect } from '@playwright/test';\\n \\n test('should navigate to the page', async ({ page }) => {\\n await page.goto('/');\\n await expect(page.locator('h1')).toBeVisible();\\n });\\n `,\\n filename: \\\"foo.spec.ts\\\",\\n },\\n {\\n code: `\\n import { test } from '@playwright/test';\\n \\n test('should fill the form', async ({ page }) => {\\n await page.fill('input[name=\\\"username\\\"]', 'testuser');\\n await page.click('button[type=\\\"submit\\\"]');\\n await expect(page.locator('.success-message')).toBeVisible();\\n });\\n `,\\n filename: \\\"bar.test.ts\\\",\\n },\\n {\\n code: `\\n function foo() {\\n setTimeout(() => {\\n console.log('Operation delayed');\\n }, 1000);\\n }\\n `,\\n filename: \\\"utils.ts\\\",\\n },\\n {\\n code: `\\n import { test } from '@playwright/test';\\n \\n test('should wait for API response', async ({ page }) => {\\n await page.goto('/');\\n await page.waitForResponse('**/api/data');\\n await page.click('.button');\\n });\\n `,\\n filename: \\\"wait-response.test.ts\\\",\\n },\\n {\\n code: `\\n import { test } from '@playwright/test';\\n \\n test('should wait for load state', async ({ page }) => {\\n await page.goto('/');\\n await page.waitForLoadState('networkidle');\\n await page.click('.button');\\n });\\n `,\\n filename: \\\"wait-load-state.test.ts\\\",\\n },\\n {\\n code: `\\n import { test } from '@playwright/test';\\n \\n test('should wait for navigation', async ({ page }) => {\\n await page.goto('/');\\n await Promise.all([\\n page.waitForNavigation(),\\n page.click('a.link')\\n ]);\\n });\\n `,\\n filename: \\\"wait-navigation.test.ts\\\",\\n },\\n {\\n code: `\\n import { test } from '@playwright/test';\\n \\n test('should wait for URL change', async ({ page }) => {\\n await page.goto('/');\\n await page.click('a.link');\\n await page.waitForURL('**/new-page');\\n });\\n `,\\n filename: \\\"wait-url.test.ts\\\",\\n },\\n {\\n code: `\\n import { test, expect } from '@playwright/test';\\n \\n test('should use locator with auto-wait instead of waitForSelector', async ({ page }) => {\\n await page.goto('/');\\n \\n // ✅ Modern approach - locator with automatic waiting\\n await expect(page.locator('.button')).toBeVisible();\\n await page.locator('.button').click();\\n \\n // ✅ Direct action with auto-wait\\n await page.locator('input[name=\\\"username\\\"]').fill('testuser');\\n });\\n `,\\n filename: \\\"modern-selectors.test.ts\\\",\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n import { test } from '@playwright/test';\\n \\n test('should not use setTimeout', async ({ page }) => {\\n await page.goto('/');\\n setTimeout(() => {\\n console.log('This is wrong');\\n }, 1000);\\n });\\n `,\\n errors: [{ messageId: \\\"noDelaysInTests\\\" }],\\n filename: \\\"qux.spec.ts\\\",\\n },\\n {\\n code: `\\n import { test } from '@playwright/test';\\n \\n test('should not use page.waitForTimeout', async ({ page }) => {\\n await page.goto('/');\\n await page.waitForTimeout(500);\\n await page.click('.button');\\n });\\n `,\\n errors: [{ messageId: \\\"noDelaysInTests\\\" }],\\n filename: \\\"quux.test.ts\\\",\\n },\\n {\\n code: `\\n import { test } from '@playwright/test';\\n \\n test('should not use waitForSelector', async ({ page }) => {\\n await page.goto('/');\\n await page.waitForSelector('.button');\\n await page.click('.button');\\n });\\n `,\\n errors: [{ messageId: \\\"noDelaysInTests\\\" }],\\n filename: \\\"wait-selector.test.ts\\\",\\n },\\n {\\n code: `\\n import { test } from '@playwright/test';\\n \\n test('should not use low timeouts', async ({ page }) => {\\n page.setDefaultTimeout(500);\\n await page.goto('/');\\n });\\n `,\\n errors: [{ messageId: \\\"noDelaysInTests\\\" }],\\n filename: \\\"corge.spec.ts\\\",\\n },\\n {\\n code: `\\n import { test } from '@playwright/test';\\n \\n async function sleep(ms) {\\n return new Promise(resolve => setTimeout(resolve, ms));\\n }\\n \\n test('should not use custom sleep functions', async ({ page }) => {\\n await page.goto('/');\\n await sleep(1000);\\n await page.click('.button');\\n });\\n `,\\n errors: [{ messageId: \\\"noDelaysInTests\\\" }, { messageId: \\\"noDelaysInTests\\\" }],\\n filename: \\\"grault.spec.ts\\\",\\n },\\n {\\n code: `\\n import { test } from '@playwright/test';\\n \\n test('should not use inline promise delays', async ({ page }) => {\\n await page.goto('/');\\n await new Promise(resolve => setTimeout(resolve, 2000));\\n await page.click('.button');\\n });\\n `,\\n errors: [{ messageId: \\\"noDelaysInTests\\\" }],\\n filename: \\\"garply.test.ts\\\",\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"no-delays-in-ui-tests\\\", noDelaysInUiTests, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-duplicate-imports.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree } from \\\"@typescript-eslint/utils\\\";\\nimport { RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\n\\ntype MessageIds = \\\"noDuplicateImports\\\";\\ntype Options = [];\\n\\nconst nodeTypes = {\\n importDeclaration: TSESTree.AST_NODE_TYPES.ImportDeclaration,\\n exportAllDeclaration: TSESTree.AST_NODE_TYPES.ExportAllDeclaration,\\n exportNamedDeclaration: TSESTree.AST_NODE_TYPES.ExportNamedDeclaration,\\n literal: TSESTree.AST_NODE_TYPES.Literal,\\n stringType: \\\"string\\\",\\n} as const;\\n\\nconst url = \\\"https://example.com/rules/\\\";\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${url}${ruleName}`);\\n\\nconst noDuplicateImports = createRule<Options, MessageIds>({\\n name: \\\"no-duplicate-imports\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Disallow duplicate imports from the same module\\\",\\n },\\n messages: {\\n noDuplicateImports: \\\"Duplicate import from '{{source}}'\\\",\\n },\\n schema: [],\\n },\\n defaultOptions: [],\\n\\n create(context: RuleContext<MessageIds, Options>) {\\n const sourcesMap = new Map<string, TSESTree.Node>();\\n\\n function checkSource(source: string, node: TSESTree.Node) {\\n if (sourcesMap.has(source)) {\\n context.report({\\n node,\\n messageId: \\\"noDuplicateImports\\\",\\n data: {\\n source,\\n },\\n });\\n } else {\\n sourcesMap.set(source, node);\\n }\\n }\\n\\n return {\\n [nodeTypes.importDeclaration](node: TSESTree.ImportDeclaration) {\\n if (\\n node.source.type !== nodeTypes.literal ||\\n typeof node.source.value !== nodeTypes.stringType\\n ) {\\n return;\\n }\\n\\n const source = node.source.value;\\n checkSource(source, node);\\n },\\n\\n [nodeTypes.exportNamedDeclaration](node: TSESTree.ExportNamedDeclaration) {\\n if (\\n !node.source ||\\n node.source.type !== nodeTypes.literal ||\\n typeof node.source.value !== nodeTypes.stringType\\n ) {\\n return;\\n }\\n\\n const source = node.source.value;\\n checkSource(source, node);\\n },\\n\\n [nodeTypes.exportAllDeclaration](node: TSESTree.ExportAllDeclaration) {\\n if (\\n node.source.type !== nodeTypes.literal ||\\n typeof node.source.value !== nodeTypes.stringType\\n ) {\\n return;\\n }\\n\\n const source = node.source.value;\\n checkSource(source, node);\\n },\\n };\\n },\\n});\\n\\nexport default noDuplicateImports;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noDuplicateImports from \\\"@root/rules/no-duplicate-imports\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n import { foo } from 'module-a';\\n import { bar } from 'module-b';\\n `,\\n },\\n {\\n code: `\\n import { foo, bar } from 'module-a';\\n `,\\n },\\n {\\n code: `\\n import DefaultExport from 'module-a';\\n import { namedExport } from 'module-b';\\n `,\\n },\\n {\\n code: `\\n import * as moduleA from 'module-a';\\n export { foo } from 'module-b';\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n import { foo } from 'module-a';\\n import { bar } from 'module-a';\\n `,\\n errors: [{ messageId: \\\"noDuplicateImports\\\" }],\\n },\\n {\\n code: `\\n import { foo } from 'module-a';\\n export { bar } from 'module-a';\\n `,\\n errors: [{ messageId: \\\"noDuplicateImports\\\" }],\\n },\\n {\\n code: `\\n import DefaultExport from 'module-a';\\n import { namedExport } from 'module-a';\\n `,\\n errors: [{ messageId: \\\"noDuplicateImports\\\" }],\\n },\\n ],\\n};\\n\\nconst edgeCases = {\\n invalid: [\\n {\\n code: `\\n export { foo } from 'module-a';\\n export { bar } from 'module-a';\\n `,\\n errors: [{ messageId: \\\"noDuplicateImports\\\" }],\\n },\\n {\\n code: `\\n import { foo } from 'module-a';\\n import { bar } from 'module-b';\\n import { baz } from 'module-a';\\n `,\\n errors: [{ messageId: \\\"noDuplicateImports\\\" }],\\n },\\n {\\n code: `\\n import * as moduleA from 'module-a';\\n export * from 'module-a';\\n `,\\n errors: [{ messageId: \\\"noDuplicateImports\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases, edgeCases];\\nrunTests(\\\"no-duplicate-imports\\\", noDuplicateImports, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-eslint-disable-without-approved.ts' and a test for it.\",\"rule_code\":\"import { RuleCreator } from \\\"@typescript-eslint/utils/eslint-utils\\\";\\nimport { AST_TOKEN_TYPES } from \\\"@typescript-eslint/types\\\";\\n\\ntype MessageIds = \\\"missingApproved\\\";\\ntype Options = [];\\n\\nconst url = \\\"https://example.com/rules/\\\";\\nconst disablePattern = \\\"eslint-disable\\\";\\nconst approvedText = \\\"Approved\\\";\\n\\nconst createRule = RuleCreator((name) => `${url}${name}`);\\n\\nexport default createRule<Options, MessageIds>({\\n name: \\\"no-eslint-disable-without-approved\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: `Require \\\"// ${approvedText}\\\" comment before any ${disablePattern} comment`,\\n },\\n messages: {\\n missingApproved: `An \\\"// ${approvedText}\\\" comment must precede any \\\"${disablePattern}\\\" comment.`,\\n },\\n schema: [],\\n },\\n defaultOptions: [],\\n\\n create(context) {\\n const sourceCode = context.sourceCode;\\n\\n return {\\n Program() {\\n const comments = sourceCode.getAllComments();\\n\\n for (let i = 0; i < comments.length; i++) {\\n const comment = comments[i];\\n\\n if (comment) {\\n const isDisable =\\n comment.type === AST_TOKEN_TYPES.Line &&\\n comment.value.trim().startsWith(disablePattern);\\n\\n if (isDisable) {\\n const prevComment = comments[i - 1];\\n\\n const isApproved =\\n prevComment &&\\n prevComment.type === AST_TOKEN_TYPES.Line &&\\n prevComment.loc.end.line === comment.loc.start.line - 1 &&\\n prevComment.value.trim() === approvedText;\\n\\n if (!isApproved) {\\n context.report({\\n loc: comment.loc,\\n messageId: \\\"missingApproved\\\",\\n });\\n }\\n }\\n }\\n }\\n },\\n };\\n },\\n});\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport rule from \\\"@root/rules/no-eslint-disable-without-approved\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: ` // Approved\\n // eslint-disable\\n const x = 5;\\n x = 10;`,\\n },\\n\\n {\\n code: ` // just a comment\\n console.log(\\\"no eslint disable here\\\");`,\\n },\\n\\n {\\n code: ` // Approved\\n // eslint-disable\\n const x = 5;\\n\\n // Approved\\n // eslint-disable\\n const y = 10;`,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `// eslint-disable\\n const x = 5;\\n x = 10;`,\\n errors: [{ messageId: \\\"missingApproved\\\" }],\\n },\\n\\n {\\n code: `// Approved\\n\\n // eslint-disable\\n const x = 5;`,\\n errors: [{ messageId: \\\"missingApproved\\\" }],\\n },\\n\\n {\\n code: `// approved\\n // eslint-disable\\n const x = 5;`,\\n errors: [{ messageId: \\\"missingApproved\\\" }],\\n },\\n\\n {\\n code: `// Approved by team lead\\n // eslint-disable\\n const x = 5;`,\\n errors: [{ messageId: \\\"missingApproved\\\" }],\\n },\\n\\n {\\n code: `// Approved\\n // eslint-disable\\n const x = 5;\\n\\n // eslint-disable\\n const y = 10;`,\\n errors: [{ messageId: \\\"missingApproved\\\" }],\\n },\\n\\n {\\n code: `// not Approved\\n // eslint-disable\\n const x = 5;`,\\n errors: [{ messageId: \\\"missingApproved\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\n\\nrunTests(\\\"no-eslint-disable-without-approved\\\", rule, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-fd-prefix-in-folders.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 IGNORED_PATH_PARTS = [\\\"input-file\\\", \\\"node_modules\\\"];\\n\\nconst noFdPrefixInFolders = createRule({\\n name: \\\"no-fd-prefix-in-folders\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Must not use fd prefix in folder names\\\",\\n },\\n messages: {\\n noFdPrefixInFolders: \\\"Folder name '{{folder}}' must not start with 'fd'\\\",\\n },\\n schema: [],\\n },\\n create(context: RuleContext<\\\"noFdPrefixInFolders\\\", []>) {\\n const fileName = context.filename;\\n\\n for (const ignored of IGNORED_PATH_PARTS) {\\n if (fileName.includes(ignored)) {\\n return {};\\n }\\n }\\n\\n const dirParts = path\\n .dirname(fileName)\\n .split(/[/\\\\\\\\]+/)\\n .filter(Boolean);\\n\\n for (const part of dirParts) {\\n if (part.toLowerCase().startsWith(\\\"fd\\\")) {\\n context.report({\\n loc: { line: 1, column: 0 },\\n messageId: \\\"noFdPrefixInFolders\\\",\\n data: { folder: part },\\n });\\n break;\\n }\\n }\\n\\n return {};\\n },\\n defaultOptions: [],\\n});\\n\\nexport default noFdPrefixInFolders;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport rule from \\\"@root/rules/no-fd-prefix-in-folders\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n //src/components/my-component.ts\\n export const a = 1;`,\\n filename: \\\"components/my-component.ts\\\",\\n },\\n {\\n code: `\\n //src/components/fd-component.ts\\n export const a = 1;`,\\n filename: \\\"components/my-component.ts\\\",\\n },\\n {\\n code: `\\n //src/folder/my-component.ts\\n export const a = 1;\\n `,\\n filename: \\\"src/folder/my-component.ts\\\",\\n },\\n {\\n code: `\\n // No filename provided\\n export const a = 1;\\n `,\\n filename: undefined,\\n },\\n {\\n code: `\\n //my-component.ts\\n export const a = 1;\\n `,\\n filename: \\\"my-component.ts\\\",\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n //src/fd-utils/my-component.ts\\n export const a = 1;`,\\n filename: \\\"src/fd-utils/my-component.ts\\\",\\n errors: [{ messageId: \\\"noFdPrefixInFolders\\\" }],\\n },\\n {\\n code: `\\n //fd-utils/my-component.ts\\n export const a = 1;`,\\n filename: \\\"fd-utils/my-component.ts\\\",\\n errors: [{ messageId: \\\"noFdPrefixInFolders\\\" }],\\n },\\n {\\n code: `\\n //fd/utils/my-component.ts\\n export const a = 1;`,\\n filename: \\\"fd/utils/my-component.ts\\\",\\n errors: [{ messageId: \\\"noFdPrefixInFolders\\\" }],\\n },\\n {\\n code: `\\n //src/fdLogic/my-component.ts\\n export const a = 1;`,\\n filename: \\\"src/fdLogic/my-component.ts\\\",\\n errors: [{ messageId: \\\"noFdPrefixInFolders\\\" }],\\n },\\n {\\n code: `\\n //src/utils/helpers/fd-logic/test.ts\\n export const a = 1;\\n `,\\n filename: \\\"src/utils/helpers/fd-logic/test.ts\\\",\\n errors: [{ messageId: \\\"noFdPrefixInFolders\\\" }],\\n },\\n {\\n code: `\\n //src/fdlogic/my-component.ts\\n export const a = 1;\\n `,\\n filename: \\\"src/fdlogic/my-component.ts\\\",\\n errors: [{ messageId: \\\"noFdPrefixInFolders\\\" }],\\n },\\n {\\n code: `\\n //src/fd_component/my-component.ts\\n export const a = 1;\\n `,\\n filename: \\\"src/fd_component/my-component.ts\\\",\\n errors: [{ messageId: \\\"noFdPrefixInFolders\\\" }],\\n },\\n {\\n code: `\\n //src/fds/my-component.ts\\n export const a = 1;\\n `,\\n filename: \\\"src/fds/my-component.ts\\\",\\n errors: [{ messageId: \\\"noFdPrefixInFolders\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"no-fd-prefix-in-folders\\\", rule, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-get-in-function-names-without-return.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\\ninterface RuleOptions {\\n prefixes?: readonly string[];\\n exceptions?: readonly string[];\\n maxRecursionDepth?: number;\\n}\\n\\nconst constants = {\\n url: \\\"https://example.com/rules/\\\",\\n ruleName: \\\"no-get-in-function-names-without-return\\\",\\n defaults: {\\n prefixes: [\\\"get\\\"],\\n exceptions: [],\\n maxRecursionDepth: 10,\\n },\\n messageIds: {\\n noGetInFunctionNamesWithoutReturn: \\\"noGetInFunctionNamesWithoutReturn\\\",\\n },\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description:\\n \\\"Prohibit function names that begin with specified prefixes and do not return values\\\",\\n },\\n messages: {\\n noGetInFunctionNamesWithoutReturn:\\n \\\"Function '{{functionName}}' starts with '{{prefix}}' but does not have a return value\\\",\\n },\\n schema: [\\n {\\n type: \\\"object\\\",\\n properties: {\\n prefixes: { type: \\\"array\\\", items: { type: \\\"string\\\" } },\\n exceptions: { type: \\\"array\\\", items: { type: \\\"string\\\" } },\\n maxRecursionDepth: { type: \\\"number\\\" },\\n },\\n additionalProperties: false,\\n },\\n ],\\n },\\n nodeTypes: {\\n Identifier: AST_NODE_TYPES.Identifier,\\n FunctionDeclaration: AST_NODE_TYPES.FunctionDeclaration,\\n FunctionExpression: AST_NODE_TYPES.FunctionExpression,\\n ArrowFunctionExpression: AST_NODE_TYPES.ArrowFunctionExpression,\\n VariableDeclarator: AST_NODE_TYPES.VariableDeclarator,\\n BlockStatement: AST_NODE_TYPES.BlockStatement,\\n ReturnStatement: AST_NODE_TYPES.ReturnStatement,\\n SwitchStatement: AST_NODE_TYPES.SwitchStatement,\\n IfStatement: AST_NODE_TYPES.IfStatement,\\n },\\n nodeKeys: {\\n id: \\\"id\\\",\\n name: \\\"name\\\",\\n parent: \\\"parent\\\",\\n body: \\\"body\\\",\\n consequent: \\\"consequent\\\",\\n alternate: \\\"alternate\\\",\\n cases: \\\"cases\\\",\\n argument: \\\"argument\\\",\\n init: \\\"init\\\",\\n },\\n values: {\\n anonymous: \\\"anonymous\\\",\\n empty: \\\"\\\",\\n },\\n} as const;\\n\\ntype AnyFunction =\\n | TSESTree.FunctionDeclaration\\n | TSESTree.FunctionExpression\\n | TSESTree.ArrowFunctionExpression;\\ntype MessageIds = keyof typeof constants.messageIds;\\n\\ninterface Services {\\n context: RuleContext<MessageIds, [RuleOptions?]>;\\n options: Required<RuleOptions>;\\n}\\n\\nfunction getFunctionName(node: AnyFunction) {\\n const idNode =\\n node.type !== constants.nodeTypes.ArrowFunctionExpression ? node[constants.nodeKeys.id] : null;\\n\\n if (idNode) {\\n return idNode[constants.nodeKeys.name];\\n }\\n\\n const parent = node[constants.nodeKeys.parent];\\n\\n if (parent.type === constants.nodeTypes.VariableDeclarator) {\\n const parentId = parent[constants.nodeKeys.id];\\n\\n if (parentId.type === constants.nodeTypes.Identifier) {\\n return parentId[constants.nodeKeys.name];\\n }\\n }\\n\\n return null;\\n}\\n\\nfunction hasReturnStatement(node: TSESTree.Node, services: Services, depth = 0): boolean {\\n if (depth > services.options.maxRecursionDepth) {\\n return false;\\n }\\n\\n if (node.type === constants.nodeTypes.BlockStatement) {\\n return node[constants.nodeKeys.body].some((statement) =>\\n hasReturnStatement(statement, services, depth + 1),\\n );\\n }\\n\\n if (node.type === constants.nodeTypes.ReturnStatement) {\\n return node[constants.nodeKeys.argument] !== null;\\n }\\n\\n if (node.type === constants.nodeTypes.IfStatement) {\\n const hasReturnInConsequent = hasReturnStatement(\\n node[constants.nodeKeys.consequent],\\n services,\\n depth + 1,\\n );\\n const alternateNode = node[constants.nodeKeys.alternate];\\n const hasReturnInAlternate = alternateNode\\n ? hasReturnStatement(alternateNode, services, depth + 1)\\n : false;\\n\\n return hasReturnInConsequent && hasReturnInAlternate;\\n }\\n\\n if (node.type === constants.nodeTypes.SwitchStatement) {\\n const hasDefault = node[constants.nodeKeys.cases].some((c) => c.test === null);\\n\\n if (!hasDefault) {\\n return false;\\n }\\n\\n return node[constants.nodeKeys.cases].every((c) =>\\n c.consequent.some((statement) => hasReturnStatement(statement, services, depth + 1)),\\n );\\n }\\n\\n return false;\\n}\\n\\nfunction checkFunction(node: AnyFunction, services: Services) {\\n const functionName = getFunctionName(node);\\n\\n if (!functionName || services.options.exceptions.includes(functionName)) {\\n return;\\n }\\n\\n const matchingPrefix = services.options.prefixes.find((prefix) => functionName.startsWith(prefix));\\n\\n if (!matchingPrefix) {\\n return;\\n }\\n\\n if (\\n node.type === constants.nodeTypes.ArrowFunctionExpression &&\\n node[constants.nodeKeys.body].type !== constants.nodeTypes.BlockStatement\\n ) {\\n return;\\n }\\n\\n if (!hasReturnStatement(node[constants.nodeKeys.body], services)) {\\n const reportNode =\\n node.type !== constants.nodeTypes.ArrowFunctionExpression && node.id ? node.id : node;\\n\\n services.context.report({\\n node: reportNode,\\n messageId: constants.messageIds.noGetInFunctionNamesWithoutReturn,\\n data: { functionName, prefix: matchingPrefix },\\n });\\n }\\n}\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName) => `${constants.url}${ruleName}`);\\n\\nconst noGetInFunctionNamesWithoutReturn = createRule<[RuleOptions?], MessageIds>({\\n name: constants.ruleName,\\n meta: {\\n ...constants.meta,\\n docs: { ...constants.meta.docs, url: `${constants.url}${constants.ruleName}` },\\n },\\n defaultOptions: [constants.defaults],\\n\\n create(context) {\\n const services: Services = {\\n context,\\n options: { ...constants.defaults, ...context.options[0] },\\n };\\n\\n return {\\n FunctionDeclaration(node) {\\n checkFunction(node, services);\\n },\\n FunctionExpression(node) {\\n checkFunction(node, services);\\n },\\n ArrowFunctionExpression(node) {\\n checkFunction(node, services);\\n },\\n };\\n },\\n});\\n\\nexport default noGetInFunctionNamesWithoutReturn;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noGetInFunctionNamesWithoutReturn from \\\"@root/rules/no-get-in-function-names-without-return\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `function getFoo() { return 42; }`,\\n },\\n {\\n code: `const getBar = () => { return \\\"baz\\\"; };`,\\n },\\n {\\n code: `const getBaz = () => \\\"qux\\\";`,\\n },\\n {\\n code: `\\n function getQux(val: number) {\\n switch (val) {\\n case 1: return \\\"one\\\";\\n case 2: return \\\"two\\\";\\n default: return \\\"other\\\";\\n }\\n }\\n `,\\n },\\n {\\n code: `\\n function getWaldo(val: boolean) {\\n if (val) {\\n return \\\"A\\\";\\n } else {\\n return \\\"B\\\";\\n }\\n }\\n `,\\n },\\n {\\n code: `function doSomething() { console.log(\\\"hello\\\"); }`,\\n },\\n {\\n code: `function getGarply() {}`,\\n options: [{ exceptions: [\\\"getGarply\\\"] }],\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `function getFoo() { console.log(\\\"no return\\\"); }`,\\n errors: [\\n {\\n messageId: \\\"noGetInFunctionNamesWithoutReturn\\\",\\n data: { functionName: \\\"getFoo\\\", prefix: \\\"get\\\" },\\n },\\n ],\\n },\\n {\\n code: `const getBar = () => { const y = 10; };`,\\n errors: [\\n {\\n messageId: \\\"noGetInFunctionNamesWithoutReturn\\\",\\n data: { functionName: \\\"getBar\\\", prefix: \\\"get\\\" },\\n },\\n ],\\n },\\n {\\n code: `\\n function getBaz(val: number) {\\n switch (val) {\\n case 1: console.log(\\\"one\\\"); break;\\n }\\n }\\n `,\\n errors: [\\n {\\n messageId: \\\"noGetInFunctionNamesWithoutReturn\\\",\\n data: { functionName: \\\"getBaz\\\", prefix: \\\"get\\\" },\\n },\\n ],\\n },\\n {\\n code: `\\n function getQux() {\\n if (true) {\\n return 10;\\n }\\n }\\n `,\\n errors: [\\n {\\n messageId: \\\"noGetInFunctionNamesWithoutReturn\\\",\\n data: { functionName: \\\"getQux\\\", prefix: \\\"get\\\" },\\n },\\n ],\\n },\\n {\\n code: `\\n function getWaldo() {\\n function inner() { return \\\"inner\\\"; }\\n inner();\\n }\\n `,\\n errors: [\\n {\\n messageId: \\\"noGetInFunctionNamesWithoutReturn\\\",\\n data: { functionName: \\\"getWaldo\\\", prefix: \\\"get\\\" },\\n },\\n ],\\n },\\n {\\n code: `\\n const getThud = () => {\\n const inner = () => { return \\\"inner\\\"; };\\n inner();\\n };\\n `,\\n errors: [\\n {\\n messageId: \\\"noGetInFunctionNamesWithoutReturn\\\",\\n data: { functionName: \\\"getThud\\\", prefix: \\\"get\\\" },\\n },\\n ],\\n },\\n {\\n code: `\\n function getPlugh() {\\n try {\\n const result = doSomething();\\n } catch (error) {\\n console.error(error);\\n }\\n }\\n `,\\n errors: [\\n {\\n messageId: \\\"noGetInFunctionNamesWithoutReturn\\\",\\n data: { functionName: \\\"getPlugh\\\", prefix: \\\"get\\\" },\\n },\\n ],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\n\\nrunTests(\\\"no-get-in-function-names-without-return\\\", noGetInFunctionNamesWithoutReturn, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-include-unnecessary-parameters.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 urls: {\\n base: \\\"https://example.com/rules/\\\",\\n },\\n meta: {\\n type: \\\"problem\\\",\\n ruleName: \\\"no-include-unnecessary-parameters\\\",\\n description: \\\"Disallow unnecessary function parameters.\\\",\\n },\\n messages: {\\n unnecessaryParameter: \\\"Parameter '{{param}}' is not used inside the function.\\\",\\n },\\n messageId: \\\"unnecessaryParameter\\\",\\n schema: [],\\n defaultOptions: [],\\n} as const;\\n\\ntype MessageIds = \\\"unnecessaryParameter\\\";\\ntype RuleOptions = readonly [];\\n\\nfunction collectUsedIdentifiers(body?: TSESTree.BlockStatement | TSESTree.Expression) {\\n const used = new Set<string>();\\n\\n if (body) {\\n function handleChild(value: unknown) {\\n if (typeof value === \\\"object\\\" && value && \\\"type\\\" in value) {\\n traverse(value as TSESTree.Node);\\n }\\n }\\n\\n function handleArray(arr: unknown[]) {\\n for (const child of arr) {\\n handleChild(child);\\n }\\n }\\n\\n function traverse(node: TSESTree.Node) {\\n if (node.type === \\\"Identifier\\\" && \\\"name\\\" in node) {\\n used.add((node as TSESTree.Identifier).name);\\n }\\n\\n for (const [key, value] of Object.entries(node)) {\\n if (key !== \\\"parent\\\") {\\n if (Array.isArray(value)) {\\n handleArray(value);\\n } else {\\n handleChild(value);\\n }\\n }\\n }\\n }\\n\\n traverse(body);\\n }\\n\\n return used;\\n}\\n\\nfunction getParamIdentifiers(param: TSESTree.Parameter) {\\n const identifiers: TSESTree.Identifier[] = [];\\n\\n function extract(node: TSESTree.Node) {\\n switch (node.type) {\\n case \\\"Identifier\\\":\\n identifiers.push(node);\\n break;\\n case \\\"AssignmentPattern\\\":\\n extract(node.left);\\n break;\\n case \\\"RestElement\\\":\\n extract(node.argument);\\n break;\\n case \\\"ObjectPattern\\\":\\n for (const prop of node.properties) {\\n if (prop.type === \\\"Property\\\") {\\n extract(prop.value);\\n } else if (prop.type === \\\"RestElement\\\") {\\n extract(prop.argument);\\n }\\n }\\n break;\\n case \\\"ArrayPattern\\\":\\n for (const element of node.elements) {\\n if (element) extract(element);\\n }\\n break;\\n default:\\n break;\\n }\\n }\\n\\n extract(param);\\n return identifiers;\\n}\\n\\nfunction checkUnusedParams(\\n node: TSESTree.FunctionDeclaration | TSESTree.FunctionExpression | TSESTree.ArrowFunctionExpression,\\n context: RuleContext<MessageIds, RuleOptions>,\\n) {\\n const usedNames = collectUsedIdentifiers(node.body);\\n\\n for (const param of node.params) {\\n for (const ident of getParamIdentifiers(param)) {\\n if (!usedNames.has(ident.name) && ident.name !== \\\"_\\\") {\\n context.report({\\n node: ident,\\n messageId: constants.messageId,\\n data: { param: ident.name },\\n });\\n }\\n }\\n }\\n}\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName) => `${constants.urls.base}${ruleName}`);\\n\\nconst noIncludeUnnecessaryParams = createRule({\\n name: constants.meta.ruleName,\\n meta: {\\n type: constants.meta.type,\\n docs: {\\n description: constants.meta.description,\\n },\\n messages: constants.messages,\\n schema: constants.schema,\\n },\\n defaultOptions: constants.defaultOptions,\\n\\n create(context) {\\n return {\\n FunctionDeclaration(node) {\\n checkUnusedParams(node, context);\\n },\\n FunctionExpression(node) {\\n checkUnusedParams(node, context);\\n },\\n ArrowFunctionExpression(node) {\\n checkUnusedParams(node, context);\\n },\\n };\\n },\\n});\\n\\nexport default noIncludeUnnecessaryParams;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noUnnecessaryParams from \\\"@root/rules/no-include-unnecessary-parameters\\\";\\n\\nconst validCases = {\\n valid: [\\n { code: `function foo() {}` },\\n { code: `const bar = (a) => { return a + 1; };` },\\n { code: `function baz(a, b) { return a + b; }` },\\n { code: `function foo({ x }) { return x; }` },\\n { code: `const fn = ([a, b]) => a + b;` },\\n { code: `function foo({ x: { y } }) { return y; }` },\\n { code: `function bar(...args) { return args.length; }` },\\n { code: `function bar(a = 1) { return a; }` },\\n { code: `function foo([a, [b, c]]) { return a + b + c; }` },\\n { code: `function foo(_, b) { return b; }` },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `function foo(a) {}`,\\n errors: [{ messageId: \\\"unnecessaryParameter\\\", data: { param: \\\"a\\\" } }],\\n },\\n {\\n code: `function foo({ x }) {}`,\\n errors: [{ messageId: \\\"unnecessaryParameter\\\", data: { param: \\\"x\\\" } }],\\n },\\n {\\n code: `const fn = ([a, b]) => a;`,\\n errors: [{ messageId: \\\"unnecessaryParameter\\\", data: { param: \\\"b\\\" } }],\\n },\\n {\\n code: `function foo([a, [b, c]]) { return b; }`,\\n errors: [\\n { messageId: \\\"unnecessaryParameter\\\", data: { param: \\\"a\\\" } },\\n { messageId: \\\"unnecessaryParameter\\\", data: { param: \\\"c\\\" } },\\n ],\\n },\\n {\\n code: `function bar(a, ...args) { return a; }`,\\n errors: [{ messageId: \\\"unnecessaryParameter\\\", data: { param: \\\"args\\\" } }],\\n },\\n {\\n code: `function bar(a = 1) {}`,\\n errors: [{ messageId: \\\"unnecessaryParameter\\\", data: { param: \\\"a\\\" } }],\\n },\\n {\\n code: `function foo({ x: { y }, z }) { return z; }`,\\n errors: [{ messageId: \\\"unnecessaryParameter\\\", data: { param: \\\"y\\\" } }],\\n },\\n {\\n code: `function foo(a, b, c) { return b; }`,\\n errors: [\\n { messageId: \\\"unnecessaryParameter\\\", data: { param: \\\"a\\\" } },\\n { messageId: \\\"unnecessaryParameter\\\", data: { param: \\\"c\\\" } },\\n ],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"no-include-unnecessary-parameters\\\", noUnnecessaryParams, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-integers-instead-of-enums.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree, AST_NODE_TYPES, type ParserServices } from \\\"@typescript-eslint/utils\\\";\\nimport { type RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\nimport ts from \\\"typescript\\\";\\n\\nconst constants = {\\n url: \\\"https://example.com/rules/\\\",\\n ruleName: \\\"no-integers-instead-of-enums\\\",\\n messageIds: {\\n noIntegersInsteadOfEnums: \\\"noIntegersInsteadOfEnums\\\",\\n },\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description:\\n \\\"Disallow using integers where a pseudo-enum (union of number \\\" +\\n \\\"literals derived from an object) is expected.\\\",\\n },\\n messages: {\\n noIntegersInsteadOfEnums:\\n \\\"Integer literal '{{literalValue}}' used where a pseudo-enum \\\" +\\n \\\"(union of number literals) is expected. Use a member of the \\\" +\\n \\\"corresponding object.\\\",\\n },\\n schema: [],\\n },\\n nodeTypes: {\\n Literal: AST_NODE_TYPES.Literal,\\n VariableDeclarator: AST_NODE_TYPES.VariableDeclarator,\\n AssignmentExpression: AST_NODE_TYPES.AssignmentExpression,\\n Property: AST_NODE_TYPES.Property,\\n ReturnStatement: AST_NODE_TYPES.ReturnStatement,\\n CallExpression: AST_NODE_TYPES.CallExpression,\\n ArrayExpression: AST_NODE_TYPES.ArrayExpression,\\n JSXAttribute: AST_NODE_TYPES.JSXAttribute,\\n JSXExpressionContainer: AST_NODE_TYPES.JSXExpressionContainer,\\n UnaryExpression: AST_NODE_TYPES.UnaryExpression,\\n Identifier: AST_NODE_TYPES.Identifier,\\n },\\n types: {\\n number: \\\"number\\\",\\n },\\n operators: {\\n minus: \\\"-\\\",\\n plus: \\\"+\\\",\\n },\\n suffixes: {\\n expression: \\\"Expression\\\",\\n },\\n} as const;\\n\\ntype MessageIds = typeof constants.messageIds.noIntegersInsteadOfEnums;\\ntype RuleOptions = [];\\n\\ninterface Services {\\n checker: ts.TypeChecker;\\n tsNodeMap: ParserServices[\\\"esTreeNodeToTSNodeMap\\\"];\\n reportedNodes: Set<string>;\\n context: RuleContext<MessageIds, RuleOptions>;\\n}\\n\\nfunction isValueNumber(value: unknown): value is number {\\n return typeof value === constants.types.number;\\n}\\n\\nfunction isUnionOfNumberLiterals(type: ts.Type) {\\n return type.isUnion() && type.types.every((t) => (t.flags & ts.TypeFlags.NumberLiteral) !== 0);\\n}\\n\\nfunction getLiteralValue(node: TSESTree.Node) {\\n if (node.type === constants.nodeTypes.Literal && isValueNumber(node.value)) {\\n return node.value;\\n }\\n\\n if (\\n node.type === constants.nodeTypes.UnaryExpression &&\\n node.argument.type === constants.nodeTypes.Literal &&\\n isValueNumber(node.argument.value)\\n ) {\\n if (node.operator === constants.operators.minus) return -node.argument.value;\\n\\n if (node.operator === constants.operators.plus) return node.argument.value;\\n }\\n\\n return undefined;\\n}\\n\\nfunction isExpression(node: TSESTree.Node) {\\n const nodeType = node.type;\\n return (\\n nodeType.endsWith(constants.suffixes.expression) ||\\n nodeType === constants.nodeTypes.Literal ||\\n nodeType === constants.nodeTypes.Identifier\\n );\\n}\\n\\nfunction reportIfNeeded(tsNode: ts.Node, reportNode: TSESTree.Node, value: number, services: Services) {\\n const key = `${reportNode.range[0]}-${reportNode.range[1]}`;\\n\\n if (services.reportedNodes.has(key) || !ts.isExpression(tsNode)) {\\n return;\\n }\\n\\n const contextualType = services.checker.getContextualType(tsNode);\\n const nodeType = services.checker.getTypeAtLocation(tsNode);\\n\\n if (\\n contextualType &&\\n isUnionOfNumberLiterals(contextualType) &&\\n (nodeType.flags & ts.TypeFlags.NumberLiteral) !== 0\\n ) {\\n services.context.report({\\n node: reportNode,\\n messageId: constants.messageIds.noIntegersInsteadOfEnums,\\n data: { literalValue: String(value) },\\n });\\n services.reportedNodes.add(key);\\n }\\n}\\n\\nfunction checkExpression(node: TSESTree.Node | null | undefined, services: Services) {\\n if (!node) return;\\n\\n const value = getLiteralValue(node);\\n\\n if (!isValueNumber(value)) return;\\n\\n const tsNode = services.tsNodeMap.get(node);\\n\\n if (!tsNode) return;\\n\\n reportIfNeeded(tsNode, node, value, services);\\n}\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${constants.url}${ruleName}`);\\n\\nconst noIntegersInsteadOfEnums = createRule<RuleOptions, MessageIds>({\\n name: constants.ruleName,\\n meta: constants.meta,\\n defaultOptions: [],\\n create(context) {\\n const parserServices = context.sourceCode.parserServices;\\n\\n if (!parserServices?.program || !parserServices.esTreeNodeToTSNodeMap) {\\n return {};\\n }\\n\\n const services: Services = {\\n checker: parserServices.program.getTypeChecker(),\\n tsNodeMap: parserServices.esTreeNodeToTSNodeMap,\\n reportedNodes: new Set<string>(),\\n context,\\n };\\n\\n return {\\n Literal(node: TSESTree.Literal) {\\n checkExpression(node, services);\\n },\\n UnaryExpression(node: TSESTree.UnaryExpression) {\\n checkExpression(node, services);\\n },\\n VariableDeclarator(node: TSESTree.VariableDeclarator) {\\n checkExpression(node.init, services);\\n },\\n ReturnStatement(node: TSESTree.ReturnStatement) {\\n checkExpression(node.argument, services);\\n },\\n Property(node: TSESTree.Property) {\\n if (isExpression(node.value)) {\\n checkExpression(node.value, services);\\n }\\n },\\n ArrayExpression(node: TSESTree.ArrayExpression) {\\n for (const element of node.elements) {\\n if (element && isExpression(element)) {\\n checkExpression(element, services);\\n }\\n }\\n },\\n AssignmentExpression(node: TSESTree.AssignmentExpression) {\\n checkExpression(node.right, services);\\n },\\n };\\n },\\n});\\n\\nexport default noIntegersInsteadOfEnums;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noIntegersInsteadOfEnums from \\\"@root/rules/no-integers-instead-of-enums\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n const bar = { foo: 0, baz: 1 } as const;\\n type Bar = typeof bar[keyof typeof bar];\\n const a: Bar = bar.foo;\\n const b: Bar = bar.baz;\\n `,\\n },\\n {\\n code: `\\n const a = 42;\\n `,\\n },\\n {\\n code: `\\n const bar = { foo: 0, baz: 1 } as const;\\n function useBar(val: number) {}\\n useBar(1);\\n `,\\n },\\n ],\\n};\\n\\nconst testCases = [validCases];\\n\\nrunTests(\\\"no-integers-instead-of-enums\\\", noIntegersInsteadOfEnums, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-long-filter-map.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 maxLines = 5;\\nconst callBackMethods = [\\\"filter\\\", \\\"map\\\"];\\n\\nconst noLongFilterMap = createRule({\\n name: \\\"no-long-filter-map\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Disallow filter-map constructions with too many lines of code\\\",\\n },\\n messages: {\\n noLongFilterMap: \\\"Filter-map construction is too long\\\",\\n },\\n schema: [],\\n },\\n create(context: RuleContext<\\\"noLongFilterMap\\\", []>) {\\n return {\\n CallExpression(node: TSESTree.CallExpression) {\\n const isFilterOrMap = (n: TSESTree.CallExpression): boolean =>\\n n.callee.type === \\\"MemberExpression\\\" &&\\n n.callee.property.type === \\\"Identifier\\\" &&\\n callBackMethods.includes(n.callee.property.name);\\n\\n let totalCallbackLines = 0;\\n let current: TSESTree.CallExpression | null = node;\\n\\n while (current && isFilterOrMap(current)) {\\n const arg = current.arguments[0];\\n\\n if (\\n arg &&\\n (arg.type === \\\"FunctionExpression\\\" || arg.type === \\\"ArrowFunctionExpression\\\") &&\\n arg.loc\\n ) {\\n const loc = arg.loc;\\n totalCallbackLines += loc.end.line - loc.start.line;\\n }\\n\\n if (\\n current.callee.type === \\\"MemberExpression\\\" &&\\n current.callee.object.type === \\\"CallExpression\\\"\\n ) {\\n current = current.callee.object;\\n } else {\\n break;\\n }\\n }\\n\\n if (totalCallbackLines > maxLines) {\\n context.report({\\n node,\\n messageId: \\\"noLongFilterMap\\\",\\n });\\n }\\n },\\n };\\n },\\n defaultOptions: [],\\n});\\n\\nexport default noLongFilterMap;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noLongFilterMap from \\\"@root/rules/no-long-filter-map\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n const result = items\\n .filter(x => x.enabled)\\n .map(x => x.value);\\n `,\\n },\\n {\\n code: `\\n const result = items\\n .filter(x => {\\n if (!x) return false;\\n return x.enabled;\\n });\\n `,\\n },\\n {\\n code: `\\n const result = items.map(x => {\\n const a = x.a;\\n const b = x.b;\\n const c = x.c;\\n return a + b + c;\\n });\\n `,\\n },\\n {\\n code: `\\n const result = items\\n .filter(x => {\\n return x.a;\\n })\\n .map(x => {\\n return x.b;\\n })\\n `,\\n },\\n {\\n code: `\\n const result = items\\n .filter(x => {\\n return x.a;\\n })\\n .map(x => {\\n return x.b;\\n })\\n\\n const result2 = items\\n .filter(x => {\\n return x.a;\\n })\\n .map(x => {\\n return x.b;\\n })\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n const result = items.map(x => {\\n const a = x.a;\\n const b = x.b;\\n const c = x.c;\\n const d = x.d;\\n return a + b + c + d;\\n });\\n `,\\n errors: [{ messageId: \\\"noLongFilterMap\\\" }],\\n },\\n {\\n code: `\\n const result = items\\n .filter(item => {\\n if (!item) return false;\\n if (item.type !== 'valid') return false;\\n if (item.disabled) return false;\\n return true;\\n })\\n .map(item => {\\n const a = item.valueA;\\n const b = item.valueB;\\n const c = item.valueC;\\n return a + b + c;\\n });\\n `,\\n errors: [{ messageId: \\\"noLongFilterMap\\\" }],\\n },\\n {\\n code: `\\n const result = items\\n .filter(x => {\\n return x.a;\\n })\\n .map(x => {\\n return x.b;\\n })\\n .filter(x => {\\n return x.c;\\n });\\n `,\\n errors: [{ messageId: \\\"noLongFilterMap\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"no-long-filter-map\\\", noLongFilterMap, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-new-date.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 date: \\\"Date\\\",\\n identifier: \\\"Identifier\\\",\\n} as const;\\n\\nconst noNewDate = createRule({\\n name: \\\"no-new-date\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Disallow the use of new Date(); use team's date utilities instead\\\",\\n },\\n messages: {\\n noNewDate: \\\"Must use our date functions instead of 'new Date()'\\\",\\n },\\n schema: [],\\n },\\n create(context: RuleContext<\\\"noNewDate\\\", []>) {\\n return {\\n NewExpression(node: TSESTree.NewExpression) {\\n if (\\n node.callee.type === nodeTypeIdentifiers.identifier &&\\n node.callee.name === nodeTypeIdentifiers.date\\n ) {\\n context.report({\\n node,\\n messageId: \\\"noNewDate\\\",\\n });\\n }\\n },\\n };\\n },\\n defaultOptions: [],\\n});\\n\\nexport default noNewDate;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noNewDate from \\\"@root/rules/no-new-date\\\";\\n\\nconst validCases = {\\n valid: [\\n { code: \\\"const d = getNow();\\\" },\\n { code: \\\"const Date = 123; const d = Date;\\\" },\\n { code: \\\"class MyDate {}; const d = new MyDate();\\\" },\\n { code: \\\"const d = Date();\\\" },\\n { code: \\\"const d = Date.now();\\\" },\\n { code: \\\"export type DateString = string;\\\" },\\n { code: \\\"import { DateTime } from 'luxon'; const d = DateTime.now();\\\" },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n { code: \\\"const d = new Date();\\\", errors: [{ messageId: \\\"noNewDate\\\" }] },\\n { code: \\\"const d = new Date(2020, 1, 1);\\\", errors: [{ messageId: \\\"noNewDate\\\" }] },\\n { code: \\\"function foo() { return new Date(); }\\\", errors: [{ messageId: \\\"noNewDate\\\" }] },\\n { code: \\\"const getNow = () => new Date();\\\", errors: [{ messageId: \\\"noNewDate\\\" }] },\\n {\\n code: \\\"class Timer { start() { this.started = new Date(); } }\\\",\\n errors: [{ messageId: \\\"noNewDate\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"no-new-date\\\", noNewDate, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-nullable-check.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, AST_NODE_TYPES } 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/\\\";\\nconst createRule = ESLintUtils.RuleCreator((ruleName) => `${url}${ruleName}`);\\n\\nfunction isNullOrUndefined(node: TSESTree.Expression | null) {\\n return (\\n node !== null &&\\n ((node.type === AST_NODE_TYPES.Literal && node.value === null) ||\\n (node.type === AST_NODE_TYPES.Identifier && node.name === \\\"undefined\\\") ||\\n (node.type === AST_NODE_TYPES.UnaryExpression && node.operator === \\\"void\\\"))\\n );\\n}\\n\\nfunction findPropertyInObject(objectExpression: TSESTree.ObjectExpression, propertyName: string) {\\n return objectExpression.properties.find(\\n (p): p is TSESTree.Property =>\\n p.type === AST_NODE_TYPES.Property &&\\n p.key.type === AST_NODE_TYPES.Identifier &&\\n p.key.name === propertyName,\\n );\\n}\\n\\nfunction isDefinitelyNotNullable(annotation: TSESTree.TSTypeAnnotation | undefined) {\\n if (!annotation) return false;\\n\\n const typeNode = annotation.typeAnnotation;\\n\\n if (typeNode.type === AST_NODE_TYPES.TSUnionType) {\\n return !typeNode.types.some(\\n (t) => t.type === AST_NODE_TYPES.TSNullKeyword || t.type === AST_NODE_TYPES.TSUndefinedKeyword,\\n );\\n }\\n\\n return (\\n typeNode.type !== AST_NODE_TYPES.TSNullKeyword && typeNode.type !== AST_NODE_TYPES.TSUndefinedKeyword\\n );\\n}\\n\\nfunction isObjectWithUntypedType(value: unknown): value is { type: unknown } {\\n return typeof value === \\\"object\\\" && value !== null && \\\"type\\\" in value;\\n}\\n\\nfunction isExpression(node: unknown): node is TSESTree.Expression {\\n if (!isObjectWithUntypedType(node) || typeof node.type !== \\\"string\\\") {\\n return false;\\n }\\n\\n return isExpressionType(node.type);\\n}\\n\\nfunction isExpressionType(type: string): type is TSESTree.Expression[\\\"type\\\"] {\\n return [\\n \\\"ArrayExpression\\\",\\n \\\"ArrowFunctionExpression\\\",\\n \\\"AssignmentExpression\\\",\\n \\\"AwaitExpression\\\",\\n \\\"BinaryExpression\\\",\\n \\\"CallExpression\\\",\\n \\\"ChainExpression\\\",\\n \\\"ClassExpression\\\",\\n \\\"ConditionalExpression\\\",\\n \\\"FunctionExpression\\\",\\n \\\"Identifier\\\",\\n \\\"ImportExpression\\\",\\n \\\"Literal\\\",\\n \\\"LogicalExpression\\\",\\n \\\"MemberExpression\\\",\\n \\\"MetaProperty\\\",\\n \\\"NewExpression\\\",\\n \\\"ObjectExpression\\\",\\n \\\"SequenceExpression\\\",\\n \\\"Super\\\",\\n \\\"TaggedTemplateExpression\\\",\\n \\\"TemplateLiteral\\\",\\n \\\"ThisExpression\\\",\\n \\\"UnaryExpression\\\",\\n \\\"UpdateExpression\\\",\\n \\\"YieldExpression\\\",\\n \\\"TSAsExpression\\\",\\n \\\"TSNonNullExpression\\\",\\n \\\"TSTypeAssertion\\\",\\n ].includes(type);\\n}\\n\\nfunction isSafeObjectInit(\\n init: TSESTree.Expression,\\n node: TSESTree.MemberExpression,\\n context: RuleContext<\\\"avoidOptionalChaining\\\", []>,\\n) {\\n if (init.type === AST_NODE_TYPES.ObjectExpression && node.property.type === AST_NODE_TYPES.Identifier) {\\n const prop = findPropertyInObject(init, node.property.name);\\n const expr = prop?.value;\\n\\n if (prop && expr !== undefined && isExpression(expr) && !isNullOrUndefined(expr)) {\\n context.report({\\n node,\\n messageId: \\\"avoidOptionalChaining\\\",\\n });\\n }\\n } else if (init.type === AST_NODE_TYPES.NewExpression || init.type === AST_NODE_TYPES.ArrayExpression) {\\n context.report({\\n node,\\n messageId: \\\"avoidOptionalChaining\\\",\\n });\\n }\\n}\\n\\nfunction checkVariableTypeAnnotation(\\n declarator: TSESTree.VariableDeclarator,\\n node: TSESTree.MemberExpression,\\n context: RuleContext<\\\"avoidOptionalChaining\\\", []>,\\n) {\\n if (\\n declarator.id.type === AST_NODE_TYPES.Identifier &&\\n isDefinitelyNotNullable(declarator.id.typeAnnotation)\\n ) {\\n context.report({\\n node,\\n messageId: \\\"avoidOptionalChaining\\\",\\n });\\n return true;\\n }\\n\\n return false;\\n}\\n\\nfunction checkOptionalChaining(\\n node: TSESTree.MemberExpression,\\n context: RuleContext<\\\"avoidOptionalChaining\\\", []>,\\n) {\\n if (!node.optional) return;\\n\\n const object = node.object;\\n\\n if (object.type !== AST_NODE_TYPES.Identifier) return;\\n\\n const currentScope = context.sourceCode.getScope(node);\\n const variable = currentScope.variables.find((v) => v.name === object.name);\\n const definition = variable ? variable.defs[0] : undefined;\\n\\n if (!definition) return;\\n\\n if (definition.type === \\\"Parameter\\\") {\\n const paramNode = definition.name;\\n\\n if (isDefinitelyNotNullable(paramNode.typeAnnotation)) {\\n context.report({\\n node,\\n messageId: \\\"avoidOptionalChaining\\\",\\n });\\n }\\n\\n return;\\n }\\n\\n if (definition.node?.type === AST_NODE_TYPES.VariableDeclarator) {\\n const reported = checkVariableTypeAnnotation(definition.node, node, context);\\n\\n if (reported) return;\\n\\n if (definition.node.init) {\\n isSafeObjectInit(definition.node.init, node, context);\\n }\\n }\\n}\\n\\nconst noNullableCheck = createRule({\\n name: \\\"no-nullable-check\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Must not use '?' when we know that the value is not null\\\",\\n },\\n messages: {\\n avoidOptionalChaining: \\\"Must not use '?' when the value is not null\\\",\\n },\\n schema: [],\\n },\\n defaultOptions: [],\\n create(context: RuleContext<\\\"avoidOptionalChaining\\\", []>) {\\n return {\\n MemberExpression(node) {\\n checkOptionalChaining(node, context);\\n },\\n };\\n },\\n});\\n\\nexport default noNullableCheck;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport rule from \\\"@root/rules/no-nullable-check\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n const foo = getFoo();\\n const value = foo?.bar;\\n `,\\n },\\n {\\n code: `\\n const foo: Foo | null = getFoo();\\n const value = foo?.bar;\\n `,\\n },\\n {\\n code: `\\n const bar: Bar | undefined = getBar();\\n const result = bar?.baz();\\n `,\\n },\\n {\\n code: `\\n const baz: Baz | null | undefined = getBaz();\\n baz?.qux;\\n `,\\n },\\n {\\n code: `\\n function f(a) {\\n return a?.toString();\\n }\\n `,\\n },\\n {\\n code: `\\n let foo: Foo | null = null; foo?.bar;`,\\n },\\n {\\n code: `\\n const bar: { baz: string } | undefined = getBar(); bar?.baz;`,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n const foo: Foo = new Foo();\\n const value = foo?.bar;\\n `,\\n errors: [{ messageId: \\\"avoidOptionalChaining\\\" }],\\n },\\n {\\n code: `\\n let bar: { baz: number } = { baz: 123 };\\n console.log(bar?.baz);\\n `,\\n errors: [{ messageId: \\\"avoidOptionalChaining\\\" }],\\n },\\n {\\n code: `\\n function f(a: number) {\\n return a?.toFixed(2);\\n }\\n `,\\n errors: [{ messageId: \\\"avoidOptionalChaining\\\" }],\\n },\\n {\\n code: `\\n const foo: Foo = new Foo(); foo?.getBar();`,\\n errors: [{ messageId: \\\"avoidOptionalChaining\\\" }],\\n },\\n {\\n code: `\\n let bar: { baz: string } = { baz: \\\"value\\\" }; bar?.baz;`,\\n errors: [{ messageId: \\\"avoidOptionalChaining\\\" }],\\n },\\n {\\n code: `\\n const baz: string = \\\"test\\\"; baz?.length;`,\\n errors: [{ messageId: \\\"avoidOptionalChaining\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"no-nullable-check\\\", rule, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-px-in-tailwind.ts' and a test for it.\",\"rule_code\":\"import { 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 noPxInTailwind = createRule({\\n name: \\\"no-px-in-tailwind\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Disallow px in tailwind styles\\\",\\n },\\n messages: {\\n noPxInTailwind: \\\"Do not use px in tailwind styles\\\",\\n },\\n schema: [],\\n },\\n create(context: RuleContext<\\\"noPxInTailwind\\\", []>) {\\n return {\\n JSXAttribute(node) {\\n if (node.name && node.name.name === \\\"className\\\") {\\n if (node.value && node.value.type === \\\"Literal\\\" && typeof node.value.value === \\\"string\\\") {\\n const classStr = node.value.value;\\n\\n const classes = classStr.split(/\\\\s+/);\\n const pxMatches = classes.filter((cls) => /\\\\[[^[\\\\]]*px[^[\\\\]]*\\\\]/.test(cls));\\n\\n if (pxMatches.length > 0) {\\n context.report({\\n node,\\n messageId: \\\"noPxInTailwind\\\",\\n });\\n }\\n }\\n }\\n },\\n };\\n },\\n defaultOptions: [],\\n});\\n\\nexport default noPxInTailwind;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noPxInTailwind from \\\"@root/rules/no-px-in-tailwind\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n filename: \\\"test.jsx\\\",\\n code: `<div className=\\\"mt-2 text-sm w-full\\\"></div>`,\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `<div></div>`,\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `<div className=\\\"mt-[1rem] w-[100%]\\\"></div>`,\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `<div className={someVar}></div>`,\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `<div style=\\\"width:[200px]\\\"></div>`,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n filename: \\\"test.jsx\\\",\\n code: `<div className=\\\"mt-[10px] text-[12px] w-[300px]\\\"></div>`,\\n errors: [{ messageId: \\\"noPxInTailwind\\\" }],\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `<div className=\\\"mt-[10px] w-[200px] text-[16px]\\\"></div>`,\\n errors: [{ messageId: \\\"noPxInTailwind\\\" }],\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `<div className=\\\"text-[14px] text-gray-800\\\"></div>`,\\n errors: [{ messageId: \\\"noPxInTailwind\\\" }],\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `<div className=\\\"hover:text-[10px] focus:w-[200px]\\\"></div>`,\\n errors: [{ messageId: \\\"noPxInTailwind\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"no-px-in-tailwind\\\", noPxInTailwind, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-redundant-type-alias-for-object.ts' and a test for it.\",\"rule_code\":\"import { AST_NODE_TYPES, ESLintUtils, TSESTree } from \\\"@typescript-eslint/utils\\\";\\n\\nconst url = \\\"https://example.com/rules/\\\";\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${url}${ruleName}`);\\n\\nfunction isEnumLikeConstant(node: TSESTree.VariableDeclarator): boolean {\\n if (node.id.type !== \\\"Identifier\\\") return false;\\n\\n let init = node.init;\\n let isConstAssertion = false;\\n\\n if (init && init.type === \\\"TSAsExpression\\\") {\\n if (\\n init.typeAnnotation.type === \\\"TSTypeReference\\\" &&\\n init.typeAnnotation.typeName.type === \\\"Identifier\\\"\\n ) {\\n if (init.typeAnnotation.typeName.name === \\\"const\\\") {\\n isConstAssertion = true;\\n }\\n }\\n\\n init = init.expression;\\n }\\n\\n if (!init || init.type !== \\\"ObjectExpression\\\") return false;\\n\\n if (!isConstAssertion) return false;\\n\\n const values: string[] = [];\\n\\n init.properties.forEach((prop) => {\\n if (prop.type !== \\\"Property\\\") return;\\n\\n const value = prop.value;\\n\\n if (value.type === \\\"Literal\\\") {\\n values.push(typeof value.value);\\n } else if (value.type === \\\"MemberExpression\\\") {\\n values.push(\\\"reference\\\");\\n }\\n });\\n\\n return values.length !== 0 && values.every((v) => v === values[0]);\\n}\\n\\nfunction isRedundantTypeAlias(\\n node: TSESTree.TSTypeAliasDeclaration,\\n enumLikeConsts: Map<string, TSESTree.VariableDeclarator>,\\n) {\\n const typeAnnotation = node.typeAnnotation;\\n\\n if (typeAnnotation.type !== \\\"TSIndexedAccessType\\\") return false;\\n\\n const { objectType, indexType } = typeAnnotation;\\n\\n if (\\n objectType.type !== \\\"TSTypeQuery\\\" ||\\n indexType.type !== \\\"TSTypeOperator\\\" ||\\n indexType.operator !== \\\"keyof\\\" ||\\n (indexType.typeAnnotation && indexType.typeAnnotation.type !== \\\"TSTypeQuery\\\")\\n )\\n return false;\\n\\n const objName1 = objectType.exprName.type === \\\"Identifier\\\" ? objectType.exprName.name : null;\\n const objName2 =\\n indexType.typeAnnotation && indexType.typeAnnotation.exprName.type === \\\"Identifier\\\"\\n ? indexType.typeAnnotation.exprName.name\\n : null;\\n\\n if (!objName1 || !objName2 || objName1 !== objName2) return false;\\n\\n return !enumLikeConsts.has(objName1);\\n}\\n\\nconst noRedundantTypeAlias = createRule({\\n name: \\\"no-redundant-type-alias\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Disallow redundant type aliases for non-enum-like objects\\\",\\n },\\n messages: {\\n noRedundantTypeAlias: \\\"Do not use redundant type alias for non enum-like objects\\\",\\n },\\n schema: [],\\n },\\n defaultOptions: [],\\n create(context) {\\n const enumLikeConsts = new Map<string, TSESTree.VariableDeclarator>();\\n\\n return {\\n VariableDeclarator(node) {\\n if (isEnumLikeConstant(node)) {\\n if (node.id.type === AST_NODE_TYPES.Identifier) {\\n enumLikeConsts.set(node.id.name, node);\\n }\\n }\\n },\\n\\n TSTypeAliasDeclaration(node) {\\n if (isRedundantTypeAlias(node, enumLikeConsts)) {\\n context.report({\\n node,\\n messageId: \\\"noRedundantTypeAlias\\\",\\n });\\n }\\n },\\n };\\n },\\n});\\n\\nexport default noRedundantTypeAlias;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noRedundantTypeAlias from \\\"@root/rules/no-redundant-type-alias-for-object\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n export const foo = {\\n bar: \\\"Bar\\\",\\n };\\n type Bar = typeof foo.bar;\\n `,\\n },\\n {\\n code: `\\n const colors = {\\n red: \\\"#f00\\\",\\n green: \\\"#0f0\\\",\\n };\\n type Color = typeof colors.red;\\n `,\\n },\\n {\\n code: `\\n export enum Foo {\\n A = \\\"A\\\",\\n B = \\\"B\\\",\\n }\\n export type FooValues = Foo[keyof typeof Foo]; \\n `,\\n },\\n {\\n code: `\\n type Status = \\\"pending\\\" | \\\"done\\\" | \\\"error\\\";\\n `,\\n },\\n {\\n code: `\\n const foo = {\\n a: \\\"A\\\",\\n b: \\\"B\\\",\\n } as const;\\n type Foo = (typeof foo)[keyof typeof foo];\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n export const foo = {\\n bar: \\\"Bar\\\",\\n };\\n export type Foo = (typeof foo)[keyof typeof foo];\\n `,\\n errors: [{ messageId: \\\"noRedundantTypeAlias\\\" }],\\n },\\n {\\n code: `\\n const status = {\\n pending: \\\"pending\\\",\\n done: \\\"done\\\",\\n };\\n export type Status = (typeof status)[keyof typeof status];\\n `,\\n errors: [{ messageId: \\\"noRedundantTypeAlias\\\" }],\\n },\\n {\\n code: `\\n export const directions = {\\n up: \\\"UP\\\",\\n down: \\\"DOWN\\\",\\n };\\n export type Direction = (typeof directions)[keyof typeof directions];\\n `,\\n errors: [{ messageId: \\\"noRedundantTypeAlias\\\" }],\\n },\\n {\\n code: `\\n const foo = {\\n a: 1,\\n b: 2,\\n };\\n export type Foo = (typeof foo)[keyof typeof foo]; \\n `,\\n errors: [{ messageId: \\\"noRedundantTypeAlias\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"no-redundant-type-alias\\\", noRedundantTypeAlias, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-specify-return-type.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: \\\"no-specify-return-type\\\",\\n messageIds: {\\n noSpecifyReturnType: \\\"noSpecifyReturnType\\\",\\n },\\n meta: {\\n type: \\\"suggestion\\\",\\n docs: {\\n description: \\\"Disallow explicit return type annotations when they are unnecessary\\\",\\n },\\n messages: {\\n mustNotSpecifyReturnType: \\\"Must not specify return type when it can be inferred\\\",\\n },\\n schema: [],\\n },\\n nodeTypes: {\\n functionDeclaration: AST_NODE_TYPES.FunctionDeclaration,\\n methodDefinition: AST_NODE_TYPES.MethodDefinition,\\n arrowFunctionExpression: AST_NODE_TYPES.ArrowFunctionExpression,\\n functionExpression: AST_NODE_TYPES.FunctionExpression,\\n tsTypeReference: AST_NODE_TYPES.TSTypeReference,\\n tsPredicateType: AST_NODE_TYPES.TSTypePredicate,\\n identifier: AST_NODE_TYPES.Identifier,\\n tsTypeQuery: AST_NODE_TYPES.TSTypeQuery,\\n property: AST_NODE_TYPES.Property,\\n thisExpression: AST_NODE_TYPES.ThisExpression,\\n },\\n typeNames: {\\n asserts: \\\"asserts\\\",\\n },\\n properties: {\\n typeName: \\\"typeName\\\",\\n name: \\\"name\\\",\\n },\\n} as const;\\n\\nfunction isTypeGuard(node: TSESTree.Node) {\\n if (node.type === constants.nodeTypes.functionDeclaration && node.returnType?.typeAnnotation) {\\n const typeAnnotation = node.returnType.typeAnnotation;\\n\\n if (typeAnnotation.type === constants.nodeTypes.tsPredicateType) {\\n return true;\\n }\\n\\n if (\\n typeAnnotation.type === constants.nodeTypes.tsTypeReference &&\\n typeAnnotation.typeName.type === constants.nodeTypes.identifier &&\\n typeAnnotation.typeName.name === constants.typeNames.asserts\\n ) {\\n return true;\\n }\\n }\\n\\n return false;\\n}\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${constants.url}${ruleName}`);\\n\\nconst noSpecifyReturnType = createRule<[], typeof constants.messageIds.noSpecifyReturnType>({\\n name: constants.ruleName,\\n meta: {\\n type: constants.meta.type,\\n docs: {\\n description: constants.meta.docs.description,\\n },\\n messages: {\\n [constants.messageIds.noSpecifyReturnType]: constants.meta.messages.mustNotSpecifyReturnType,\\n },\\n schema: constants.meta.schema,\\n },\\n defaultOptions: [],\\n create(context: RuleContext<typeof constants.messageIds.noSpecifyReturnType, []>) {\\n const { sourceCode } = context;\\n\\n return {\\n [constants.nodeTypes.functionDeclaration](node: TSESTree.FunctionDeclaration) {\\n if (node.returnType && !isTypeGuard(node)) {\\n context.report({\\n node,\\n messageId: constants.messageIds.noSpecifyReturnType,\\n });\\n }\\n },\\n [constants.nodeTypes.methodDefinition](node: TSESTree.MethodDefinition) {\\n if (node.value.returnType) {\\n context.report({\\n node,\\n messageId: constants.messageIds.noSpecifyReturnType,\\n });\\n }\\n },\\n [constants.nodeTypes.arrowFunctionExpression](node: TSESTree.ArrowFunctionExpression) {\\n if (node.returnType) {\\n context.report({\\n node,\\n messageId: constants.messageIds.noSpecifyReturnType,\\n });\\n }\\n },\\n [constants.nodeTypes.functionExpression](node: TSESTree.FunctionExpression) {\\n if (node.returnType) {\\n const ancestors = sourceCode.getAncestors(node);\\n const parent = ancestors.length > 0 ? ancestors[ancestors.length - 1] : null;\\n\\n if (\\n parent &&\\n parent.type !== constants.nodeTypes.property &&\\n parent.type !== constants.nodeTypes.methodDefinition\\n ) {\\n context.report({\\n node,\\n messageId: constants.messageIds.noSpecifyReturnType,\\n });\\n }\\n }\\n },\\n [constants.nodeTypes.property](node: TSESTree.Property) {\\n if (\\n node.method &&\\n node.value.type === constants.nodeTypes.functionExpression &&\\n node.value.returnType\\n ) {\\n context.report({\\n node,\\n messageId: constants.messageIds.noSpecifyReturnType,\\n });\\n }\\n },\\n };\\n },\\n});\\n\\nexport default noSpecifyReturnType;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noSpecifyReturnType from \\\"@root/rules/no-specify-return-type\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `function foo(a: number, b: number) {\\n return a * b;\\n }`,\\n },\\n {\\n code: `const bar = (x: number) => x * x;`,\\n },\\n {\\n code: `class Foo1 {\\n baz() {\\n return { data: \\\"some data\\\" };\\n }\\n }`,\\n },\\n {\\n code: `function foo2(data: number[]) {\\n if (data.length === 0) {\\n return null;\\n }\\n return data.map(x => x * 2);\\n }`,\\n },\\n {\\n code: `const bar = {\\n foo3() {\\n return 5\\n }\\n }`,\\n },\\n {\\n code: `function foo4(value: any): value is string {\\n return typeof value === \\\"string\\\";\\n }`,\\n },\\n {\\n code: `function foo5(value: any): value is Error {\\n return value instanceof Error;\\n }`,\\n },\\n {\\n code: `function foo6(value: any): asserts value is string {\\n if (typeof value !== \\\"string\\\") {\\n throw new Error(\\\"Not a string!\\\");\\n }\\n }`,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `function foo7(): string {\\n return \\\"bar\\\";\\n }`,\\n errors: [{ messageId: \\\"noSpecifyReturnType\\\" }],\\n },\\n {\\n code: `function foo8(a: number, b: number): number {\\n return a + b;\\n }`,\\n errors: [{ messageId: \\\"noSpecifyReturnType\\\" }],\\n },\\n {\\n code: `function foo9(x: number, y: number): { x: number; y: number } {\\n return { x, y };\\n }`,\\n errors: [{ messageId: \\\"noSpecifyReturnType\\\" }],\\n },\\n {\\n code: `function foo10(): number[] {\\n return [1, 2, 3];\\n }`,\\n errors: [{ messageId: \\\"noSpecifyReturnType\\\" }],\\n },\\n {\\n code: `function foo11(message: string): void {\\n console.log(message);\\n }`,\\n errors: [{ messageId: \\\"noSpecifyReturnType\\\" }],\\n },\\n {\\n code: `function foo12(): any {\\n return \\\"something\\\";\\n }`,\\n errors: [{ messageId: \\\"noSpecifyReturnType\\\" }],\\n },\\n ],\\n};\\n\\nconst edgeCases = {\\n invalid: [\\n {\\n code: `function foo13<T>(arg: T): T {\\n return arg;\\n }`,\\n errors: [{ messageId: \\\"noSpecifyReturnType\\\" }],\\n },\\n {\\n code: `const bar2 = (name: string): string => {\\n return \\\\`Hello, \\\\${name}!\\\\`;\\n }`,\\n errors: [{ messageId: \\\"noSpecifyReturnType\\\" }],\\n },\\n {\\n code: `class Baz3 {\\n getValue(): number {\\n return 42;\\n }\\n }`,\\n errors: [{ messageId: \\\"noSpecifyReturnType\\\" }],\\n },\\n {\\n code: `const bar4 = {\\n method(): string {\\n return \\\"hello\\\";\\n }\\n }`,\\n errors: [{ messageId: \\\"noSpecifyReturnType\\\" }],\\n },\\n {\\n code: `type Quz = () => void;\\n const bar: Quz = function(): void {\\n console.log(\\\"handled\\\");\\n }`,\\n errors: [{ messageId: \\\"noSpecifyReturnType\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases, edgeCases];\\nrunTests(\\\"no-specify-return-type\\\", noSpecifyReturnType, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-string-length-check.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree, type ParserServices } from \\\"@typescript-eslint/utils\\\";\\nimport { RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\nimport ts from \\\"typescript\\\";\\n\\nconst AST = TSESTree.AST_NODE_TYPES;\\n\\nconst ruleConstants = {\\n type: \\\"problem\\\",\\n ruleName: \\\"no-string-length-check\\\",\\n description: \\\"Avoid using .length property for empty string checks.\\\",\\n message: \\\"Avoid using .length property for empty string checks.\\\",\\n messageId: \\\"noStringLength\\\",\\n baseUrl: \\\"https://example.com/rule/\\\",\\n lengthPropertyName: \\\"length\\\",\\n typeNumber: \\\"number\\\",\\n\\n comparisonOperators: {\\n zero: new Set([\\\"===\\\", \\\"!==\\\", \\\"==\\\", \\\"!=\\\", \\\">\\\", \\\"<=\\\", \\\"<\\\"]),\\n one: new Set([\\\">=\\\", \\\"<\\\"]),\\n forStatement: new Set([\\\"<\\\", \\\">\\\", \\\"<=\\\", \\\">=\\\"]),\\n },\\n validUsages: new Set([\\n AST.VariableDeclarator,\\n AST.CallExpression,\\n AST.MemberExpression,\\n AST.AssignmentExpression,\\n AST.UpdateExpression,\\n ]),\\n truthyCheckContexts: new Set([\\n AST.IfStatement,\\n AST.ConditionalExpression,\\n AST.LogicalExpression,\\n AST.UnaryExpression,\\n AST.ExpressionStatement,\\n AST.ReturnStatement,\\n AST.DoWhileStatement,\\n AST.WhileStatement,\\n AST.ForStatement,\\n AST.ChainExpression,\\n ]),\\n} as const;\\n\\ntype MessageIds = typeof ruleConstants.messageId;\\ntype Options = [];\\n\\ninterface Services {\\n checker: ts.TypeChecker;\\n tsNodeMap: ParserServices[\\\"esTreeNodeToTSNodeMap\\\"];\\n context: RuleContext<MessageIds, Options>;\\n}\\n\\nconst createRule = ESLintUtils.RuleCreator((name) => `${ruleConstants.baseUrl}${name}`);\\n\\nfunction isString(node: TSESTree.Expression, services: Services): boolean {\\n const tsNode = services.tsNodeMap.get(node);\\n const type = services.checker.getTypeAtLocation(tsNode);\\n return (type.getFlags() & ts.TypeFlags.StringLike) !== 0;\\n}\\n\\nfunction shouldReport(node: TSESTree.MemberExpression, services: Services): boolean {\\n return (\\n node.property.type === AST.Identifier &&\\n node.property.name === ruleConstants.lengthPropertyName &&\\n !node.computed &&\\n isString(node.object, services)\\n );\\n}\\n\\nfunction isLengthComparedToZero(node: TSESTree.MemberExpression): boolean {\\n const parent = node.parent;\\n\\n if (!parent || parent.type !== AST.BinaryExpression) return false;\\n\\n const { operator, left, right } = parent;\\n const otherSide = left === node ? right : left;\\n\\n if (otherSide.type !== AST.Literal || typeof otherSide.value !== ruleConstants.typeNumber) return false;\\n\\n const val = otherSide.value;\\n\\n return (\\n (val === 0 && ruleConstants.comparisonOperators.zero.has(operator)) ||\\n (val === 1 && ruleConstants.comparisonOperators.one.has(operator))\\n );\\n}\\n\\nfunction isValidUsage(node: TSESTree.MemberExpression): boolean {\\n const parent = node.parent;\\n\\n if (!parent) return false;\\n\\n if (ruleConstants.validUsages.has(parent.type)) {\\n if (parent.type === AST.VariableDeclarator) return parent.init === node;\\n\\n if (parent.type === AST.CallExpression) return parent.arguments.includes(node);\\n\\n if (parent.type === AST.MemberExpression) return parent.object === node;\\n\\n if (parent.type === AST.AssignmentExpression) return parent.right === node;\\n\\n return true;\\n }\\n\\n return (\\n parent.type === AST.BinaryExpression &&\\n ruleConstants.comparisonOperators.forStatement.has(parent.operator) &&\\n parent.parent?.type === AST.ForStatement\\n );\\n}\\n\\nconst noStringLengthCheck = createRule({\\n name: ruleConstants.ruleName,\\n meta: {\\n type: ruleConstants.type,\\n docs: { description: ruleConstants.description },\\n messages: { noStringLength: ruleConstants.message },\\n schema: [],\\n },\\n defaultOptions: [],\\n create(context: RuleContext<MessageIds, Options>) {\\n const parserServices = context.sourceCode.parserServices;\\n\\n if (!parserServices?.program || !parserServices.esTreeNodeToTSNodeMap) {\\n return {};\\n }\\n\\n const services: Services = {\\n checker: parserServices.program.getTypeChecker(),\\n tsNodeMap: parserServices.esTreeNodeToTSNodeMap,\\n context,\\n };\\n\\n return {\\n MemberExpression(node: TSESTree.MemberExpression) {\\n if (!shouldReport(node, services)) return;\\n\\n if (isValidUsage(node)) return;\\n\\n const parent = node.parent;\\n\\n if (!parent) return;\\n\\n if (isLengthComparedToZero(node) || ruleConstants.truthyCheckContexts.has(parent.type)) {\\n context.report({ node, messageId: ruleConstants.messageId });\\n }\\n },\\n };\\n },\\n});\\n\\nexport default noStringLengthCheck;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noStringLengthCheck from \\\"@root/rules/no-string-length-check\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: \\\"const foo = bar ? bar : baz;\\\",\\n },\\n {\\n code: \\\"const foo = bar ?? baz;\\\",\\n },\\n {\\n code: \\\"if (str) { console.log('not empty'); }\\\",\\n },\\n {\\n code: \\\"const result = str ? 'has value' : 'empty';\\\",\\n },\\n {\\n code: \\\"const hasValue = !!str;\\\",\\n },\\n {\\n code: \\\"const len = str.length;\\\",\\n },\\n {\\n code: \\\"const arr = [1, 2, 3]; if (arr.length) { console.log('has elements'); }\\\",\\n },\\n {\\n code: \\\"const arr = new Array(3); if (arr.length) { console.log('has elements'); }\\\",\\n },\\n {\\n code: \\\"const arr = []; if (arr.length) { console.log('has elements'); }\\\",\\n },\\n {\\n code: \\\"const arr = Array(3); if (arr.length) { console.log('has elements'); }\\\",\\n },\\n {\\n code: \\\"const arr = new Array(); if (arr.length) { console.log('has elements'); }\\\",\\n },\\n {\\n code: \\\"const arr = Array.from({ length: 3 }); if (arr.length) { console.log('has elements'); }\\\",\\n },\\n {\\n code: \\\"const arr = [...Array(3)]; if (arr.length) { console.log('has elements'); }\\\",\\n },\\n {\\n code: \\\"const arr = Array(3).fill(0); if (arr.length) { console.log('has elements'); }\\\",\\n },\\n {\\n code: \\\"const arr = new Array(3).fill(0); if (arr.length) { console.log('has elements'); }\\\",\\n },\\n {\\n code:\\n \\\"const arr = Array.from({ length: 3 }, (_, i) => i); \\\" +\\n \\\"if (arr.length) { console.log('has elements'); }\\\",\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: \\\"if (str.length) { console.log('not empty'); }\\\",\\n\\n errors: [{ messageId: \\\"noStringLength\\\" }],\\n },\\n {\\n code: \\\"if (str.length === 0) { console.log('empty'); }\\\",\\n\\n errors: [{ messageId: \\\"noStringLength\\\" }],\\n },\\n {\\n code: \\\"if (str.length !== 0) { console.log('not empty'); }\\\",\\n\\n errors: [{ messageId: \\\"noStringLength\\\" }],\\n },\\n {\\n code: \\\"if (str.length == 0) { console.log('empty'); }\\\",\\n\\n errors: [{ messageId: \\\"noStringLength\\\" }],\\n },\\n {\\n code: \\\"if (str.length != 0) { console.log('not empty'); }\\\",\\n\\n errors: [{ messageId: \\\"noStringLength\\\" }],\\n },\\n {\\n code: \\\"if (str.length > 0) { console.log('not empty'); }\\\",\\n\\n errors: [{ messageId: \\\"noStringLength\\\" }],\\n },\\n {\\n code: \\\"if (str.length < 1) { console.log('empty'); }\\\",\\n\\n errors: [{ messageId: \\\"noStringLength\\\" }],\\n },\\n {\\n code: \\\"if (str.length >= 1) { console.log('not empty'); }\\\",\\n\\n errors: [{ messageId: \\\"noStringLength\\\" }],\\n },\\n {\\n code: \\\"const result = str.length ? 'has value' : 'empty';\\\",\\n\\n errors: [{ messageId: \\\"noStringLength\\\" }],\\n },\\n {\\n code: \\\"const hasValue = !!str.length;\\\",\\n errors: [{ messageId: \\\"noStringLength\\\" }],\\n },\\n {\\n code: \\\"return str.length;\\\",\\n errors: [{ messageId: \\\"noStringLength\\\" }],\\n },\\n {\\n code: \\\"while (str.length) { break; }\\\",\\n errors: [{ messageId: \\\"noStringLength\\\" }],\\n },\\n {\\n code: \\\"do { break; } while (str.length);\\\",\\n errors: [{ messageId: \\\"noStringLength\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"no-string-length-check\\\", noStringLengthCheck, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-tailwind-colors.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree } from \\\"@typescript-eslint/utils\\\";\\nimport { type RuleContext } from \\\"@typescript-eslint/utils/ts-eslint\\\";\\n\\nconst constants = {\\n url: \\\"https://example.com/rules/\\\",\\n ruleName: \\\"no-tailwind-colors\\\",\\n messageIds: {\\n noTailwindColors: \\\"noTailwindColors\\\",\\n },\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Disallow the direct use of Tailwind CSS color utility classes.\\\",\\n },\\n messages: {\\n noTailwindColors: \\\"Do not use Tailwind color class '{{colorClass}}'.\\\",\\n },\\n schema: [],\\n },\\n nodeTypes: {\\n jsxIdentifier: \\\"JSXIdentifier\\\",\\n literal: \\\"Literal\\\",\\n templateLiteral: \\\"TemplateLiteral\\\",\\n callExpression: \\\"CallExpression\\\",\\n identifier: \\\"Identifier\\\",\\n logicalExpression: \\\"LogicalExpression\\\",\\n jsxExpressionContainer: \\\"JSXExpressionContainer\\\",\\n },\\n nodeKeys: {\\n value: \\\"value\\\",\\n name: \\\"name\\\",\\n raw: \\\"raw\\\",\\n quasis: \\\"quasis\\\",\\n right: \\\"right\\\",\\n callee: \\\"callee\\\",\\n arguments: \\\"arguments\\\",\\n expression: \\\"expression\\\",\\n },\\n dataKeys: {\\n colorClass: \\\"colorClass\\\",\\n },\\n types: {\\n string: \\\"string\\\",\\n },\\n separators: {\\n empty: \\\"\\\",\\n dash: \\\"-\\\",\\n },\\n functionNames: {\\n cn: \\\"cn\\\",\\n },\\n flags: {\\n global: \\\"g\\\",\\n },\\n attributeNames: [\\\"className\\\", \\\"class\\\"],\\n regexParts: {\\n prefixes: \\\"(text|bg|border)\\\",\\n colors: \\\"(red|blue|green|yellow|indigo|purple|pink|gray|stone|amber|lime|emerald|teal|cyan|sky|orange)\\\",\\n numbers: \\\"(50|100|200|300|400|500|600|700|800|900|950)\\\",\\n },\\n} as const;\\n\\nconst tailwindColorRegex = new RegExp(\\n \\\"\\\\\\\\b\\\" +\\n [constants.regexParts.prefixes, constants.regexParts.colors, constants.regexParts.numbers].join(\\n constants.separators.dash,\\n ) +\\n \\\"\\\\\\\\b\\\",\\n constants.flags.global,\\n);\\n\\ntype MessageIds = typeof constants.messageIds.noTailwindColors;\\ntype RuleOptions = [];\\ninterface Services {\\n context: RuleContext<MessageIds, RuleOptions>;\\n processedCnCalls: Set<TSESTree.CallExpression>;\\n}\\n\\nfunction isStringLiteral(\\n node: TSESTree.Node | TSESTree.JSXChild,\\n): node is TSESTree.Literal & { value: string } {\\n return (\\n node.type === constants.nodeTypes.literal &&\\n typeof node[constants.nodeKeys.value] === constants.types.string\\n );\\n}\\n\\nfunction extractColorClasses(value: string) {\\n const matches = new Set<string>();\\n tailwindColorRegex.lastIndex = 0;\\n let match;\\n while ((match = tailwindColorRegex.exec(value)) !== null) {\\n matches.add(match[0]);\\n }\\n return matches;\\n}\\n\\nfunction reportColorClasses(colorClasses: Set<string>, node: TSESTree.Node, services: Services) {\\n if (colorClasses.size === 0) return;\\n\\n colorClasses.forEach((colorClass) => {\\n services.context.report({\\n node,\\n messageId: constants.messageIds.noTailwindColors,\\n data: { [constants.dataKeys.colorClass]: colorClass },\\n });\\n });\\n}\\n\\nfunction checkAndReport(value: string, node: TSESTree.Node, services: Services) {\\n const colorClasses = extractColorClasses(value);\\n reportColorClasses(colorClasses, node, services);\\n}\\n\\nfunction processCnArgument(arg: TSESTree.CallExpressionArgument, services: Services) {\\n if (isStringLiteral(arg)) {\\n checkAndReport(arg[constants.nodeKeys.value], arg, services);\\n } else if (arg.type === constants.nodeTypes.templateLiteral) {\\n const templateText = arg[constants.nodeKeys.quasis]\\n .map((q) => q[constants.nodeKeys.value][constants.nodeKeys.raw])\\n .join(constants.separators.empty);\\n checkAndReport(templateText, arg, services);\\n } else if (arg.type === constants.nodeTypes.logicalExpression) {\\n const rightNode = arg[constants.nodeKeys.right];\\n\\n if (isStringLiteral(rightNode)) {\\n checkAndReport(rightNode[constants.nodeKeys.value], rightNode, services);\\n }\\n }\\n}\\n\\nfunction processCnFunctionCall(node: TSESTree.CallExpression, services: Services) {\\n if (services.processedCnCalls.has(node)) {\\n return;\\n }\\n\\n const callee = node[constants.nodeKeys.callee];\\n\\n if (\\n callee.type !== constants.nodeTypes.identifier ||\\n callee[constants.nodeKeys.name] !== constants.functionNames.cn\\n ) {\\n return;\\n }\\n\\n services.processedCnCalls.add(node);\\n node[constants.nodeKeys.arguments].forEach((arg) => processCnArgument(arg, services));\\n}\\n\\nfunction processAttributeValue(\\n value: TSESTree.JSXAttribute[typeof constants.nodeKeys.value],\\n services: Services,\\n) {\\n if (!value) return;\\n\\n if (isStringLiteral(value)) {\\n checkAndReport(value[constants.nodeKeys.value], value, services);\\n return;\\n }\\n\\n if (value.type === constants.nodeTypes.jsxExpressionContainer) {\\n const expression = value[constants.nodeKeys.expression];\\n\\n if (isStringLiteral(expression)) {\\n checkAndReport(expression[constants.nodeKeys.value], expression, services);\\n } else if (expression.type === constants.nodeTypes.templateLiteral) {\\n const templateText = expression[constants.nodeKeys.quasis]\\n .map((q) => q[constants.nodeKeys.value][constants.nodeKeys.raw])\\n .join(constants.separators.empty);\\n checkAndReport(templateText, expression, services);\\n } else if (expression.type === constants.nodeTypes.callExpression) {\\n processCnFunctionCall(expression, services);\\n }\\n }\\n}\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${constants.url}${ruleName}`);\\n\\nconst noTailwindColors = createRule<RuleOptions, MessageIds>({\\n name: constants.ruleName,\\n meta: constants.meta,\\n defaultOptions: [],\\n create(context) {\\n const services: Services = {\\n context,\\n processedCnCalls: new Set(),\\n };\\n\\n return {\\n JSXAttribute(node: TSESTree.JSXAttribute) {\\n const nameNode = node[constants.nodeKeys.name];\\n\\n if (\\n nameNode.type === constants.nodeTypes.jsxIdentifier &&\\n constants.attributeNames.some(\\n (attrName) => attrName === nameNode[constants.nodeKeys.name],\\n )\\n ) {\\n processAttributeValue(node[constants.nodeKeys.value], services);\\n }\\n },\\n CallExpression(node: TSESTree.CallExpression) {\\n processCnFunctionCall(node, services);\\n },\\n };\\n },\\n});\\n\\nexport default noTailwindColors;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noTailwindColors from \\\"@root/rules/no-tailwind-colors\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `<div className=\\\"my-custom-class\\\">Valid</div>`,\\n },\\n {\\n code: `<div className={foo}>Valid</div>`,\\n },\\n {\\n code: `<div className={cn(\\\"my-class\\\", bar)}>Valid</div>`,\\n },\\n {\\n code: `<div className=\\\"flex items-center\\\">Valid</div>`,\\n },\\n {\\n code: `<div className=\\\"flex justify-between p-4 rounded-md\\\">Valid</div>`,\\n },\\n {\\n code: `<div class=\\\"container mx-auto\\\">Valid</div>`,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `<div className=\\\"text-red-500\\\">Hello</div>`,\\n errors: [{ messageId: \\\"noTailwindColors\\\", data: { colorClass: \\\"text-red-500\\\" } }],\\n },\\n {\\n code: `<div className=\\\"bg-blue-200 text-gray-800\\\">World</div>`,\\n errors: [\\n { messageId: \\\"noTailwindColors\\\", data: { colorClass: \\\"bg-blue-200\\\" } },\\n { messageId: \\\"noTailwindColors\\\", data: { colorClass: \\\"text-gray-800\\\" } },\\n ],\\n },\\n {\\n code: `<div className={\\\\`text-green-600 \\\\${foo}\\\\`}>Dynamic</div>`,\\n errors: [{ messageId: \\\"noTailwindColors\\\", data: { colorClass: \\\"text-green-600\\\" } }],\\n },\\n {\\n code: `<div className={cn(\\\"text-yellow-400\\\", baz && \\\"bg-indigo-700\\\")}>Conditional</div>`,\\n errors: [\\n { messageId: \\\"noTailwindColors\\\", data: { colorClass: \\\"text-yellow-400\\\" } },\\n { messageId: \\\"noTailwindColors\\\", data: { colorClass: \\\"bg-indigo-700\\\" } },\\n ],\\n },\\n ],\\n};\\n\\nconst edgeCases = {\\n invalid: [\\n {\\n code: `<div className=\\\"bg-sky-100\\\">Invalid</div>`,\\n errors: [{ messageId: \\\"noTailwindColors\\\", data: { colorClass: \\\"bg-sky-100\\\" } }],\\n },\\n {\\n code: `<div className=\\\"text-red-500 text-red-500\\\">Duplicate</div>`,\\n errors: [{ messageId: \\\"noTailwindColors\\\", data: { colorClass: \\\"text-red-500\\\" } }],\\n },\\n {\\n code: `<div class={cn(\\\"border-purple-300\\\", \\\"p-4\\\")}>Invalid</div>`,\\n errors: [{ messageId: \\\"noTailwindColors\\\", data: { colorClass: \\\"border-purple-300\\\" } }],\\n },\\n {\\n code: `<div className=\\\"flex items-center text-cyan-200\\\">Mixed</div>`,\\n errors: [{ messageId: \\\"noTailwindColors\\\", data: { colorClass: \\\"text-cyan-200\\\" } }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases, edgeCases];\\nrunTests(\\\"no-tailwind-colors\\\", noTailwindColors, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-then.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 noThen = createRule({\\n name: \\\"no-then\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Enforce async/await instead of .then()\\\",\\n },\\n messages: {\\n useAsyncAwait: \\\"Use async/await instead of .then()\\\",\\n },\\n schema: [],\\n },\\n create(context: RuleContext<\\\"useAsyncAwait\\\", []>) {\\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 === \\\"then\\\"\\n ) {\\n context.report({\\n node,\\n messageId: \\\"useAsyncAwait\\\",\\n });\\n }\\n },\\n };\\n },\\n defaultOptions: [],\\n});\\n\\nexport default noThen;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noThen from \\\"@root/rules/no-then\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n async function loadData() { \\n const res = await fetch(\\\"/api/data\\\");\\n const json = res.json();\\n }\\n `,\\n },\\n {\\n code: `\\n const result = doSomething();\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n fetch(\\\"/api/data\\\").then(res => res.json());\\n `,\\n errors: [{ messageId: \\\"useAsyncAwait\\\" }],\\n },\\n {\\n code: `\\n someAsyncCall().then(result => { \\n console.log(result);\\n });\\n `,\\n errors: [{ messageId: \\\"useAsyncAwait\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"no-then\\\", noThen, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-to-lower-case-with-resource-name.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 nodeTypeIdentifiers = {\\n callExpression: \\\"CallExpression\\\",\\n identifier: \\\"Identifier\\\",\\n resourceId: \\\"resourceId\\\",\\n} as const;\\n\\nconst noToLowerCaseWithResourceName = createRule({\\n name: \\\"no-to-lower-case-with-resource-name\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Cannot use toLowerCase() with resourceName\\\",\\n },\\n messages: {\\n noToLowerCase: \\\"Cannot use toLowerCase() with resourceName\\\",\\n },\\n schema: [],\\n },\\n create(context: RuleContext<\\\"noToLowerCase\\\", []>) {\\n return {\\n ClassDeclaration(node: TSESTree.ClassDeclaration) {\\n const decorators = node.decorators;\\n\\n if (!decorators) return;\\n\\n const hasResourceIdDecorator = decorators.some((decorator) => {\\n if (decorator.expression.type === nodeTypeIdentifiers.callExpression) {\\n const callee = decorator.expression.callee;\\n return (\\n callee.type === nodeTypeIdentifiers.identifier &&\\n callee.name === nodeTypeIdentifiers.resourceId\\n );\\n }\\n\\n return false;\\n });\\n\\n if (hasResourceIdDecorator && node.id) {\\n const className = node.id.name;\\n const isPascalCase = /^[A-Z][a-zA-Z0-9]*$/.test(className);\\n\\n if (!isPascalCase) {\\n context.report({\\n node,\\n messageId: \\\"noToLowerCase\\\",\\n });\\n }\\n }\\n },\\n };\\n },\\n defaultOptions: [],\\n});\\n\\nexport default noToLowerCaseWithResourceName;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noToLowerCaseWithResourceName from \\\"@root/rules/no-to-lower-case-with-resource-name\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n @resourceId(resourceIds.user)\\n class User extends BaseResource {\\n id!: number;\\n email!: string;\\n }`,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n @resourceId(resourceIds.user)\\n class user extends BaseResource {\\n id!: number;\\n email!: string;\\n }`,\\n errors: [{ messageId: \\\"noToLowerCase\\\" }],\\n },\\n ],\\n};\\n\\nconst edgeCases = {\\n valid: [\\n {\\n code: `\\n class AnotherClass {\\n description!: string;\\n }`,\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases, edgeCases];\\nrunTests(\\\"no-toLowerCase-with-resourceName\\\", noToLowerCaseWithResourceName, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-todo.ts' and a test for it.\",\"rule_code\":\"import { 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 NoTodo = createRule({\\n name: \\\"no-todo\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Disallow todo fd comments\\\",\\n },\\n messages: {\\n NoTodo: \\\"Todo fd comments are not allowed\\\",\\n },\\n schema: [],\\n },\\n create(context: RuleContext<\\\"NoTodo\\\", []>) {\\n return {\\n Program() {\\n const comments = context.sourceCode.getAllComments();\\n comments.forEach((comment) => {\\n const value = comment.value.trim();\\n\\n if (/^todo\\\\s+fd\\\\b/i.test(value)) {\\n context.report({\\n loc: comment.loc,\\n messageId: \\\"NoTodo\\\",\\n });\\n }\\n });\\n },\\n };\\n },\\n defaultOptions: [],\\n});\\n\\nexport default NoTodo;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport NoTodo from \\\"@root/rules/no-todo\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n //comment\\n function example2() {\\n return 42;\\n }\\n `,\\n },\\n {\\n code: `\\n function example2() {\\n return 42;\\n }\\n `,\\n },\\n {\\n code: `\\n //todofd\\n function example2() {\\n return 42;\\n }\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n //todo fd: fix this\\n function example() {\\n return 42;\\n }\\n `,\\n errors: [{ messageId: \\\"NoTodo\\\" }],\\n },\\n {\\n code: `\\n //TODO FD: fix this\\n function example() {\\n return 42;\\n }\\n `,\\n errors: [{ messageId: \\\"NoTodo\\\" }],\\n },\\n {\\n code: `\\n //TODO fd\\n function example() {\\n return 42;\\n }\\n `,\\n errors: [{ messageId: \\\"NoTodo\\\" }],\\n },\\n {\\n code: `\\n //todo FD\\n function example() {\\n return 42;\\n }\\n `,\\n errors: [{ messageId: \\\"NoTodo\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"no-todo\\\", NoTodo, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-untyped-objects-between-components.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESLint, 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: \\\"no-untyped-objects-between-components\\\",\\n messageIds: {\\n noUntypedObjects: \\\"noUntypedObjects\\\",\\n },\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Must not pass untyped objects between components\\\",\\n },\\n messages: {\\n noUntypedObjects:\\n \\\"Must not pass untyped objects between components. Define proper TypeScript interfaces or types.\\\",\\n },\\n schema: [],\\n },\\n nodeTypes: {\\n jsxElement: AST_NODE_TYPES.JSXElement,\\n jsxOpeningElement: AST_NODE_TYPES.JSXOpeningElement,\\n jsxAttribute: AST_NODE_TYPES.JSXAttribute,\\n jsxExpressionContainer: AST_NODE_TYPES.JSXExpressionContainer,\\n objectExpression: AST_NODE_TYPES.ObjectExpression,\\n identifier: AST_NODE_TYPES.Identifier,\\n jsxIdentifier: AST_NODE_TYPES.JSXIdentifier,\\n callExpression: AST_NODE_TYPES.CallExpression,\\n memberExpression: AST_NODE_TYPES.MemberExpression,\\n arrowFunctionExpression: AST_NODE_TYPES.ArrowFunctionExpression,\\n functionExpression: AST_NODE_TYPES.FunctionExpression,\\n tsTypeReference: AST_NODE_TYPES.TSTypeReference,\\n tsAnyKeyword: AST_NODE_TYPES.TSAnyKeyword,\\n tsObjectKeyword: AST_NODE_TYPES.TSObjectKeyword,\\n functionDeclaration: AST_NODE_TYPES.FunctionDeclaration,\\n variableDeclarator: AST_NODE_TYPES.VariableDeclarator,\\n },\\n componentPatterns: {\\n componentNameRegex: /^[A-Z][a-zA-Z0-9]*$/,\\n reactHookPrefix: \\\"use\\\",\\n },\\n typeAnnotations: {\\n any: \\\"any\\\",\\n object: \\\"object\\\",\\n },\\n definitionTypes: {\\n variable: \\\"Variable\\\",\\n parameter: \\\"Parameter\\\",\\n functionName: \\\"FunctionName\\\",\\n },\\n nodeProperties: {\\n typeAnnotation: \\\"typeAnnotation\\\",\\n typeName: \\\"typeName\\\",\\n },\\n} as const;\\n\\nconst createRule = ESLintUtils.RuleCreator((ruleName: string) => `${constants.url}${ruleName}`);\\n\\nfunction isComponentName(name: string) {\\n return constants.componentPatterns.componentNameRegex.test(name);\\n}\\n\\nfunction isReactHook(name: string) {\\n return name.startsWith(constants.componentPatterns.reactHookPrefix);\\n}\\n\\nfunction isUntypedObjectExpression(node: TSESTree.Node): boolean {\\n return node.type === constants.nodeTypes.objectExpression;\\n}\\n\\nfunction isVariableDeclaratorUntypedObject(defNode: TSESTree.VariableDeclarator): boolean {\\n if (defNode.type !== constants.nodeTypes.variableDeclarator) return false;\\n\\n const declarator = defNode;\\n\\n if (!declarator.init) return false;\\n\\n if (declarator.init.type !== constants.nodeTypes.objectExpression) return false;\\n\\n if (!declarator.id.typeAnnotation) return true;\\n\\n const typeAnnotation = declarator.id.typeAnnotation.typeAnnotation;\\n\\n if (typeAnnotation.type === constants.nodeTypes.tsAnyKeyword) return true;\\n\\n if (typeAnnotation.type === constants.nodeTypes.tsObjectKeyword) return true;\\n\\n if (\\n typeAnnotation.type === constants.nodeTypes.tsTypeReference &&\\n constants.nodeProperties.typeName in typeAnnotation &&\\n typeAnnotation.typeName.type === constants.nodeTypes.identifier\\n ) {\\n const typeName = typeAnnotation.typeName.name;\\n\\n if (typeName === constants.typeAnnotations.any || typeName === constants.typeAnnotations.object) {\\n return true;\\n }\\n }\\n\\n return false;\\n}\\n\\nfunction findVariableInScope(name: string, scope: TSESLint.Scope.Scope): TSESLint.Scope.Variable | undefined {\\n let variable = scope.variables.find((v) => v.name === name);\\n let currentScope = scope;\\n while (!variable && currentScope.upper) {\\n currentScope = currentScope.upper;\\n variable = currentScope.variables.find((v) => v.name === name);\\n }\\n return variable;\\n}\\n\\nfunction isUntypedFunctionDeclarator(defNode: TSESTree.VariableDeclarator): boolean {\\n if (defNode.type !== constants.nodeTypes.variableDeclarator || !defNode.init) {\\n return false;\\n }\\n\\n const init = defNode.init;\\n\\n return (\\n (init.type === constants.nodeTypes.arrowFunctionExpression ||\\n init.type === constants.nodeTypes.functionExpression) &&\\n !init.returnType\\n );\\n}\\n\\nfunction isVariableUntypedFunction(variable: TSESLint.Scope.Variable): boolean {\\n const definition = variable.defs[0];\\n\\n if (!definition) return false;\\n\\n if (definition.type === constants.definitionTypes.functionName) {\\n const functionNode = definition.node;\\n return functionNode.type === constants.nodeTypes.functionDeclaration && !functionNode.returnType;\\n }\\n\\n if (definition.type === constants.definitionTypes.variable) {\\n const defNode = definition.node;\\n return isUntypedFunctionDeclarator(defNode);\\n }\\n\\n return false;\\n}\\n\\nfunction isIdentifierWithoutProperType(\\n node: TSESTree.Node,\\n sourceCode: Readonly<TSESLint.SourceCode>,\\n): boolean {\\n if (node.type !== constants.nodeTypes.identifier) {\\n return false;\\n }\\n\\n const identifierNode = node;\\n const scope = sourceCode.getScope(node);\\n\\n let variable = scope.variables.find((v: TSESLint.Scope.Variable) => v.name === identifierNode.name);\\n let currentScope = scope;\\n\\n while (!variable && currentScope.upper) {\\n currentScope = currentScope.upper;\\n variable = currentScope.variables.find(\\n (v: TSESLint.Scope.Variable) => v.name === identifierNode.name,\\n );\\n }\\n\\n if (!variable || variable.defs.length === 0) {\\n return false;\\n }\\n\\n const definition = variable.defs[0];\\n\\n if (!definition) {\\n return false;\\n }\\n\\n if (definition.type === constants.definitionTypes.variable) {\\n return isVariableDeclaratorUntypedObject(definition.node);\\n }\\n\\n return false;\\n}\\n\\nfunction isCallExpressionReturningObject(node: TSESTree.Node, sourceCode: Readonly<TSESLint.SourceCode>) {\\n if (node.type !== constants.nodeTypes.callExpression) {\\n return false;\\n }\\n\\n const callExpression = node;\\n const callee = callExpression.callee;\\n\\n if (callee.type === constants.nodeTypes.identifier) {\\n if (isReactHook(callee.name)) return true;\\n\\n const scope = sourceCode.getScope(node);\\n const variable = findVariableInScope(callee.name, scope);\\n\\n if (variable && isVariableUntypedFunction(variable)) return true;\\n }\\n\\n if (callee.type === constants.nodeTypes.memberExpression) {\\n const property = callee.property;\\n\\n if (property.type === constants.nodeTypes.identifier) {\\n return isReactHook(property.name);\\n }\\n }\\n\\n return false;\\n}\\n\\nconst noUntypedObjectsBetweenComponents = createRule<[], typeof constants.messageIds.noUntypedObjects>({\\n name: constants.ruleName,\\n meta: constants.meta,\\n defaultOptions: [],\\n\\n create(context: RuleContext<typeof constants.messageIds.noUntypedObjects, []>) {\\n const { sourceCode } = context;\\n\\n function checkJSXAttribute(node: TSESTree.JSXAttribute) {\\n if (\\n node.name.type !== constants.nodeTypes.jsxIdentifier ||\\n !node.value ||\\n node.value.type !== constants.nodeTypes.jsxExpressionContainer\\n ) {\\n return;\\n }\\n\\n const expression = node.value.expression;\\n\\n if (!expression || expression.type === AST_NODE_TYPES.JSXEmptyExpression) {\\n return;\\n }\\n\\n const shouldReport =\\n isUntypedObjectExpression(expression) ||\\n isIdentifierWithoutProperType(expression, sourceCode) ||\\n isCallExpressionReturningObject(expression, sourceCode);\\n\\n if (shouldReport) {\\n context.report({\\n node: expression,\\n messageId: constants.messageIds.noUntypedObjects,\\n });\\n }\\n }\\n\\n function checkJSXOpeningElement(openingElement: TSESTree.JSXOpeningElement) {\\n if (openingElement.name.type !== constants.nodeTypes.jsxIdentifier) {\\n return;\\n }\\n\\n const componentName = openingElement.name.name;\\n\\n if (!isComponentName(componentName)) {\\n return;\\n }\\n\\n openingElement.attributes.forEach((attr: TSESTree.JSXAttribute | TSESTree.JSXSpreadAttribute) => {\\n if (attr.type === constants.nodeTypes.jsxAttribute) {\\n checkJSXAttribute(attr);\\n }\\n });\\n }\\n\\n return {\\n [constants.nodeTypes.jsxElement](node: TSESTree.JSXElement) {\\n checkJSXOpeningElement(node.openingElement);\\n },\\n };\\n },\\n});\\n\\nexport default noUntypedObjectsBetweenComponents;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noUntypedObjectsBetweenComponents from \\\"@root/rules/no-untyped-objects-between-components\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n interface FooProps {\\n bar: string;\\n baz: number;\\n }\\n \\n const foo: FooProps = { bar: \\\"test\\\", baz: 42 };\\n <FooComponent foo={foo} />\\n `,\\n },\\n {\\n code: `\\n type BarData = {\\n id: string;\\n title: string;\\n };\\n \\n const bar: BarData = { id: \\\"1\\\", title: \\\"test\\\" };\\n <BarItem data={bar} />\\n `,\\n },\\n {\\n code: `\\n interface BazConfig {\\n theme: string;\\n locale: string;\\n }\\n \\n function getBaz(): BazConfig {\\n return { theme: \\\"dark\\\", locale: \\\"en\\\" };\\n }\\n \\n <BazSettings config={getBaz()} />\\n `,\\n },\\n {\\n code: `\\n <div className=\\\"container\\\">\\n <span>Hello World</span>\\n </div>\\n `,\\n },\\n {\\n code: `\\n const foo = \\\"test\\\";\\n <FooCard name={foo} />\\n `,\\n },\\n {\\n code: `\\n const bar = true;\\n <BarModal visible={bar} />\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n const foo = { bar: \\\"test\\\", baz: 42 };\\n <FooCard foo={foo} />\\n `,\\n errors: [{ messageId: \\\"noUntypedObjects\\\" }],\\n },\\n {\\n code: `\\n <BarItem data={{ id: \\\"1\\\", title: \\\"test\\\" }} />\\n `,\\n errors: [{ messageId: \\\"noUntypedObjects\\\" }],\\n },\\n {\\n code: `\\n function getBaz() {\\n return { theme: \\\"dark\\\", locale: \\\"en\\\" };\\n }\\n \\n <BazSettings config={getBaz()} />\\n `,\\n errors: [{ messageId: \\\"noUntypedObjects\\\" }],\\n },\\n {\\n code: `\\n const foo: any = { theme: \\\"dark\\\" };\\n <FooSettings config={foo} />\\n `,\\n errors: [{ messageId: \\\"noUntypedObjects\\\" }],\\n },\\n {\\n code: `\\n const bar: object = { value: 42 };\\n <BarComponent data={bar} />\\n `,\\n errors: [{ messageId: \\\"noUntypedObjects\\\" }],\\n },\\n ],\\n};\\n\\nconst hookCases = {\\n invalid: [\\n {\\n code: `\\n <FooForm data={useFooData()} />\\n `,\\n errors: [{ messageId: \\\"noUntypedObjects\\\" }],\\n },\\n {\\n code: `\\n <BarSettings config={useBarConfig()} />\\n `,\\n errors: [{ messageId: \\\"noUntypedObjects\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases, hookCases];\\nrunTests(\\\"no-untyped-objects-between-components\\\", noUntypedObjectsBetweenComponents, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-use-id.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 checkParams(params: TSESTree.Parameter[], context: RuleContext<\\\"noIdParam\\\", []>) {\\n for (const param of params) {\\n if (param.type === \\\"Identifier\\\" && param.name === \\\"id\\\") {\\n context.report({\\n node: param,\\n messageId: \\\"noIdParam\\\",\\n });\\n }\\n\\n if (\\n param.type === \\\"AssignmentPattern\\\" &&\\n param.left.type === \\\"Identifier\\\" &&\\n param.left.name === \\\"id\\\"\\n ) {\\n context.report({\\n node: param.left,\\n messageId: \\\"noIdParam\\\",\\n });\\n }\\n }\\n}\\n\\nconst notUseIdParam = createRule({\\n name: \\\"no-use-id\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Disallow using id as a parameter name in functions\\\",\\n },\\n messages: {\\n noIdParam: \\\"Do not use id as parameter name in functions\\\",\\n },\\n schema: [],\\n },\\n create(context: RuleContext<\\\"noIdParam\\\", []>) {\\n return {\\n FunctionDeclaration(node: TSESTree.FunctionDeclaration) {\\n checkParams(node.params, context);\\n },\\n FunctionExpression(node: TSESTree.FunctionExpression) {\\n checkParams(node.params, context);\\n },\\n ArrowFunctionExpression(node: TSESTree.ArrowFunctionExpression) {\\n checkParams(node.params, context);\\n },\\n };\\n },\\n defaultOptions: [],\\n});\\n\\nexport default notUseIdParam;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport notUseIdParam from \\\"@root/rules/no-use-id\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `\\n function destructuredFunction({ id, name }) {\\n console.log(id, name);\\n }\\n `,\\n },\\n {\\n code: `\\n function anotherParameter(userId) {\\n console.log(userId);\\n }\\n `,\\n },\\n {\\n code: `\\n function nestedDestructuring({ user: { id, name } }) {\\n console.log(id, name);\\n }\\n `,\\n },\\n {\\n code: `\\n function withDefault(userId = 1) {\\n console.log(userId);\\n }\\n `,\\n },\\n {\\n code: `\\n function noParams() {\\n console.log(\\\"ok\\\");\\n }\\n `,\\n },\\n {\\n code: `\\n function restParams(...args) {\\n console.log(args);\\n }\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `\\n function exampleFunction(id) {\\n console.log(id);\\n }\\n `,\\n errors: [{ messageId: \\\"noIdParam\\\" }],\\n },\\n {\\n code: `\\n const exampleArrowFunction = (id) => {\\n console.log(id);\\n };\\n `,\\n errors: [{ messageId: \\\"noIdParam\\\" }],\\n },\\n {\\n code: `\\n const myFunc = function(id) {\\n return id;\\n };\\n `,\\n errors: [{ messageId: \\\"noIdParam\\\" }],\\n },\\n {\\n code: `\\n function withDefaultId(id = 0) {\\n return id;\\n }\\n `,\\n errors: [{ messageId: \\\"noIdParam\\\" }],\\n },\\n {\\n code: `\\n function manyParams(id, name) {\\n return name;\\n }\\n `,\\n errors: [{ messageId: \\\"noIdParam\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"no-use-id\\\", notUseIdParam, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-use-type-undefined-for-optional.ts' and a test for it.\",\"rule_code\":\"import { ESLintUtils, TSESTree } from \\\"@typescript-eslint/utils\\\";\\ntype UnionTypeNode = TSESTree.TSUnionType;\\n\\nconst ruleConstants = {\\n ruleName: \\\"no-use-type-undefined-for-optional\\\",\\n urlBase: \\\"https://example.com/rules/\\\",\\n description:\\n \\\"Disallow usage of `undefined` | `null` in parameter types. Use optional parameters instead.\\\",\\n errorMessage:\\n \\\"Parameter '{{paramName}}' must not use `undefined` or `null` in its type.\\\" +\\n \\\" Use optional parameter syntax (`param?: Type`) instead.\\\",\\n messageId: \\\"noUseUndefinedForOptional\\\",\\n nodeTypes: {\\n identifier: \\\"Identifier\\\",\\n typeTSTypeAnnotation: \\\"TSTypeAnnotation\\\",\\n typeTSUnionType: \\\"TSUnionType\\\",\\n typeUndefined: \\\"TSUndefinedKeyword\\\",\\n typeNull: \\\"TSNullKeyword\\\",\\n typeTSFunction: \\\"TSFunctionType\\\",\\n },\\n} as const;\\n\\nfunction checkFunctionParams(\\n params: TSESTree.Parameter[],\\n checkTypeAnnotation: (param: TSESTree.Identifier, unionTypes: TSESTree.TSUnionType) => void,\\n) {\\n for (const param of params) {\\n if (param.type === ruleConstants.nodeTypes.identifier) {\\n const typeAnnotation = param.typeAnnotation;\\n\\n if (!(!typeAnnotation || typeAnnotation.type !== ruleConstants.nodeTypes.typeTSTypeAnnotation)) {\\n const unionType = typeAnnotation.typeAnnotation;\\n\\n if (unionType.type === ruleConstants.nodeTypes.typeTSUnionType) {\\n checkTypeAnnotation(param, unionType);\\n }\\n }\\n }\\n }\\n}\\n\\nfunction createAutoFix(\\n context: Readonly<import(\\\"@typescript-eslint/utils\\\").TSESLint.RuleContext<string, unknown[]>>,\\n fixer: import(\\\"@typescript-eslint/utils\\\").TSESLint.RuleFixer,\\n param: TSESTree.Identifier,\\n unionTypes: TSESTree.TSUnionType,\\n): import(\\\"@typescript-eslint/utils\\\").TSESLint.RuleFix | null {\\n const sourceCode = context.sourceCode;\\n\\n const typesWithoutUndefined = unionTypes.types.filter(\\n (type) => type.type !== ruleConstants.nodeTypes.typeUndefined,\\n );\\n\\n if (typesWithoutUndefined.length === 0) {\\n return null;\\n }\\n\\n let typeText: string;\\n\\n if (typesWithoutUndefined.length === 1) {\\n typeText = sourceCode.getText(typesWithoutUndefined[0]);\\n } else {\\n const typeTexts = typesWithoutUndefined.map((type) => sourceCode.getText(type));\\n typeText = typeTexts.join(\\\" | \\\");\\n }\\n\\n const fullRange: readonly [number, number] = [param.range[0], unionTypes.range[1]];\\n\\n return fixer.replaceTextRange(fullRange, `${param.name}?: ${typeText}`);\\n}\\n\\nfunction hasUndefined(unionTypes: UnionTypeNode): boolean {\\n return unionTypes.types.some((type) => type.type === ruleConstants.nodeTypes.typeUndefined);\\n}\\n\\nfunction hasNull(unionTypes: UnionTypeNode): boolean {\\n return unionTypes.types.some((type) => type.type === ruleConstants.nodeTypes.typeNull);\\n}\\n\\ntype MessageIds = typeof ruleConstants.messageId;\\ntype Options = [];\\n\\nconst createRule = ESLintUtils.RuleCreator((name: string) => `${ruleConstants.urlBase}${name}`);\\n\\nconst noUseUndefinedForOptional = createRule<Options, MessageIds>({\\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 function checkTypeAnnotation(param: TSESTree.Identifier, unionTypes: TSESTree.TSUnionType) {\\n const hasUndefinedType = hasUndefined(unionTypes);\\n const hasNullType = hasNull(unionTypes);\\n\\n if (hasUndefinedType || hasNullType) {\\n context.report({\\n node: param,\\n messageId: \\\"noUseUndefinedForOptional\\\",\\n data: { paramName: param.name },\\n fix(fixer) {\\n if (hasUndefinedType) {\\n return createAutoFix(context, fixer, param, unionTypes);\\n }\\n\\n return null;\\n },\\n });\\n }\\n }\\n\\n return {\\n FunctionDeclaration(node: TSESTree.FunctionDeclaration) {\\n checkFunctionParams(node.params, checkTypeAnnotation);\\n },\\n FunctionExpression(node: TSESTree.FunctionExpression) {\\n checkFunctionParams(node.params, checkTypeAnnotation);\\n },\\n ArrowFunctionExpression(node: TSESTree.ArrowFunctionExpression) {\\n checkFunctionParams(node.params, checkTypeAnnotation);\\n },\\n TSMethodSignature(node: TSESTree.TSMethodSignature) {\\n checkFunctionParams(node.params, checkTypeAnnotation);\\n },\\n TSTypeAliasDeclaration(node: TSESTree.TSTypeAliasDeclaration) {\\n if (node.typeAnnotation.type === ruleConstants.nodeTypes.typeTSFunction) {\\n checkFunctionParams(node.typeAnnotation.params, checkTypeAnnotation);\\n }\\n },\\n TSTypeAnnotation(node: TSESTree.TSTypeAnnotation) {\\n if (node.typeAnnotation.type === ruleConstants.nodeTypes.typeTSFunction) {\\n checkFunctionParams(node.typeAnnotation.params, checkTypeAnnotation);\\n }\\n },\\n TSPropertySignature(node: TSESTree.TSPropertySignature) {\\n const key = node.key;\\n\\n if (key.type !== ruleConstants.nodeTypes.identifier) return;\\n\\n const typeAnnotation = node.typeAnnotation?.typeAnnotation;\\n\\n if (!typeAnnotation) return;\\n\\n if (typeAnnotation.type === ruleConstants.nodeTypes.typeTSUnionType) {\\n checkTypeAnnotation(key, typeAnnotation);\\n }\\n },\\n };\\n },\\n});\\n\\nexport default noUseUndefinedForOptional;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport rule from \\\"@root/rules/no-use-type-undefined-for-optional\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `function foo(bar?: string) {}`,\\n },\\n {\\n code: `const foo = (bar?: number) => {};`,\\n },\\n {\\n code: `const foo = function (bar?: boolean, baz: number) {};`,\\n },\\n {\\n code: `function foo(bar: string, baz: number) {}`,\\n },\\n {\\n code: `const foo = (bar: string | number) => {};`,\\n },\\n {\\n code: `function foo(bar = \\\"default\\\") {}`,\\n },\\n {\\n code: `interface Foo {\\n bar: string ;\\n baz?: number;\\n baw: {\\n bad: string | number;\\n };\\n}`,\\n },\\n {\\n code: `type foo = (bar: string | number) => void;`,\\n },\\n {\\n code: `class Foo {\\n method(bar: string | number) {}\\n}`,\\n },\\n {\\n code: `interface Foo {\\n foo(bar?: string ): void\\n}`,\\n },\\n {\\n code: `class Foo {\\n foo(bar?: string) {}\\n}`,\\n },\\n {\\n code: `const fn: { foo: (bar: string | number) => void } = { fn: () => {} };`,\\n },\\n {\\n code: `function foo({ bar }: { bar?: string }) {}`,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `function foo(bar: string | null | undefined) {}`,\\n output: `function foo(bar?: string | null) {}`,\\n errors: [{ messageId: \\\"noUseUndefinedForOptional\\\", data: { paramName: \\\"bar\\\" } }],\\n },\\n {\\n code: `function caller(fn: (bar: string | undefined) => void) {}`,\\n output: `function caller(fn: (bar?: string) => void) {}`,\\n errors: [{ messageId: \\\"noUseUndefinedForOptional\\\", data: { paramName: \\\"bar\\\" } }],\\n },\\n {\\n code: `const obj = {\\n someMethod(bar: string | undefined) {},\\n};`,\\n output: `const obj = {\\n someMethod(bar?: string) {},\\n};`,\\n errors: [{ messageId: \\\"noUseUndefinedForOptional\\\", data: { paramName: \\\"bar\\\" } }],\\n },\\n {\\n code: `const foo = function (bar?: boolean | null) {};`,\\n errors: [{ messageId: \\\"noUseUndefinedForOptional\\\", data: { paramName: \\\"bar\\\" } }],\\n },\\n {\\n code: `const foo = (bar: string | null) => {};`,\\n errors: [{ messageId: \\\"noUseUndefinedForOptional\\\", data: { paramName: \\\"bar\\\" } }],\\n },\\n {\\n code: `function foo(bar: boolean | null | undefined) {}`,\\n output: `function foo(bar?: boolean | null) {}`,\\n errors: [{ messageId: \\\"noUseUndefinedForOptional\\\", data: { paramName: \\\"bar\\\" } }],\\n },\\n {\\n code: `interface Foo {\\n bar: string | undefined;\\n baz?: number | undefined;\\n baw: {\\n bad: string | undefined;\\n };\\n}`,\\n output: `interface Foo {\\n bar?: string;\\n baz?: number;\\n baw: {\\n bad?: string;\\n };\\n}`,\\n errors: [\\n { messageId: \\\"noUseUndefinedForOptional\\\", data: { paramName: \\\"bar\\\" } },\\n { messageId: \\\"noUseUndefinedForOptional\\\", data: { paramName: \\\"baz\\\" } },\\n { messageId: \\\"noUseUndefinedForOptional\\\", data: { paramName: \\\"bad\\\" } },\\n ],\\n },\\n {\\n code: `type foo = (bar: string | undefined) => void;`,\\n output: `type foo = (bar?: string) => void;`,\\n errors: [{ messageId: \\\"noUseUndefinedForOptional\\\", data: { paramName: \\\"bar\\\" } }],\\n },\\n {\\n code: `class Foo {\\n method(bar: string | undefined) {}\\n}`,\\n output: `class Foo {\\n method(bar?: string) {}\\n}`,\\n errors: [{ messageId: \\\"noUseUndefinedForOptional\\\", data: { paramName: \\\"bar\\\" } }],\\n },\\n {\\n code: `interface Foo {\\n foo(bar: string | undefined): void\\n}`,\\n output: `interface Foo {\\n foo(bar?: string): void\\n}`,\\n errors: [{ messageId: \\\"noUseUndefinedForOptional\\\", data: { paramName: \\\"bar\\\" } }],\\n },\\n {\\n code: `class Foo {\\n foo(bar: string | undefined) {}\\n}`,\\n output: `class Foo {\\n foo(bar?: string) {}\\n}`,\\n errors: [{ messageId: \\\"noUseUndefinedForOptional\\\", data: { paramName: \\\"bar\\\" } }],\\n },\\n {\\n code: `const fn: { fn: (bar: string | undefined) => void } = { fn: () => {} };`,\\n output: `const fn: { fn: (bar?: string) => void } = { fn: () => {} };`,\\n errors: [{ messageId: \\\"noUseUndefinedForOptional\\\", data: { paramName: \\\"bar\\\" } }],\\n },\\n {\\n code: `function foo({ bar }: { bar: string | undefined }) {}`,\\n output: `function foo({ bar }: { bar?: string }) {}`,\\n errors: [{ messageId: \\\"noUseUndefinedForOptional\\\", data: { paramName: \\\"bar\\\" } }],\\n },\\n ],\\n};\\n\\nconst cases = [validCases, invalidCases];\\n\\nrunTests(\\\"no-use-type-undefined-for-optional\\\", rule, cases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'no-usless-destructing.ts' and a test for it.\",\"rule_code\":\"import { 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 noUslessDestructing = createRule({\\n name: \\\"no-usless-destructing\\\",\\n meta: {\\n type: \\\"problem\\\",\\n docs: {\\n description: \\\"Disallow destructuring when it doesn't improve code clarity or is unnecessary\\\",\\n },\\n messages: {\\n noUslessDestructing: \\\"Destructuring is not allowed in this case.\\\",\\n },\\n schema: [],\\n },\\n create(context: RuleContext<\\\"noUslessDestructing\\\", []>) {\\n return {\\n VariableDeclarator(node) {\\n if (node.id.type === \\\"ObjectPattern\\\" && node.id.properties.length === 1) {\\n context.report({\\n node,\\n messageId: \\\"noUslessDestructing\\\",\\n });\\n }\\n },\\n\\n FunctionDeclaration(node) {\\n node.params.forEach((param) => {\\n if (param.type === \\\"ObjectPattern\\\" && param.properties.length === 1) {\\n context.report({\\n node: param,\\n messageId: \\\"noUslessDestructing\\\",\\n });\\n }\\n });\\n },\\n\\n ArrowFunctionExpression(node) {\\n node.params.forEach((param) => {\\n if (param.type === \\\"ObjectPattern\\\" && param.properties.length === 1) {\\n context.report({\\n node: param,\\n messageId: \\\"noUslessDestructing\\\",\\n });\\n }\\n });\\n },\\n };\\n },\\n defaultOptions: [],\\n});\\n\\nexport default noUslessDestructing;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport noUslessDestructing from \\\"@root/rules/no-usless-destructing\\\";\\n\\nconst validCases = {\\n valid: [\\n {\\n code: `const qux = foo();\\n baz(qux.bar);\\n `,\\n },\\n {\\n code: `const name = user.name;\\n function getData(user) {\\n return user.id;\\n }\\n `,\\n },\\n {\\n code: `const { name3: name3, age: age } = user;\\n function getData({ id: id, status: status }) {\\n return id + status;\\n }\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n code: `const { bar: bar } = foo();\\n baz(bar);\\n `,\\n errors: [{ messageId: \\\"noUslessDestructing\\\" }],\\n },\\n {\\n code: `const { name: name } = user;\\n function getData({ id: id }) {\\n return id;\\n }\\n `,\\n errors: [{ messageId: \\\"noUslessDestructing\\\" }, { messageId: \\\"noUslessDestructing\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"no-usless-destructing\\\", noUslessDestructing, testCases);\\n\"}\n{\"instruction\":\"Write an ESLint rule 'server-component-must-be-async.ts' and a test for it.\",\"rule_code\":\"/* eslint-disable max-lines */\\nimport { ESLintUtils, TSESTree, TSESLint } from \\\"@typescript-eslint/utils\\\";\\n\\nconst url = \\\"https://example.com/rules/\\\";\\nconst createRule = ESLintUtils.RuleCreator((ruleName) => `${url}${ruleName}`);\\n\\nconst browser_APIs = new Set([\\n \\\"window\\\",\\n \\\"document\\\",\\n \\\"localStorage\\\",\\n \\\"sessionStorage\\\",\\n \\\"navigator\\\",\\n \\\"location\\\",\\n \\\"history\\\",\\n \\\"alert\\\",\\n \\\"confirm\\\",\\n \\\"prompt\\\",\\n \\\"console\\\",\\n]);\\n\\nconst reactHooks = new Set([\\n \\\"useState\\\",\\n \\\"useEffect\\\",\\n \\\"useContext\\\",\\n \\\"useReducer\\\",\\n \\\"useCallback\\\",\\n \\\"useMemo\\\",\\n \\\"useRef\\\",\\n \\\"useImperativeHandle\\\",\\n \\\"useLayoutEffect\\\",\\n \\\"useDebugValue\\\",\\n \\\"useDeferredValue\\\",\\n \\\"useTransition\\\",\\n \\\"useId\\\",\\n \\\"useSyncExternalStore\\\",\\n \\\"useInsertionEffect\\\",\\n]);\\n\\nconst eventHandlers = new Set([\\n \\\"onClick\\\",\\n \\\"onChange\\\",\\n \\\"onSubmit\\\",\\n \\\"onFocus\\\",\\n \\\"onBlur\\\",\\n \\\"onMouseOver\\\",\\n \\\"onMouseOut\\\",\\n \\\"onMouseDown\\\",\\n \\\"onMouseUp\\\",\\n \\\"onKeyDown\\\",\\n \\\"onKeyUp\\\",\\n \\\"onKeyPress\\\",\\n \\\"onLoad\\\",\\n \\\"onError\\\",\\n \\\"onScroll\\\",\\n \\\"onResize\\\",\\n \\\"onInput\\\",\\n \\\"onDoubleClick\\\",\\n \\\"onDrag\\\",\\n \\\"onDrop\\\",\\n \\\"onTouchStart\\\",\\n \\\"onTouchEnd\\\",\\n \\\"onTouchMove\\\",\\n]);\\n\\ntype AnyFunctionNode =\\n | TSESTree.FunctionDeclaration\\n | TSESTree.FunctionExpression\\n | TSESTree.ArrowFunctionExpression;\\n\\nfunction hasUseClientDirective(context: TSESLint.RuleContext<\\\"addAsync\\\", []>): boolean {\\n const sourceCode = context.sourceCode;\\n const firstStatement = sourceCode.ast.body[0];\\n\\n return !!(\\n firstStatement &&\\n firstStatement.type === \\\"ExpressionStatement\\\" &&\\n firstStatement.expression.type === \\\"Literal\\\" &&\\n firstStatement.expression.value === \\\"use client\\\"\\n );\\n}\\n\\nfunction isComponentFunction(node: AnyFunctionNode): boolean {\\n let result = false;\\n\\n if (node.type === \\\"FunctionDeclaration\\\") {\\n result = !!node.id && /^[A-Z]/.test(node.id.name);\\n } else {\\n const parent = node.parent;\\n\\n if (parent?.type === \\\"VariableDeclarator\\\" && parent.id.type === \\\"Identifier\\\") {\\n result = /^[A-Z]/.test(parent.id.name);\\n }\\n }\\n\\n return result;\\n}\\n\\nfunction returnsJSX(node: AnyFunctionNode): boolean {\\n if (node.body.type === \\\"BlockStatement\\\") {\\n return node.body.body.some((stmt) => {\\n if (stmt.type === \\\"ReturnStatement\\\" && stmt.argument) {\\n return containsJSX(stmt.argument);\\n }\\n\\n return false;\\n });\\n }\\n\\n return containsJSX(node.body);\\n}\\n\\nfunction containsJSX(node: TSESTree.Node): boolean {\\n let result = false;\\n\\n if (node.type === \\\"JSXElement\\\" || node.type === \\\"JSXFragment\\\") {\\n result = true;\\n } else if (\\n node.type === \\\"CallExpression\\\" &&\\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 === \\\"createElement\\\"\\n ) {\\n result = true;\\n } else if (node.type === \\\"ConditionalExpression\\\") {\\n result = containsJSX(node.consequent) || containsJSX(node.alternate);\\n } else if (node.type === \\\"LogicalExpression\\\") {\\n result = containsJSX(node.left) || containsJSX(node.right);\\n }\\n\\n return result;\\n}\\n\\nfunction hasEventHandlerAttribute(jsxElement: TSESTree.JSXElement): boolean {\\n let result = false;\\n\\n for (const attr of jsxElement.openingElement.attributes) {\\n if (\\n attr.type === \\\"JSXAttribute\\\" &&\\n attr.name.type === \\\"JSXIdentifier\\\" &&\\n eventHandlers.has(attr.name.name)\\n ) {\\n result = true;\\n break;\\n }\\n }\\n\\n return result;\\n}\\n\\nfunction checkJSXChildren(children: TSESTree.JSXChild[]): boolean {\\n let result = false;\\n\\n for (const child of children) {\\n if (checkJSXForEventHandlers(child)) {\\n result = true;\\n break;\\n }\\n }\\n\\n return result;\\n}\\n\\nfunction checkJSXForEventHandlers(jsxNode: TSESTree.Node): boolean {\\n let result = false;\\n\\n if (jsxNode.type === \\\"JSXElement\\\") {\\n if (hasEventHandlerAttribute(jsxNode)) {\\n result = true;\\n } else {\\n result = checkJSXChildren(jsxNode.children);\\n }\\n } else if (jsxNode.type === \\\"JSXFragment\\\") {\\n result = checkJSXChildren(jsxNode.children);\\n } else if (\\n jsxNode.type === \\\"JSXExpressionContainer\\\" &&\\n jsxNode.expression.type !== \\\"JSXEmptyExpression\\\"\\n ) {\\n result = checkNodeForEventHandlers(jsxNode.expression);\\n }\\n\\n return result;\\n}\\n\\nfunction checkNodeForEventHandlers(astNode: TSESTree.Node): boolean {\\n let result = false;\\n\\n if (astNode.type === \\\"JSXElement\\\" || astNode.type === \\\"JSXFragment\\\") {\\n result = checkJSXForEventHandlers(astNode);\\n } else if (astNode.type === \\\"ConditionalExpression\\\") {\\n result =\\n checkNodeForEventHandlers(astNode.consequent) || checkNodeForEventHandlers(astNode.alternate);\\n } else if (astNode.type === \\\"LogicalExpression\\\") {\\n result = checkNodeForEventHandlers(astNode.left) || checkNodeForEventHandlers(astNode.right);\\n } else if (astNode.type === \\\"ReturnStatement\\\" && astNode.argument) {\\n result = checkNodeForEventHandlers(astNode.argument);\\n }\\n\\n return result;\\n}\\n\\nfunction hasEventHandlers(node: AnyFunctionNode): boolean {\\n let result = false;\\n\\n if (node.body.type === \\\"BlockStatement\\\") {\\n for (const stmt of node.body.body) {\\n if (checkNodeForEventHandlers(stmt)) {\\n result = true;\\n break;\\n }\\n }\\n } else {\\n result = checkNodeForEventHandlers(node.body);\\n }\\n\\n return result;\\n}\\n\\nfunction checkForReactHooks(astNode: TSESTree.Node, found: { value: boolean }) {\\n if (found.value) return;\\n\\n if (astNode.type === \\\"CallExpression\\\" && astNode.callee.type === \\\"Identifier\\\") {\\n if (reactHooks.has(astNode.callee.name)) {\\n found.value = true;\\n return;\\n }\\n }\\n\\n if (astNode.type === \\\"VariableDeclaration\\\") {\\n for (const declarator of astNode.declarations) {\\n if (declarator.init && declarator.init.type === \\\"CallExpression\\\") {\\n checkForReactHooks(declarator.init, found);\\n }\\n }\\n }\\n}\\n\\nfunction processIfStatement(stmt: TSESTree.IfStatement, found: { value: boolean }) {\\n if (stmt.consequent.type === \\\"BlockStatement\\\") {\\n traverseForHooks(stmt.consequent.body, found);\\n } else {\\n checkForReactHooks(stmt.consequent, found);\\n }\\n\\n if (stmt.alternate) {\\n if (stmt.alternate.type === \\\"BlockStatement\\\") {\\n traverseForHooks(stmt.alternate.body, found);\\n } else {\\n checkForReactHooks(stmt.alternate, found);\\n }\\n }\\n}\\n\\nfunction traverseForHooks(statements: TSESTree.Statement[], found: { value: boolean }) {\\n for (const stmt of statements) {\\n if (found.value) return;\\n\\n checkForReactHooks(stmt, found);\\n\\n if (stmt.type === \\\"IfStatement\\\") {\\n processIfStatement(stmt, found);\\n }\\n }\\n}\\n\\nfunction hasReactHooks(node: AnyFunctionNode): boolean {\\n const found = { value: false };\\n\\n if (node.body.type === \\\"BlockStatement\\\") {\\n traverseForHooks(node.body.body, found);\\n } else {\\n checkForReactHooks(node.body, found);\\n }\\n\\n return found.value;\\n}\\n\\nfunction checkIdentifierForBrowserAPI(astNode: TSESTree.Node, found: { value: boolean }): boolean {\\n if (astNode.type === \\\"Identifier\\\" && browser_APIs.has(astNode.name)) {\\n found.value = true;\\n return true;\\n }\\n\\n return false;\\n}\\n\\nfunction checkMemberExpressionForBrowserAPI(astNode: TSESTree.Node, found: { value: boolean }): boolean {\\n if (\\n astNode.type === \\\"MemberExpression\\\" &&\\n astNode.object.type === \\\"Identifier\\\" &&\\n browser_APIs.has(astNode.object.name)\\n ) {\\n found.value = true;\\n return true;\\n }\\n\\n return false;\\n}\\n\\nfunction checkCallExpressionForBrowserAPI(astNode: TSESTree.CallExpression, found: { value: boolean }) {\\n if (astNode.callee.type === \\\"Identifier\\\" && browser_APIs.has(astNode.callee.name)) {\\n found.value = true;\\n return;\\n }\\n\\n if (astNode.callee.type === \\\"MemberExpression\\\") {\\n checkForBrowserAPIs(astNode.callee, found);\\n }\\n\\n for (const arg of astNode.arguments) {\\n checkForBrowserAPIs(arg as TSESTree.Node, found);\\n }\\n}\\n\\nfunction checkVariableDeclarationForBrowserAPI(\\n astNode: TSESTree.VariableDeclaration,\\n found: { value: boolean },\\n) {\\n for (const declarator of astNode.declarations) {\\n if (declarator.init) {\\n checkForBrowserAPIs(declarator.init, found);\\n }\\n }\\n}\\n\\nfunction checkForBrowserAPIs(astNode: TSESTree.Node, found: { value: boolean }) {\\n let shouldRecurse = true;\\n\\n if (!found.value) {\\n if (checkIdentifierForBrowserAPI(astNode, found)) {\\n shouldRecurse = false;\\n } else if (checkMemberExpressionForBrowserAPI(astNode, found)) {\\n shouldRecurse = false;\\n } else if (astNode.type === \\\"CallExpression\\\") {\\n checkCallExpressionForBrowserAPI(astNode, found);\\n shouldRecurse = false;\\n } else if (astNode.type === \\\"VariableDeclaration\\\") {\\n checkVariableDeclarationForBrowserAPI(astNode, found);\\n shouldRecurse = false;\\n }\\n }\\n\\n if (shouldRecurse && astNode.type === \\\"ExpressionStatement\\\") {\\n checkForBrowserAPIs(astNode.expression, found);\\n }\\n}\\n\\nfunction processIfStatementForBrowserAPIs(stmt: TSESTree.IfStatement, found: { value: boolean }) {\\n if (stmt.consequent.type === \\\"BlockStatement\\\") {\\n traverseForBrowserAPIs(stmt.consequent.body, found);\\n } else {\\n checkForBrowserAPIs(stmt.consequent, found);\\n }\\n\\n if (stmt.alternate) {\\n if (stmt.alternate.type === \\\"BlockStatement\\\") {\\n traverseForBrowserAPIs(stmt.alternate.body, found);\\n } else {\\n checkForBrowserAPIs(stmt.alternate, found);\\n }\\n }\\n}\\n\\nfunction traverseForBrowserAPIs(statements: TSESTree.Statement[], found: { value: boolean }) {\\n for (const stmt of statements) {\\n if (found.value) return;\\n\\n checkForBrowserAPIs(stmt, found);\\n\\n if (stmt.type === \\\"IfStatement\\\") {\\n processIfStatementForBrowserAPIs(stmt, found);\\n }\\n }\\n}\\n\\nfunction hasBrowserAPIs(node: AnyFunctionNode): boolean {\\n const found = { value: false };\\n\\n if (node.body.type === \\\"BlockStatement\\\") {\\n traverseForBrowserAPIs(node.body.body, found);\\n } else {\\n checkForBrowserAPIs(node.body, found);\\n }\\n\\n return found.value;\\n}\\n\\nfunction isAsyncFunction(node: AnyFunctionNode): boolean {\\n return node.async === true;\\n}\\n\\nfunction createAsyncFix(fixer: TSESLint.RuleFixer, node: AnyFunctionNode) {\\n return fixer.insertTextBefore(node, \\\"async \\\");\\n}\\n\\nconst serverComponentMustBeAsync = createRule({\\n name: \\\"server-component-must-be-async\\\",\\n meta: {\\n type: \\\"suggestion\\\",\\n docs: {\\n description: \\\"Server components that don't use client-side features should be async\\\",\\n },\\n messages: {\\n addAsync: \\\"Server component should be async since it doesn't use client-side features\\\",\\n },\\n schema: [],\\n fixable: \\\"code\\\",\\n },\\n defaultOptions: [],\\n create(context) {\\n if (hasUseClientDirective(context)) {\\n return {};\\n }\\n\\n function checkFunction(node: AnyFunctionNode) {\\n let shouldReport =\\n isComponentFunction(node) &&\\n returnsJSX(node) &&\\n !isAsyncFunction(node) &&\\n !hasEventHandlers(node) &&\\n !hasReactHooks(node) &&\\n !hasBrowserAPIs(node);\\n\\n if (shouldReport) {\\n context.report({\\n node,\\n messageId: \\\"addAsync\\\",\\n fix: (fixer) => createAsyncFix(fixer, node),\\n });\\n }\\n }\\n\\n return {\\n FunctionDeclaration: checkFunction,\\n FunctionExpression: checkFunction,\\n ArrowFunctionExpression: checkFunction,\\n };\\n },\\n});\\n\\nexport default serverComponentMustBeAsync;\\n\",\"test_code\":\"import { runTests } from \\\"@root/test-utils/eslint-rule-tester\\\";\\nimport rule from \\\"@root/rules/server-component-must-be-async\\\";\\n\\nconst validCases = {\\n valid: [\\n // Client components with \\\"use client\\\" directive\\n {\\n code: `\\n\\\"use client\\\";\\nfunction ClientComponent() {\\n return <div onClick={() => alert('Hi')}>Click me</div>;\\n}\\n `,\\n },\\n {\\n code: `\\n\\\"use client\\\";\\nconst ClientComponent = () => {\\n const [state, setState] = useState(0);\\n return <div>{state}</div>;\\n};\\n `,\\n },\\n // Components with event handlers\\n {\\n code: `\\nfunction ComponentWithHandler() {\\n return <button onClick={() => alert('Hi')}>Click</button>;\\n}\\n `,\\n },\\n {\\n code: `\\nconst ComponentWithHandler = () => (\\n <div>\\n <input onChange={(e) => console.log(e.target.value)} />\\n </div>\\n);\\n `,\\n },\\n // Components using React hooks\\n {\\n code: `\\nfunction ComponentWithHooks() {\\n const [state, setState] = useState(0);\\n return <div>{state}</div>;\\n}\\n `,\\n },\\n {\\n code: `\\nconst ComponentWithHooks = () => {\\n const effect = useEffect(() => {}, []);\\n return <div>Hello</div>;\\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 <div>Hello</div>;\\n}\\n `,\\n },\\n // Components using browser APIs\\n {\\n code: `\\nfunction ComponentWithBrowserAPI() {\\n const data = localStorage.getItem('key');\\n return <div>{data}</div>;\\n}\\n `,\\n },\\n {\\n code: `\\nconst ComponentWithBrowserAPI = () => {\\n window.addEventListener('scroll', () => {});\\n return <div>Hello</div>;\\n};\\n `,\\n },\\n // Already async components\\n {\\n code: `\\nasync function AlreadyAsync() {\\n return <div>Already async</div>;\\n}\\n `,\\n },\\n {\\n code: `\\nconst AlreadyAsync = async () => <div>Already async</div>;\\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 <div>lowercase name</div>;\\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 <div>\\n <span>Text</span>\\n <button onClick={() => {}}>Click</button>\\n </div>\\n );\\n}\\n `,\\n },\\n // Components using console API\\n {\\n code: `\\nfunction ComponentWithConsole() {\\n console.log('Debug message');\\n return <div>Hello</div>;\\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 <div>Hello Server</div>;\\n}\\n `,\\n errors: [{ messageId: \\\"addAsync\\\" }],\\n output: `\\nasync function ServerComponent() {\\n return <div>Hello Server</div>;\\n}\\n `,\\n },\\n {\\n code: `\\nconst ServerComponent = () => <div>Hello</div>;\\n `,\\n errors: [{ messageId: \\\"addAsync\\\" }],\\n output: `\\nconst ServerComponent = async () => <div>Hello</div>;\\n `,\\n },\\n // Function expression components\\n {\\n code: `\\nconst ServerComponent = function() {\\n return <div>Hello Server</div>;\\n};\\n `,\\n errors: [{ messageId: \\\"addAsync\\\" }],\\n output: `\\nconst ServerComponent = async function() {\\n return <div>Hello Server</div>;\\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 <div>First</div>\\n <div>Second</div>\\n </>\\n );\\n}\\n `,\\n errors: [{ messageId: \\\"addAsync\\\" }],\\n output: `\\nasync function ServerComponent() {\\n return (\\n <>\\n <div>First</div>\\n <div>Second</div>\\n </>\\n );\\n}\\n `,\\n },\\n // Exported components\\n {\\n code: `\\nexport function ServerComponent() {\\n return <div>Exported component</div>;\\n}\\n `,\\n errors: [{ messageId: \\\"addAsync\\\" }],\\n output: `\\nexport async function ServerComponent() {\\n return <div>Exported component</div>;\\n}\\n `,\\n },\\n {\\n code: `\\nexport default function ServerComponent() {\\n return <div>Default export</div>;\\n}\\n `,\\n errors: [{ messageId: \\\"addAsync\\\" }],\\n output: `\\nexport default async function ServerComponent() {\\n return <div>Default export</div>;\\n}\\n `,\\n },\\n // Components with conditional returns\\n {\\n code: `\\nfunction ServerComponent() {\\n if (condition) {\\n return <div>Conditional JSX</div>;\\n }\\n return <div>Default JSX</div>;\\n}\\n `,\\n errors: [{ messageId: \\\"addAsync\\\" }],\\n output: `\\nasync function ServerComponent() {\\n if (condition) {\\n return <div>Conditional JSX</div>;\\n }\\n return <div>Default JSX</div>;\\n}\\n `,\\n },\\n // Components with complex JSX\\n {\\n code: `\\nfunction ComplexServerComponent() {\\n const data = processData();\\n return (\\n <div>\\n <h1>Title</h1>\\n <p>Content: {data}</p>\\n <ul>\\n {items.map(item => <li key={item.id}>{item.name}</li>)}\\n </ul>\\n </div>\\n );\\n}\\n `,\\n errors: [{ messageId: \\\"addAsync\\\" }],\\n output: `\\nasync function ComplexServerComponent() {\\n const data = processData();\\n return (\\n <div>\\n <h1>Title</h1>\\n <p>Content: {data}</p>\\n <ul>\\n {items.map(item => <li key={item.id}>{item.name}</li>)}\\n </ul>\\n </div>\\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<MessageIds, Options>,\\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<Options, MessageIds>({\\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<string>) {\\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<string> = 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 <button onClick={onClick}>Click me</button>\\n );\\n `,\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n function Button({ onClick }) {\\n return <button onClick={onClick}>Click me</button>;\\n }\\n `,\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n const Button = function({ onClick }) {\\n return <button onClick={onClick}>Click me</button>;\\n };\\n `,\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n export default function Button({ onClick }) {\\n return <button onClick={onClick}>Click me</button>;\\n }\\n `,\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n someWrapper(function({ onClick }) {\\n return <button onClick={onClick}>Click me</button>;\\n });\\n `,\\n },\\n ],\\n};\\n\\nconst invalidCases = {\\n invalid: [\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n const Button = ({ handleClick }) => (\\n <button onClick={handleClick}>Click me</button>\\n );\\n `,\\n errors: [{ messageId: \\\"useOnPrefix\\\" }],\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n function Button({ handleClick }) {\\n return <button onClick={handleClick}>Click me</button>;\\n }\\n `,\\n errors: [{ messageId: \\\"useOnPrefix\\\" }],\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n const Button = function({ handleClick }) {\\n return <button onClick={handleClick}>Click me</button>;\\n };\\n `,\\n errors: [{ messageId: \\\"useOnPrefix\\\" }],\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n export default function Button({ handleClick }) {\\n return <button onClick={handleClick}>Click me</button>;\\n }\\n `,\\n errors: [{ messageId: \\\"useOnPrefix\\\" }],\\n },\\n {\\n filename: \\\"test.jsx\\\",\\n code: `\\n someWrapper(function({ handleClick }) {\\n return <button onClick={handleClick}>Click me</button>;\\n });\\n `,\\n errors: [{ messageId: \\\"useOnPrefix\\\" }],\\n },\\n ],\\n};\\n\\nconst testCases = [validCases, invalidCases];\\nrunTests(\\\"use-on-prefix\\\", UseOnPrefix, testCases);\\n\"}"} |