-
-
Notifications
You must be signed in to change notification settings - Fork 681
/
Copy pathdefine-props-declaration.js
305 lines (275 loc) · 7.61 KB
/
define-props-declaration.js
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/**
* @author Amorites
* See LICENSE file in root directory for full license.
*/
'use strict'
const utils = require('../utils')
const PROPS_SEPARATOR = ', '
/**
* @param {RuleFixer} fixer
* @param {CallExpression} node
* @param {ComponentProp[]} props
* @param {RuleContext} context
*/
function* fixTypeBased(fixer, node, props, context) {
try {
const sourceCode = context.getSourceCode()
const autoFixToSeparateInterface =
context.options[1]?.autoFixToSeparateInterface || false
const componentPropsData = props.map((prop) =>
getComponentPropData(prop, sourceCode)
)
const componentPropsTypes = componentPropsData.map(
({ name, type, required, defaultValue }) => {
const isOptional = required === false || defaultValue
return `${name}${isOptional ? '?' : ''}: ${type}`
}
)
const componentPropsTypeCode = `{${componentPropsTypes.join(PROPS_SEPARATOR)}}`
// remove defineProps function parameters
yield fixer.replaceText(node.arguments[0], '')
// add type annotation
if (autoFixToSeparateInterface) {
const variableDeclarationNode = node.parent.parent
if (!variableDeclarationNode) {
return
}
yield fixer.insertTextBefore(
variableDeclarationNode,
`interface Props ${componentPropsTypeCode.replace(/;/g, ',')}; `
)
yield fixer.insertTextAfter(node.callee, `<Props>`)
} else {
yield fixer.insertTextAfter(node.callee, `<${componentPropsTypeCode}>`)
}
// add defaults if needed
const propTypesDataWithDefaultValue = componentPropsData.filter(
({ defaultValue }) => defaultValue
)
if (propTypesDataWithDefaultValue.length > 0) {
const defaultsCode = propTypesDataWithDefaultValue
.map(
({ name, defaultValue }) =>
`${name}: ${sourceCode.getText(defaultValue)}`
)
.join(PROPS_SEPARATOR)
yield fixer.insertTextBefore(node, `withDefaults(`)
yield fixer.insertTextAfter(node, `, { ${defaultsCode} })`)
}
return null
} catch (error) {
return null
}
}
const mapNativeType = (/** @type {string} */ nativeType) => {
switch (nativeType) {
case 'String': {
return 'string'
}
case 'Number': {
return 'number'
}
case 'Boolean': {
return 'boolean'
}
case 'Object': {
return 'Record<string, any>'
}
case 'Array': {
return 'any[]'
}
case 'Function': {
return '(...args: any[]) => any'
}
case 'Symbol': {
return 'symbol'
}
default: {
return nativeType
}
}
}
/**
* @param {ComponentProp} prop
* @param {SourceCode} sourceCode
*/
function getComponentPropData(prop, sourceCode) {
if (prop.propName === null) {
throw new Error('Unexpected prop with null name.')
}
if (prop.type !== 'object') {
throw new Error(`Unexpected prop type: ${prop.type}.`)
}
const type = optionGetType(prop.value, sourceCode)
const required = optionGetRequired(prop.value)
const defaultValue = optionGetDefault(prop.value)
return {
name: prop.propName,
type,
required,
defaultValue
}
}
/**
* @param {Expression} node
* @param {SourceCode} sourceCode
* @returns {string}
*/
function optionGetType(node, sourceCode) {
switch (node.type) {
case 'Identifier': {
return mapNativeType(node.name)
}
case 'ObjectExpression': {
const typeProperty = utils.findProperty(node, 'type')
if (typeProperty == null) {
return sourceCode.getText(node)
}
return optionGetType(typeProperty.value, sourceCode)
}
case 'ArrayExpression': {
return node.elements
.map((element) => {
// TODO handle SpreadElement
if (element === null || element.type === 'SpreadElement') {
return sourceCode.getText(node)
}
return optionGetType(element, sourceCode)
})
.filter(Boolean)
.join(' | ')
}
case 'TSAsExpression': {
const typeAnnotation = node.typeAnnotation
if (typeAnnotation.typeName.name !== 'PropType') {
return sourceCode.getText(node)
}
// in some project configuration parser populates deprecated field `typeParameters` instead of `typeArguments`
const typeArguments =
'typeArguments' in node
? typeAnnotation.typeArguments
: typeAnnotation.typeParameters
const typeArgument = Array.isArray(typeArguments)
? typeArguments[0].params[0]
: typeArguments.params[0]
if (typeArgument === undefined) {
return sourceCode.getText(node)
}
return sourceCode.getText(typeArgument)
}
case 'LogicalExpression': {
if (node.operator === '||') {
const left = optionGetType(node.left, sourceCode)
const right = optionGetType(node.right, sourceCode)
if (left && right) {
return `${left} | ${right}`
}
}
return sourceCode.getText(node)
}
default: {
return sourceCode.getText(node)
}
}
}
/**
* @param {Expression} node
* @returns {boolean | undefined }
*/
function optionGetRequired(node) {
if (node.type === 'ObjectExpression') {
const requiredProperty = utils.findProperty(node, 'required')
if (requiredProperty == null) {
return false
}
if (requiredProperty.value.type === 'Literal') {
return Boolean(requiredProperty.value.value)
}
}
// Unknown
return false
}
/**
* @param {Expression} node
* @returns {Expression | undefined }
*/
function optionGetDefault(node) {
if (node.type === 'ObjectExpression') {
const defaultProperty = utils.findProperty(node, 'default')
if (defaultProperty == null) {
return undefined
}
return defaultProperty.value
}
// Unknown
return undefined
}
/**
* @typedef {import('../utils').ComponentProp} ComponentProp
*/
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'enforce declaration style of `defineProps`',
categories: undefined,
url: 'https://eslint.vuejs.org/rules/define-props-declaration.html'
},
fixable: 'code',
schema: [
{
enum: ['type-based', 'runtime']
},
{
type: 'object',
properties: {
autoFixToSeparateInterface: {
type: 'boolean',
default: false
}
}
}
],
messages: {
hasArg: 'Use type-based declaration instead of runtime declaration.',
hasTypeArg: 'Use runtime declaration instead of type-based declaration.'
}
},
/** @param {RuleContext} context */
create(context) {
const scriptSetup = utils.getScriptSetupElement(context)
if (!scriptSetup || !utils.hasAttribute(scriptSetup, 'lang', 'ts')) {
return {}
}
const defineType = context.options[0] || 'type-based'
return utils.defineScriptSetupVisitor(context, {
onDefinePropsEnter(node, props) {
switch (defineType) {
case 'type-based': {
if (node.arguments.length > 0) {
context.report({
node,
messageId: 'hasArg',
*fix(fixer) {
yield* fixTypeBased(fixer, node, props, context)
}
})
}
break
}
case 'runtime': {
const typeArguments =
'typeArguments' in node ? node.typeArguments : node.typeParameters
if (typeArguments && typeArguments.params.length > 0) {
context.report({
node,
messageId: 'hasTypeArg'
})
}
break
}
}
}
})
}
}