mm_eslint 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +202 -0
  3. package/README_EN.md +202 -0
  4. package/index.js +608 -0
  5. package/package.json +44 -0
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2025 Admin
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,202 @@
1
+ # MM ESLint Plugin
2
+
3
+ 基于个人命名规范的ESLint插件,支持类名、函数名、变量名、常量名等命名规范检测。
4
+
5
+ ## 功能特性
6
+
7
+ - ✅ **类名检测** - 大驼峰命名法(PascalCase)
8
+ - ✅ **函数名检测** - 小驼峰命名法(camelCase)
9
+ - ✅ **方法名检测** - 小驼峰命名法(camelCase)
10
+ - ✅ **变量名检测** - 小写蛇形命名法(snake_case)
11
+ - ✅ **常量名检测** - 大写蛇形命名法(UPPER_SNAKE_CASE)
12
+ - ✅ **私有成员检测** - 下划线开头的小写蛇形命名
13
+ - ✅ **长度限制** - 所有命名长度限制在1-20字符
14
+ - ✅ **单个单词优先** - 鼓励使用单个单词命名
15
+ - ✅ **禁止废话词** - 避免使用Manager、Handler等冗余词汇
16
+
17
+ ## 安装
18
+
19
+ ### npm安装
20
+
21
+ ```bash
22
+ npm install mm-eslint-plugin --save-dev
23
+ ```
24
+
25
+ ### 本地安装
26
+
27
+ 如果您想使用本地版本,可以将插件文件复制到项目中:
28
+
29
+ ```bash
30
+ # 复制插件文件到您的项目
31
+ cp mm-eslint-plugin/index.js your-project/eslint-plugins/
32
+ ```
33
+
34
+ ## 快速开始
35
+
36
+ ### 1. 基本配置
37
+
38
+ 在您的ESLint配置文件中引入插件:
39
+
40
+ ```javascript
41
+ // eslint.config.js
42
+ const namingConventionPlugin = require('mm-eslint-plugin');
43
+
44
+ module.exports = [
45
+ {
46
+ files: ['**/*.js'],
47
+ plugins: {
48
+ 'naming-convention': namingConventionPlugin
49
+ },
50
+ rules: {
51
+ 'naming-convention/class-name': 'error',
52
+ 'naming-convention/function-name': 'error',
53
+ 'naming-convention/method-name': 'error',
54
+ 'naming-convention/variable-name': 'warn',
55
+ 'naming-convention/constant-name': 'error',
56
+ 'naming-convention/private-naming': 'warn'
57
+ }
58
+ }
59
+ ];
60
+ ```
61
+
62
+ ### 2. 命令行使用
63
+
64
+ ```bash
65
+ # 验证单个文件
66
+ npx eslint your-file.js
67
+
68
+ # 验证所有JS文件
69
+ npx eslint "**/*.js"
70
+
71
+ # 验证并自动修复
72
+ npx eslint --fix your-file.js
73
+ ```
74
+
75
+ ## 命名规范规则
76
+
77
+ ### 类名规则(class-name)
78
+ - **级别**: error
79
+ - **要求**: 大驼峰命名法(PascalCase)
80
+ - **长度**: 1-20字符
81
+ - **示例**: `UserService`, `ProductManager`
82
+ - **错误示例**: `userService`, `USER_SERVICE`
83
+
84
+ ### 函数名规则(function-name)
85
+ - **级别**: error
86
+ - **要求**: 小驼峰命名法(camelCase)
87
+ - **长度**: 1-20字符
88
+ - **优先**: 单个单词
89
+ - **示例**: `getUser`, `calculateTotal`
90
+ - **错误示例**: `GetUser`, `get_user`
91
+
92
+ ### 方法名规则(method-name)
93
+ - **级别**: error
94
+ - **要求**: 小驼峰命名法(camelCase)
95
+ - **长度**: 1-20字符
96
+ - **优先**: 单个单词
97
+ - **示例**: `getName`, `setValue`
98
+ - **错误示例**: `GetName`, `get_name`
99
+
100
+ ### 变量名规则(variable-name)
101
+ - **级别**: warn
102
+ - **要求**: 小写蛇形命名法(snake_case)
103
+ - **长度**: 1-20字符
104
+ - **优先**: 单个单词
105
+ - **示例**: `user_count`, `max_retry`
106
+ - **错误示例**: `userCount`, `MAX_RETRY`
107
+
108
+ ### 常量名规则(constant-name)
109
+ - **级别**: error
110
+ - **要求**: 大写蛇形命名法(UPPER_SNAKE_CASE)
111
+ - **长度**: 1-20字符
112
+ - **示例**: `MAX_RETRY`, `DEFAULT_TIMEOUT`
113
+ - **错误示例**: `maxRetry`, `defaultTimeout`
114
+
115
+ ### 私有成员规则(private-naming)
116
+ - **级别**: warn
117
+ - **要求**: 下划线开头的小写蛇形命名
118
+ - **长度**: 2-20字符
119
+ - **示例**: `_user_count`, `_internal_data`
120
+ - **错误示例**: `userCount`, `_UserCount`
121
+
122
+ ## 错误示例
123
+
124
+ ```javascript
125
+ // ❌ 错误的命名示例
126
+ class userService { // 类名应该大驼峰
127
+ const GetUser = function() {}; // 函数名应该小驼峰
128
+ let maxRetryCount = 5; // 变量名应该小写蛇形
129
+ const userCount = 10; // 常量名应该大写蛇形
130
+
131
+ // ✅ 正确的命名示例
132
+ class UserService {
133
+ constructor() {
134
+ this._user_count = 0; // 私有属性正确
135
+ }
136
+
137
+ getUser() { // 方法名正确
138
+ return this._user_count;
139
+ }
140
+ }
141
+
142
+ const MAX_RETRY = 5; // 常量名正确
143
+ let user_count = 10; // 变量名正确
144
+ ```
145
+
146
+ ## 配置选项
147
+
148
+ 您可以通过配置自定义规则参数:
149
+
150
+ ```javascript
151
+ // 自定义配置示例
152
+ const customConfig = {
153
+ 'class-name': {
154
+ regex: /^[A-Z][a-zA-Z]*$/,
155
+ min: 1,
156
+ max: 25, // 扩展最大长度
157
+ message: '类名{name}必须使用大驼峰命名法'
158
+ }
159
+ };
160
+
161
+ const detector = new NamingDetector(customConfig);
162
+ ```
163
+
164
+ ## 开发
165
+
166
+ ### 项目结构
167
+
168
+ ```
169
+ mm-eslint-plugin/
170
+ ├── index.js # 主插件文件
171
+ ├── package.json # npm配置
172
+ ├── eslint.config.js # ESLint配置
173
+ ├── test.js # 单元测试
174
+ ├── example.js # 使用示例
175
+ └── README.md # 说明文档
176
+ ```
177
+
178
+ ### 运行测试
179
+
180
+ ```bash
181
+ # 运行单元测试
182
+ npm test
183
+
184
+ # 运行ESLint检查
185
+ npm run lint
186
+ ```
187
+
188
+ ## 许可证
189
+
190
+ ISC License
191
+
192
+ ## 贡献
193
+
194
+ 欢迎提交Issue和Pull Request来改进这个插件。
195
+
196
+ ## 更新日志
197
+
198
+ ### v1.0.0
199
+ - 初始版本发布
200
+ - 支持类名、函数名、方法名、变量名、常量名、私有成员命名规范检测
201
+ - 支持长度限制和单个单词优先规则
202
+ - 支持禁止废话词检测
package/README_EN.md ADDED
@@ -0,0 +1,202 @@
1
+ # MM ESLint Plugin
2
+
3
+ An ESLint plugin based on personal naming conventions, supporting naming convention detection for class names, function names, variable names, constant names, and more.
4
+
5
+ ## Features
6
+
7
+ - ✅ **Class Name Detection** - PascalCase naming convention
8
+ - ✅ **Function Name Detection** - camelCase naming convention
9
+ - ✅ **Method Name Detection** - camelCase naming convention
10
+ - ✅ **Variable Name Detection** - snake_case naming convention
11
+ - ✅ **Constant Name Detection** - UPPER_SNAKE_CASE naming convention
12
+ - ✅ **Private Member Detection** - underscore-prefixed snake_case naming
13
+ - ✅ **Length Restrictions** - All names limited to 1-20 characters
14
+ - ✅ **Single Word Preferred** - Encourages single word naming
15
+ - ✅ **Forbidden Words** - Avoids redundant words like Manager, Handler, etc.
16
+
17
+ ## Installation
18
+
19
+ ### npm Installation
20
+
21
+ ```bash
22
+ npm install mm-eslint-plugin --save-dev
23
+ ```
24
+
25
+ ### Local Installation
26
+
27
+ If you want to use a local version, you can copy the plugin files to your project:
28
+
29
+ ```bash
30
+ # Copy plugin files to your project
31
+ cp mm-eslint-plugin/index.js your-project/eslint-plugins/
32
+ ```
33
+
34
+ ## Quick Start
35
+
36
+ ### 1. Basic Configuration
37
+
38
+ Import the plugin in your ESLint configuration file:
39
+
40
+ ```javascript
41
+ // eslint.config.js
42
+ const namingConventionPlugin = require('mm-eslint-plugin');
43
+
44
+ module.exports = [
45
+ {
46
+ files: ['**/*.js'],
47
+ plugins: {
48
+ 'naming-convention': namingConventionPlugin
49
+ },
50
+ rules: {
51
+ 'naming-convention/class-name': 'error',
52
+ 'naming-convention/function-name': 'error',
53
+ 'naming-convention/method-name': 'error',
54
+ 'naming-convention/variable-name': 'warn',
55
+ 'naming-convention/constant-name': 'error',
56
+ 'naming-convention/private-naming': 'warn'
57
+ }
58
+ }
59
+ ];
60
+ ```
61
+
62
+ ### 2. Command Line Usage
63
+
64
+ ```bash
65
+ # Validate a single file
66
+ npx eslint your-file.js
67
+
68
+ # Validate all JS files
69
+ npx eslint "**/*.js"
70
+
71
+ # Validate and auto-fix
72
+ npx eslint --fix your-file.js
73
+ ```
74
+
75
+ ## Naming Convention Rules
76
+
77
+ ### Class Name Rule (class-name)
78
+ - **Level**: error
79
+ - **Requirement**: PascalCase naming convention
80
+ - **Length**: 1-20 characters
81
+ - **Examples**: `UserService`, `ProductManager`
82
+ - **Invalid Examples**: `userService`, `USER_SERVICE`
83
+
84
+ ### Function Name Rule (function-name)
85
+ - **Level**: error
86
+ - **Requirement**: camelCase naming convention
87
+ - **Length**: 1-20 characters
88
+ - **Preference**: Single word
89
+ - **Examples**: `getUser`, `calculateTotal`
90
+ - **Invalid Examples**: `GetUser`, `get_user`
91
+
92
+ ### Method Name Rule (method-name)
93
+ - **Level**: error
94
+ - **Requirement**: camelCase naming convention
95
+ - **Length**: 1-20 characters
96
+ - **Preference**: Single word
97
+ - **Examples**: `getName`, `setValue`
98
+ - **Invalid Examples**: `GetName`, `get_name`
99
+
100
+ ### Variable Name Rule (variable-name)
101
+ - **Level**: warn
102
+ - **Requirement**: snake_case naming convention
103
+ - **Length**: 1-20 characters
104
+ - **Preference**: Single word
105
+ - **Examples**: `user_count`, `max_retry`
106
+ - **Invalid Examples**: `userCount`, `MAX_RETRY`
107
+
108
+ ### Constant Name Rule (constant-name)
109
+ - **Level**: error
110
+ - **Requirement**: UPPER_SNAKE_CASE naming convention
111
+ - **Length**: 1-20 characters
112
+ - **Examples**: `MAX_RETRY`, `DEFAULT_TIMEOUT`
113
+ - **Invalid Examples**: `maxRetry`, `defaultTimeout`
114
+
115
+ ### Private Member Rule (private-naming)
116
+ - **Level**: warn
117
+ - **Requirement**: underscore-prefixed snake_case naming
118
+ - **Length**: 2-20 characters
119
+ - **Examples**: `_user_count`, `_internal_data`
120
+ - **Invalid Examples**: `userCount`, `_UserCount`
121
+
122
+ ## Error Examples
123
+
124
+ ```javascript
125
+ // ❌ Invalid naming examples
126
+ class userService { // Class name should be PascalCase
127
+ const GetUser = function() {}; // Function name should be camelCase
128
+ let maxRetryCount = 5; // Variable name should be snake_case
129
+ const userCount = 10; // Constant name should be UPPER_SNAKE_CASE
130
+
131
+ // ✅ Correct naming examples
132
+ class UserService {
133
+ constructor() {
134
+ this._user_count = 0; // Private property correct
135
+ }
136
+
137
+ getUser() { // Method name correct
138
+ return this._user_count;
139
+ }
140
+ }
141
+
142
+ const MAX_RETRY = 5; // Constant name correct
143
+ let user_count = 10; // Variable name correct
144
+ ```
145
+
146
+ ## Configuration Options
147
+
148
+ You can customize rule parameters through configuration:
149
+
150
+ ```javascript
151
+ // Custom configuration example
152
+ const customConfig = {
153
+ 'class-name': {
154
+ regex: /^[A-Z][a-zA-Z]*$/,
155
+ min: 1,
156
+ max: 25, // Extend maximum length
157
+ message: 'Class name {name} must use PascalCase naming convention'
158
+ }
159
+ };
160
+
161
+ const detector = new NamingDetector(customConfig);
162
+ ```
163
+
164
+ ## Development
165
+
166
+ ### Project Structure
167
+
168
+ ```
169
+ mm-eslint-plugin/
170
+ ├── index.js # Main plugin file
171
+ ├── package.json # npm configuration
172
+ ├── eslint.config.js # ESLint configuration
173
+ ├── test.js # Unit tests
174
+ ├── example.js # Usage examples
175
+ └── README.md # Documentation
176
+ ```
177
+
178
+ ### Running Tests
179
+
180
+ ```bash
181
+ # Run unit tests
182
+ npm test
183
+
184
+ # Run ESLint checks
185
+ npm run lint
186
+ ```
187
+
188
+ ## License
189
+
190
+ ISC License
191
+
192
+ ## Contributing
193
+
194
+ Welcome to submit Issues and Pull Requests to improve this plugin.
195
+
196
+ ## Changelog
197
+
198
+ ### v1.0.0
199
+ - Initial version release
200
+ - Support for class name, function name, method name, variable name, constant name, and private member naming convention detection
201
+ - Support for length restrictions and single word preference rules
202
+ - Support for forbidden words detection
package/index.js ADDED
@@ -0,0 +1,608 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 命名规范检测器类
5
+ */
6
+ class NamingDetector {
7
+ static config = {
8
+ forbidden_words: [
9
+ 'manager', 'handler', 'processor', 'controller',
10
+ 'Management', 'Handler', 'Processor', 'Controller',
11
+ 'LoggerManager', 'AppState', 'UserHandler'
12
+ ],
13
+ // 类名大驼峰规则
14
+ 'class-name': {
15
+ name: '类名',
16
+ message: '{type}{name}必须使用大驼峰命名法(PascalCase),长度{min}-{max}字符,且优先使用单个单词',
17
+ regex: /^[A-Z][a-zA-Z]*$/, // 大写字母开头,只包含字母
18
+ min: 1,
19
+ max: 20
20
+ },
21
+
22
+ // 函数名小驼峰规则
23
+ 'function-name': {
24
+ name: '函数名',
25
+ message: '必须使用小驼峰命名法(camelCase),长度{min}-{max}字符,且优先使用单个单词',
26
+ regex: /^[a-z][a-zA-Z]*$/, // 小写字母开头,只包含字母
27
+ min: 1,
28
+ max: 20,
29
+ single_word_preferred: true
30
+ },
31
+
32
+ // 方法名小驼峰规则
33
+ 'method-name': {
34
+ name: '方法名',
35
+ message: '必须使用小驼峰命名法(camelCase),长度{min}-{max}字符,且优先使用单个单词',
36
+ regex: /^[a-z][a-zA-Z]*$/, // 小写字母开头,只包含字母
37
+ min: 1,
38
+ max: 20,
39
+ single_word_preferred: true
40
+ },
41
+
42
+ // 入参名小写蛇形规则
43
+ 'param-name': {
44
+ name: '入参名',
45
+ message: '必须使用小写蛇形命名法(snake_case),长度{min}-{max}字符',
46
+ regex: /^[a-z][a-z0-9_]*(_[a-z0-9]+)*$/, // 小写字母开头,可包含下划线
47
+ min: 1,
48
+ max: 20
49
+ },
50
+
51
+ // 变量名小写蛇形规则
52
+ 'variable-name': {
53
+ name: '变量名',
54
+ message: '必须使用小写蛇形命名法(snake_case),长度{min}-{max}字符',
55
+ regex: /^[a-z][a-z0-9_]*(_[a-z0-9]+)*$/, // 小写字母开头,可包含下划线
56
+ min: 1,
57
+ max: 20
58
+ },
59
+
60
+ // 常量名大写蛇形规则
61
+ 'constant-name': {
62
+ name: '常量名',
63
+ message: '必须使用大写蛇形命名法(UPPER_SNAKE_CASE),长度{min}-{max}字符',
64
+ regex: /^[A-Z][A-Z0-9_]*(_[A-Z0-9]+)*$/, // 大写字母开头,可包含下划线
65
+ min: 1,
66
+ max: 20
67
+ },
68
+
69
+ // 属性名小写蛇形规则
70
+ 'property-name': {
71
+ name: '属性名',
72
+ message: '必须使用小写蛇形命名法(snake_case),长度{min}-{max}字符',
73
+ regex: /^[a-z][a-z0-9_]*(_[a-z0-9]+)*$/, // 小写字母开头,可包含下划线
74
+ min: 1,
75
+ max: 20
76
+ },
77
+
78
+ // 私有方法/属性规则
79
+ 'private-naming': {
80
+ name: '私有成员',
81
+ message: '必须以单下划线开头,后跟小写蛇形命名,长度{min}-{max}字符',
82
+ regex: /^_[a-z][a-z0-9_]*(_[a-z0-9]+)*$/, // 下划线开头,小写蛇形
83
+ min: 2,
84
+ max: 20
85
+ }
86
+ }
87
+
88
+ constructor(config) {
89
+ // 合并默认配置和传入配置
90
+ const merged_config = { ...NamingDetector.config };
91
+ if (config && typeof config === 'object') {
92
+ Object.keys(config).forEach(key => {
93
+ if (merged_config[key]) {
94
+ merged_config[key] = { ...merged_config[key], ...config[key] };
95
+
96
+ // 处理字符串形式的正则表达式
97
+ if (typeof merged_config[key].regex === 'string') {
98
+ try {
99
+ // 从字符串中提取正则表达式模式和标志
100
+ const regex_match = merged_config[key].regex.match(/^\/(.*)\/([gimuy]*)$/);
101
+ if (regex_match) {
102
+ merged_config[key].regex = new RegExp(regex_match[1], regex_match[2]);
103
+ } else {
104
+ // 如果不是标准的正则表达式字符串格式,直接创建
105
+ merged_config[key].regex = new RegExp(merged_config[key].regex);
106
+ }
107
+ } catch (error) {
108
+ console.warn(`无效的正则表达式: ${merged_config[key].regex}`, error);
109
+ merged_config[key].regex = null;
110
+ }
111
+ }
112
+ }
113
+ });
114
+ }
115
+ this.config = merged_config;
116
+ this._init_rules();
117
+ }
118
+
119
+ _new_model() {
120
+ return {
121
+ name: '',
122
+ message: '',
123
+ regex: null,
124
+ min: 1,
125
+ max: 20
126
+ }
127
+ }
128
+
129
+ _init_rules() {
130
+ // 绑定规则检查方法
131
+ this._rules = {
132
+ 'class-name': this._checkName.bind(this, 'class-name'),
133
+ 'function-name': this._checkName.bind(this, 'function-name'),
134
+ 'method-name': this._checkName.bind(this, 'method-name'),
135
+ 'param-name': this._checkName.bind(this, 'param-name'),
136
+ 'variable-name': this._checkName.bind(this, 'variable-name'),
137
+ 'constant-name': this._checkName.bind(this, 'constant-name'),
138
+ 'property-name': this._checkName.bind(this, 'property-name'),
139
+ 'private-naming': this._checkName.bind(this, 'private-naming')
140
+ };
141
+ }
142
+ }
143
+
144
+ /**
145
+ * 通用命名检查方法
146
+ * @param {string} rule_type - 规则类型
147
+ * @param {string} name - 名称
148
+ * @returns {Object} 检查结果
149
+ * @private
150
+ */
151
+ NamingDetector.prototype._checkName = function (rule_type, name) {
152
+ if (!name) {
153
+ throw new TypeError('名称不能为空');
154
+ }
155
+
156
+ const config = this.config[rule_type];
157
+ if (!config) {
158
+ throw new Error(`不支持的规则类型: ${rule_type}`);
159
+ }
160
+
161
+ const errors = [];
162
+
163
+ // 检查长度
164
+ if (name.length < config.min) {
165
+ errors.push(`${config.name}长度不能少于${config.min}个字符`);
166
+ }
167
+ if (name.length > config.max) {
168
+ errors.push(`${config.name}长度不能超过${config.max}个字符`);
169
+ }
170
+
171
+ // 检查正则表达式
172
+ if (config.regex && !config.regex.test(name)) {
173
+ const error_message = config.message
174
+ .replace('{name}', `"${name}"`)
175
+ .replace('{type}', config.name)
176
+ .replace('{min}', config.min)
177
+ .replace('{max}', config.max)
178
+ .replace('{regex}', config.regex.toString());
179
+ errors.push(error_message);
180
+ }
181
+
182
+ // 检查禁止词汇
183
+ if (this._hasForbiddenWords(name)) {
184
+ errors.push(`${config.name}包含禁止的废话词`);
185
+ }
186
+
187
+ // 检查是否优先使用单个单词
188
+ if (config.single_word_preferred) {
189
+ if (name.includes('_') || name.includes('-')) {
190
+ errors.push(`${config.name}应优先使用单个单词`);
191
+ }
192
+ }
193
+
194
+ return {
195
+ valid: errors.length === 0,
196
+ errors: errors
197
+ };
198
+ }
199
+
200
+ /**
201
+ * 检查是否包含禁止的废话词
202
+ * @param {string} name - 名称
203
+ * @returns {boolean} 是否包含禁止词
204
+ * @private
205
+ */
206
+ NamingDetector.prototype._hasForbiddenWords = function (name) {
207
+ if (!name) {
208
+ return false;
209
+ }
210
+
211
+ const forbidden_words = this.config.forbidden_words || [];
212
+
213
+ return forbidden_words.some(word =>
214
+ name.toLowerCase().includes(word.toLowerCase())
215
+ );
216
+ }
217
+
218
+ /**
219
+ * 检测名称是否符合规范
220
+ * @param {string} name - 名称
221
+ * @param {string} type - 类型(class/function/variable/constant/private)
222
+ * @returns {Object} 检测结果
223
+ */
224
+ NamingDetector.prototype.checkName = function (name, type) {
225
+ if (typeof name !== 'string' || !name.trim()) {
226
+ return {
227
+ valid: false,
228
+ errors: ['名称必须是有效的字符串']
229
+ };
230
+ }
231
+
232
+ if (typeof type !== 'string' || !type.trim()) {
233
+ return {
234
+ valid: false,
235
+ errors: ['类型必须是有效的字符串']
236
+ };
237
+ }
238
+
239
+ const rule_method = this._rules[type];
240
+ if (!rule_method) {
241
+ return {
242
+ valid: false,
243
+ errors: [`不支持的类型: ${type}`]
244
+ };
245
+ }
246
+
247
+ try {
248
+ return rule_method(name);
249
+ } catch (error) {
250
+ return {
251
+ valid: false,
252
+ errors: [`检测名称时出错: ${error.message}`]
253
+ };
254
+ }
255
+ }
256
+
257
+ /**
258
+ * 批量检测名称
259
+ * @param {Array} names - 名称数组
260
+ * @param {string} type - 类型
261
+ * @returns {Array} 检测结果数组
262
+ */
263
+ NamingDetector.prototype.checkNames = function (names, type) {
264
+ if (!Array.isArray(names)) {
265
+ throw new TypeError('名称必须是数组');
266
+ }
267
+
268
+ return names.map(name => this.check_name(name, type));
269
+ }
270
+
271
+ /**
272
+ * ESLint规则实现
273
+ */
274
+
275
+ /**
276
+ * 类名大驼峰规则
277
+ */
278
+ const classNameRule = {
279
+ meta: {
280
+ type: 'suggestion',
281
+ docs: {
282
+ description: '类名必须使用大驼峰命名法(PascalCase)且优先使用单个单词',
283
+ category: 'Stylistic Issues',
284
+ recommended: true
285
+ },
286
+ schema: [
287
+ {
288
+ type: 'object',
289
+ properties: {
290
+ regex: { type: 'string' },
291
+ min: { type: 'number' },
292
+ max: { type: 'number' },
293
+ message: { type: 'string' },
294
+ single_word_preferred: { type: 'boolean' }
295
+ },
296
+ additionalProperties: false
297
+ }
298
+ ]
299
+ },
300
+ create(context) {
301
+ const options = context.options[0] || {};
302
+ return {
303
+ ClassDeclaration(node) {
304
+ const class_name = node.id.name;
305
+ const detector = new NamingDetector({ 'class-name': options });
306
+ const result = detector.checkName(class_name, 'class-name');
307
+
308
+ if (!result.valid) {
309
+ result.errors.forEach(error => {
310
+ context.report({
311
+ node: node.id,
312
+ message: `类名"${class_name}"不符合规范: ${error}`
313
+ });
314
+ });
315
+ }
316
+ }
317
+ };
318
+ }
319
+ };
320
+
321
+ /**
322
+ * 函数名小驼峰规则
323
+ */
324
+ const functionNameRule = {
325
+ meta: {
326
+ type: 'suggestion',
327
+ docs: {
328
+ description: '函数名必须使用小驼峰命名法(camelCase)且优先使用单个单词',
329
+ category: 'Stylistic Issues',
330
+ recommended: true
331
+ },
332
+ schema: [
333
+ {
334
+ type: 'object',
335
+ properties: {
336
+ regex: { type: 'string' },
337
+ min: { type: 'number' },
338
+ max: { type: 'number' },
339
+ message: { type: 'string' },
340
+ single_word_preferred: { type: 'boolean' }
341
+ },
342
+ additionalProperties: false
343
+ }
344
+ ]
345
+ },
346
+ create(context) {
347
+ const options = context.options[0] || {};
348
+ return {
349
+ FunctionDeclaration(node) {
350
+ const function_name = node.id ? node.id.name : 'anonymous';
351
+ if (function_name !== 'anonymous') {
352
+ const detector = new NamingDetector({ 'function-name': options });
353
+ const result = detector.checkName(function_name, 'function-name');
354
+
355
+ if (!result.valid) {
356
+ result.errors.forEach(error => {
357
+ context.report({
358
+ node: node.id,
359
+ message: `函数名"${function_name}"不符合规范: ${error}`
360
+ });
361
+ });
362
+ }
363
+ }
364
+ },
365
+
366
+ FunctionExpression(node) {
367
+ if (node.id) {
368
+ const function_name = node.id.name;
369
+ const detector = new NamingDetector({ 'function-name': options });
370
+ const result = detector.checkName(function_name, 'function-name');
371
+
372
+ if (!result.valid) {
373
+ result.errors.forEach(error => {
374
+ context.report({
375
+ node: node.id,
376
+ message: `函数表达式名"${function_name}"不符合规范: ${error}`
377
+ });
378
+ });
379
+ }
380
+ }
381
+ }
382
+ };
383
+ }
384
+ };
385
+
386
+ /**
387
+ * 方法名小驼峰规则
388
+ */
389
+ const methodNameRule = {
390
+ meta: {
391
+ type: 'suggestion',
392
+ docs: {
393
+ description: '方法名必须使用小驼峰命名法(camelCase)且优先使用单个单词',
394
+ category: 'Stylistic Issues',
395
+ recommended: true
396
+ },
397
+ schema: [
398
+ {
399
+ type: 'object',
400
+ properties: {
401
+ regex: { type: 'string' },
402
+ min: { type: 'number' },
403
+ max: { type: 'number' },
404
+ message: { type: 'string' },
405
+ single_word_preferred: { type: 'boolean' }
406
+ },
407
+ additionalProperties: false
408
+ }
409
+ ]
410
+ },
411
+ create(context) {
412
+ const options = context.options[0] || {};
413
+ return {
414
+ MethodDefinition(node) {
415
+ const method_name = node.key.name;
416
+ const detector = new NamingDetector({ 'method-name': options });
417
+ const result = detector.checkName(method_name, 'method-name');
418
+
419
+ if (!result.valid) {
420
+ result.errors.forEach(error => {
421
+ context.report({
422
+ node: node.key,
423
+ message: `方法名"${method_name}"不符合规范: ${error}`
424
+ });
425
+ });
426
+ }
427
+ }
428
+ };
429
+ }
430
+ };
431
+
432
+ /**
433
+ * 变量名小写蛇形规则
434
+ */
435
+ const variableNameRule = {
436
+ meta: {
437
+ type: 'suggestion',
438
+ docs: {
439
+ description: '变量名必须使用小写蛇形命名法(snake_case)',
440
+ category: 'Stylistic Issues',
441
+ recommended: true
442
+ },
443
+ schema: [
444
+ {
445
+ type: 'object',
446
+ properties: {
447
+ regex: { type: 'string' },
448
+ min: { type: 'number' },
449
+ max: { type: 'number' },
450
+ message: { type: 'string' },
451
+ single_word_preferred: { type: 'boolean' }
452
+ },
453
+ additionalProperties: false
454
+ }
455
+ ]
456
+ },
457
+ create(context) {
458
+ const options = context.options[0] || {};
459
+ return {
460
+ VariableDeclarator(node) {
461
+ if (node.id.type === 'Identifier') {
462
+ const variable_name = node.id.name;
463
+ const detector = new NamingDetector({ 'variable-name': options });
464
+ const result = detector.checkName(variable_name, 'variable-name');
465
+
466
+ if (!result.valid) {
467
+ result.errors.forEach(error => {
468
+ context.report({
469
+ node: node.id,
470
+ message: `变量名"${variable_name}"不符合规范: ${error}`
471
+ });
472
+ });
473
+ }
474
+ }
475
+ }
476
+ };
477
+ }
478
+ };
479
+
480
+ /**
481
+ * 常量名大写蛇形规则
482
+ */
483
+ const constantNameRule = {
484
+ meta: {
485
+ type: 'suggestion',
486
+ docs: {
487
+ description: '常量名必须使用大写蛇形命名法(UPPER_SNAKE_CASE)',
488
+ category: 'Stylistic Issues',
489
+ recommended: true
490
+ },
491
+ schema: [
492
+ {
493
+ type: 'object',
494
+ properties: {
495
+ regex: { type: 'string' },
496
+ min: { type: 'number' },
497
+ max: { type: 'number' },
498
+ message: { type: 'string' },
499
+ single_word_preferred: { type: 'boolean' }
500
+ },
501
+ additionalProperties: false
502
+ }
503
+ ]
504
+ },
505
+ create(context) {
506
+ const options = context.options[0] || {};
507
+ return {
508
+ VariableDeclarator(node) {
509
+ if (node.id.type === 'Identifier' && node.parent.kind === 'const') {
510
+ const constant_name = node.id.name;
511
+ const detector = new NamingDetector({ 'constant-name': options });
512
+ const result = detector.checkName(constant_name, 'constant-name');
513
+
514
+ if (!result.valid) {
515
+ result.errors.forEach(error => {
516
+ context.report({
517
+ node: node.id,
518
+ message: `常量名"${constant_name}"不符合规范: ${error}`
519
+ });
520
+ });
521
+ }
522
+ }
523
+ }
524
+ };
525
+ }
526
+ };
527
+
528
+ /**
529
+ * 私有成员命名规则
530
+ */
531
+ const privateNamingRule = {
532
+ meta: {
533
+ type: 'suggestion',
534
+ docs: {
535
+ description: '私有成员必须以单下划线开头,后跟小写蛇形命名',
536
+ category: 'Stylistic Issues',
537
+ recommended: true
538
+ },
539
+ schema: [
540
+ {
541
+ type: 'object',
542
+ properties: {
543
+ regex: { type: 'string' },
544
+ min: { type: 'number' },
545
+ max: { type: 'number' },
546
+ message: { type: 'string' },
547
+ single_word_preferred: { type: 'boolean' }
548
+ },
549
+ additionalProperties: false
550
+ }
551
+ ]
552
+ },
553
+ create(context) {
554
+ const options = context.options[0] || {};
555
+ return {
556
+ MethodDefinition(node) {
557
+ const method_name = node.key.name;
558
+ if (method_name.startsWith('_')) {
559
+ const detector = new NamingDetector({ 'private-naming': options });
560
+ const result = detector.checkName(method_name, 'private-naming');
561
+
562
+ if (!result.valid) {
563
+ result.errors.forEach(error => {
564
+ context.report({
565
+ node: node.key,
566
+ message: `私有方法名"${method_name}"不符合规范: ${error}`
567
+ });
568
+ });
569
+ }
570
+ }
571
+ },
572
+
573
+ Property(node) {
574
+ if (node.key.type === 'Identifier' && node.key.name.startsWith('_')) {
575
+ const private_name = node.key.name;
576
+ const detector = new NamingDetector({ 'private-naming': options });
577
+ const result = detector.checkName(private_name, 'private-naming');
578
+
579
+ if (!result.valid) {
580
+ result.errors.forEach(error => {
581
+ context.report({
582
+ node: node.key,
583
+ message: `私有属性名"${private_name}"不符合规范: ${error}`
584
+ });
585
+ });
586
+ }
587
+ }
588
+ }
589
+ };
590
+ }
591
+ };
592
+
593
+ /**
594
+ * 命名规范ESLint插件
595
+ */
596
+ const namingRules = {
597
+ 'class-name': classNameRule,
598
+ 'function-name': functionNameRule,
599
+ 'method-name': methodNameRule,
600
+ 'variable-name': variableNameRule,
601
+ 'constant-name': constantNameRule,
602
+ 'private-naming': privateNamingRule
603
+ };
604
+
605
+ module.exports = {
606
+ NamingDetector,
607
+ rules: namingRules
608
+ };
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "mm_eslint",
3
+ "version": "1.0.1",
4
+ "description": "ESLint plugin for naming conventions - PascalCase, camelCase, snake_case, and UPPER_SNAKE_CASE naming rules",
5
+ "main": "index.js",
6
+ "keywords": [
7
+ "eslint",
8
+ "eslintplugin",
9
+ "eslint-plugin",
10
+ "naming-convention",
11
+ "naming-rules",
12
+ "coding-standards",
13
+ "pascalcase",
14
+ "camelcase",
15
+ "snake-case",
16
+ "code-quality"
17
+ ],
18
+ "author": "qww",
19
+ "license": "ISC",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "https://gitee.com/qiuwenwu91/mm_eslint.git"
23
+ },
24
+ "homepage": "https://gitee.com/qiuwenwu91/mm_eslint",
25
+ "bugs": {
26
+ "url": "https://gitee.com/qiuwenwu91/mm_eslint/issues"
27
+ },
28
+ "engines": {
29
+ "node": ">=12.0.0"
30
+ },
31
+ "peerDependencies": {
32
+ "eslint": ">=8.0.0"
33
+ },
34
+ "scripts": {
35
+ "test": "node test.js",
36
+ "lint": "npx eslint . --config eslint.config.js"
37
+ },
38
+ "files": [
39
+ "index.js",
40
+ "README.md",
41
+ "README_EN.md",
42
+ "LICENSE"
43
+ ]
44
+ }