forked from sveltejs/eslint-plugin-svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprefer-const.ts
81 lines (69 loc) · 1.88 KB
/
prefer-const.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import type { TSESTree } from '@typescript-eslint/types';
import { createRule } from '../utils/index.js';
import { defineWrapperListener, getCoreRule } from '../utils/eslint-core.js';
const coreRule = getCoreRule('prefer-const');
/**
* Finds and returns the callee of a declaration node within variable declarations or object patterns.
*/
function findDeclarationCallee(node: TSESTree.Expression) {
const { parent } = node;
if (parent.type === 'VariableDeclarator' && parent.init?.type === 'CallExpression') {
return parent.init.callee;
}
return null;
}
/**
* Determines if a declaration should be skipped in the const preference analysis.
* Specifically checks for Svelte's state management utilities ($props, $derived).
*/
function shouldSkipDeclaration(declaration: TSESTree.Expression | null) {
if (!declaration) {
return false;
}
const callee = findDeclarationCallee(declaration);
if (!callee) {
return false;
}
if (callee.type === 'Identifier' && ['$props', '$derived'].includes(callee.name)) {
return true;
}
if (callee.type !== 'MemberExpression' || callee.object.type !== 'Identifier') {
return false;
}
if (
callee.object.name === '$derived' &&
callee.property.type === 'Identifier' &&
callee.property.name === 'by'
) {
return true;
}
return false;
}
export default createRule('prefer-const', {
meta: {
...coreRule.meta,
docs: {
description: coreRule.meta.docs.description,
category: 'Best Practices',
recommended: false,
extensionRule: 'prefer-const'
}
},
create(context) {
return defineWrapperListener(coreRule, context, {
createListenerProxy(coreListener) {
return {
...coreListener,
VariableDeclaration(node) {
for (const decl of node.declarations) {
if (shouldSkipDeclaration(decl.init)) {
return;
}
}
coreListener.VariableDeclaration?.(node);
}
};
}
});
}
});